@smartkomm/plexus-cli 0.1.156 → 0.1.157
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/cli.mjs +3 -3
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -11203,7 +11203,7 @@ The link is valid for {{gueltigkeit}} and works once. Afterwards you are signed
|
|
|
11203
11203
|
|
|
11204
11204
|
{{einstellungenLink}}`,en:`Open Plexus and, in the user menu, \u201CSettings\u201D \u2192 \u201CSignature\u201D:
|
|
11205
11205
|
|
|
11206
|
-
{{einstellungenLink}}`}}]},rw=[jW,WW,JW,QW,ZW,r1,n1,E1,$1,M1,K1,V1,G1,Y1,J1,X1,n2,o2,a2,R1,I1,O1,l2,d2,c2,i1,o1,l1,d1,f1,h1,w1,S1,D1,O2,N2,BW,GW,f2,m2,g2,w2,v2,S2,E2];function iw(e){let t=rw.find(n=>n.id===e);return t===void 0&&F(`notifications: unknown letter "${e}"`),t}s(iw,"letterDefFor");function ow(e){return rw.some(t=>t.id===e)}s(ow,"hasLetterDef");function sw(e,t){return t===void 0?!0:xf(e,t)}s(sw,"letterArgCompatible");function _l(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${bn(e)} (${e})`,en:`${bn(e)} (${e})`}}s(_l,"letterArgTypeLabel");function b_(e){let t=new Map,n=s((r,i)=>{let o=t.get(r);o===void 0?t.set(r,[i]):o.push(i)},"add");for(let r of e.args)n(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of o_)n(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return t}s(b_,"eventArgSources");function v_(e,t){let n=e.type===void 0?[...t]:t.filter(r=>sw(r.type,e.type));if(n.length>1)return{status:"ambiguous",matches:n};if(n.length===1){let r=n[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...t]}:{status:"unused"}}s(v_,"resolveLetterParam");var aw=["booked","rescheduled","cancelled"],C2={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},S_=":";function A_(e,t){return`${e}${S_}${t}`}s(A_,"appointmentEventId");function P2(e){let t=e.lastIndexOf(S_);if(t<=0)return null;let n=e.slice(t+1);return aw.includes(n)?{taskKey:e.slice(0,t),kind:n}:null}s(P2,"parseAppointmentEventId");var x_={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function Js(e){return Array.isArray(e.tasks)?e.tasks.filter(t=>typeof t?.key=="string"&&t.result?.kind==="appointment"):[]}s(Js,"appointmentTasksOf");function D2(e){return aw.map(t=>({id:A_(e.key,t),label:{de:`${x_[t].de} \u2013 \u201E${e.title.de}\u201C`,en:`${x_[t].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(D2,"appointmentTaskEvents");function E_(e,t){let n=t.notificationEvents?.(e)??[],r=Js(e).flatMap(D2);return r.length===0?n:[...n,...r]}s(E_,"nodeNotificationEvents");function F2(e){return Object.fromEntries(aw.map(t=>[A_(e,t),{templateId:C2[t]}]))}s(F2,"defaultAppointmentBindings");function L2(e,t){if(e===void 0)return{notifications:e,dropped:[]};let n=[],r={};for(let[i,o]of Object.entries(e))P2(i)?.taskKey===t?n.push(i):r[i]=o;return n.length===0?{notifications:e,dropped:n}:{notifications:Object.keys(r).length===0?void 0:r,dropped:n}}s(L2,"withoutAppointmentBindings");function Vf(e,t,n){let r=new Set(Js(t).map(d=>d.key)),i=new Set(Js(n).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=L2(o,d);o=c.notifications,a.push(...c.dropped)}let l=[];for(let d of i)if(!r.has(d))for(let[c,u]of Object.entries(F2(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(Vf,"syncAppointmentBindings");function M2(e){return e.kind==="task"&&!("title"in e)}s(M2,"isLegacyFreeTodoContext");function lw(e){let{context:t}=e;if(M2(t)&&F(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),t.kind==="task")return{...e,context:t,kind:"task",createdVia:"human",partyId:t.partyId};let{anchor:n,task:r,kind:i,title:o,description:a,...l}=t,d=n.scope==="node"?{nodeId:n.nodeId,templateKey:n.templateKey,gatesNode:n.gatesNode,blocks:n.blocks}:n.scope==="application"?{scope:"application",templateKey:n.templateKey}:n.scope==="crossNode"?{scope:"application",nodeId:n.nodeId,templateKey:n.templateKey,blocks:n.blocks}:{};return{...e,context:t,...l,...d,...r??{},kind:i}}s(lw,"readWorkItem");async function Nl(e,t){let n;if(t.nodeId!==void 0){let r=t.nodeId;n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(t.isOpen!==void 0){let r=t.isOpen;n=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",t.applicationId).eq("isOpen",r)).collect()}else n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",t.applicationId)).collect();return n.filter(r=>t.isOpen===void 0||r.isOpen===t.isOpen).map(lw)}s(Nl,"listWorkItemsForApplication");var cpe=m.union(m.literal("approved"),m.literal("rejected")),Cl=new Set(["task","approval"]);function q2(e,t){switch(e){case"task":return t?.gatesNode===!0&&F("expandComposedTask: gatesNode is approval-only \u2014 a 'task' template never gates its node (use blocks to hold a gating sibling back)"),{kind:"task",recipient:"internal",gatesNode:!1};case"approval":return{kind:"approval",recipient:"internal",isApproval:!0,gatesNode:t?.gatesNode??!0};default:F(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Cl].join(", ")}`)}}s(q2,"expandComposedTask");for(let e of["task","approval"]){let t=q2(e);t.kind==="approval"!=(t.isApproval===!0)&&F(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var T_=Ri,qi=`${T_}.`,K2=new Set(["text","number","date","boolean","option","edge"]);function Bf(e,t){let n=e[t];return n===void 0&&F(`[env/unknownKey] no environment key '${t}'`),typeof n=="string"?null:Object.keys(n)}s(Bf,"contextFields");function $_(e,t){return Object.hasOwn(e,t)}s($_,"isContextKey");function R_(e){let t=[];for(let n of Object.keys(e)){let r=Bf(e,n);if(r===null)t.push(n);else for(let i of r)t.push(`${n}.${i}`)}return t}s(R_,"leafPaths");function Pl(e,t){let[n="",r,...i]=t.split(".");if(!$_(e,n)||i.length>0)return;let o=e[n];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Pl,"leafType");function I_(e){let t=new Set;for(let n of e){let r=Qs(n);r!==null&&t.add(r.split(".")[0])}return[...t]}s(I_,"contextKeysOf");function Qs(e){return e.startsWith(qi)?e.slice(qi.length):null}s(Qs,"contextPathOf");function Dl(e){return e===T_||e.startsWith(qi)}s(Dl,"isContextIdentifier");function Uf(e,t){let n=Qs(t)??"",[r=""]=n.split("."),i=Object.keys(e);if(!$_(e,r))return{code:"env/unknownKey",message:{de:`'${t}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${t}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Pl(e,n)!==void 0)return null;let o=Bf(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${t}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${qi}${r}'.`,en:`'${t}': environment key '${r}' is a single value \u2014 read it as '${qi}${r}'.`}:{de:`'${t}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${t}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s(Uf,"identifierIssue");function Gf(e,t,n=Object.keys(e)){let r={};for(let i of n){let o=Bf(e,i),a=Object.hasOwn(t,i)?t[i]:void 0;if(a===void 0&&F(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${qi}${i}`]=a;continue}for(let l of o){let d=typeof a=="object"&&a!==null&&Object.hasOwn(a,l)?a[l]:void 0;d===void 0&&F(`[env/missing] context key '${i}' carries no '${l}'`),r[`${qi}${i}.${l}`]=d}}return r}s(Gf,"flatten");function O_(e,t,n){if(n===void 0)return!1;let r=Bf(e,t);return r===null?!0:typeof n=="object"&&n!==null&&r.every(i=>n[i]!==void 0)}s(O_,"contextValueComplete");function j2(e,t){switch(t){case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e);default:return typeof e=="string"}}s(j2,"valueMatchesDataType");function __(e,t,n=Object.keys(e.types)){let r=new Set(n);for(let i of R_(e.types)){if(!r.has(i.split(".")[0]))continue;let o=t[`${qi}${i}`];o===void 0&&F(`[env/missing] context path '${i}' was not supplied`);let a=e.fields[i];if(o===null){a.nullable||F(`[env/null] context path '${i}' is not nullable but carries null`);continue}let l=bn(Pl(e.types,i));j2(o,l)||F(`[env/type] context path '${i}' expects ${l}, got ${JSON.stringify(o)}`),a.valueSet.kind==="fixed"&&!a.valueSet.values.includes(o)&&F(`[env/value] context path '${i}' carries '${String(o)}', outside ${a.valueSet.values.join(" | ")}`)}}s(__,"assertContextValues");function V2(e){let t=[],n=R_(e.types);for(let r of n){let i=Pl(e.types,r),o=bn(i);if(!Ci(i)||o===void 0||!K2.has(o)){t.push(`'${r}' has type '${String(i)}', not a scalar value type`);continue}let a=Object.hasOwn(e.fields,r)?e.fields[r]:void 0;if(a===void 0){t.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&t.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&t.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))n.includes(r)||t.push(`field spec '${r}' names no leaf of the schema`);return t}s(V2,"schemaIssues");function Zs(e){let t=V2(e);t.length>0&&F(`[env/schema] ${t.join("; ")}`)}s(Zs,"assertSchema");var zf={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function Ki(e){return JSON.stringify(e)}s(Ki,"canonical");function ea(e){return e.kind==="binary"&&e.op==="&&"?[...ea(e.left),...ea(e.right)]:[e]}s(ea,"conjuncts");function P_(e,t){let n;try{n=Rt(e)}catch{return!1}let r=Ki(Rt(t));return ea(n).some(i=>Ki(i)===r)}s(P_,"hasConjunct");function D_(e,t){try{return Ki(Rt(e))===Ki(Rt(t))}catch{return!1}}s(D_,"sameCondition");function F_(e){let t=[];for(let n of e)t.push(...It(ei(n)));return I_(t)}s(F_,"contextKeysRead");function L_(e){try{return It(Rt(e)).some(Dl)}catch{return!1}}s(L_,"readsContext");var B2=/^\d{4}-\d{2}-\d{2}$/,U2=new Set(["==","!=","<","<=",">",">=","in"]),G2=new Set(["<","<=",">",">="]);function Yf(e,t,n=[]){Zs(t);let r;try{r=Rt(e)}catch(a){let l=a.message;return[Ut("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of It(r)){if(!Dl(a)){i.push(Ut("condition/foreignIdentifier",`'${a}' ist kein Umgebungswert \u2014 Bedingungen lesen nur '$env.*'`,`'${a}' is not a context identifier \u2014 conditions read only '$env.*'`));continue}let l=Uf(t.types,a);l!==null&&i.push(Ut("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Dr(r,t,i);Fl(o)||i.push(Ut("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),H2(r,t,i);for(let{identifier:a,op:l}of uw(r,t))i.push(Ut("condition/unguardedNullable",`'${l}' \xFCber '${a}', das leer sein kann, braucht davor eine Absicherung '${a} != null &&'`,`'${l}' over '${a}', which may be null, needs a guard '${a} != null &&' before it`));return i.push(...z2(r,n)),i}s(Yf,"conditionIssues");function z2(e,t){let n=ea(e).map(Ki);return t.flatMap(r=>{let i=Rt(r),o=W2(i);return o===null||!n.includes(Ki(o))?[]:[{severity:"info",code:"condition/guardForm",message:{de:`[condition/guardForm] eine gespiegelte Absicherung z\xE4hlt nicht \u2014 schreibe sie genau als '${r}'`,en:`[condition/guardForm] a mirrored guard does not count \u2014 write it exactly as '${r}'`}}]})}s(z2,"guardFormHints");function W2(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let t={...e,left:e.right,right:e.left};return Ki(t)===Ki(e)?null:t}s(W2,"mirror");function Fl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Fl,"isBooleanish");function M_(e){let t=Qs(e);return t===null&&F(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),t}s(M_,"contextPath");function q_(e,t){let n=Qs(t);return n!==null&&e.fields[n]?.nullable===!0}s(q_,"isNullableLeaf");function Y2(e,t){let n=bn(Pl(e.types,M_(t)));return n===void 0?{t:"unknown"}:{t:"data",dt:n}}s(Y2,"identType");function Wf(e,t){return e.t==="unknown"||t.t==="unknown"||e.t==="null"||t.t==="null"?!0:e.t==="array"||t.t==="array"?!1:e.t==="str"&&t.t==="str"?!0:e.t==="str"?N_(e.value,t.dt):t.t==="str"?N_(t.value,e.dt):e.dt===t.dt}s(Wf,"fits");function N_(e,t){return t==="text"||t==="option"||t==="edge"?!0:t==="date"?B2.test(e):!1}s(N_,"strFits");function C_(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(C_,"orderedCategory");function Dr(e,t,n){switch(e.kind){case"num":return{t:"data",dt:"number"};case"bool":return{t:"data",dt:"boolean"};case"str":return{t:"str",value:e.value};case"null":return{t:"null"};case"ident":return Y2(t,e.path);case"arr":for(let r of e.items)Dr(r,t,n);return{t:"array"};case"unary":{let r=Dr(e.operand,t,n);return Fl(r)||n.push(Ut("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(zf,e.name)?zf[e.name]:void 0,i=e.args.map(l=>Dr(l,t,n));return r===void 0?(n.push(Ut("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(zf).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(zf).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&Wf(l,{t:"data",dt:r.params[d]}))||n.push(Ut("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Dr(e.cond,t,n);Fl(r)||n.push(Ut("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Dr(e.then,t,n),o=Dr(e.else,t,n);return Wf(i,o)||n.push(Ut("condition/typeMismatch","die beiden Zweige von 'if' haben verschiedene Typen","the two arms of 'if' differ in type")),i.t==="null"?o:i}case"binary":{let r=Dr(e.left,t,n),i=Dr(e.right,t,n);if(e.op==="&&"||e.op==="||")(!Fl(r)||!Fl(i))&&n.push(Ut("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?n.push(Ut("condition/inWithoutArray","'in' braucht rechts eine Liste, z. B. ['a', 'b']","'in' needs a list on its right, e.g. ['a', 'b']")):e.right.items.every(o=>Wf(r,Dr(o,t,[])))||n.push(Ut("condition/typeMismatch","ein Listeneintrag von 'in' passt nicht zum Typ des linken Operanden","a list item of 'in' does not match the left operand's type"));else if(G2.has(e.op)){let o=C_(r),a=C_(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&n.push(Ut("condition/orderedComparison",`'${e.op}' vergleicht nur Zahlen \u2014 f\xFCr Daten years_between(\u2026) verwenden`,`'${e.op}' compares only numbers \u2014 for dates use years_between(\u2026)`))}else Wf(r,i)||n.push(Ut("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Dr,"typeOf");function dw(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(dw,"isLiteral");function K_(e){let t=[],n=s(r=>{if(r.kind==="binary"&&U2.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(dw):dw(r.right)?[r.right]:[];i.length>0&&t.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&dw(r.left)&&t.push({ident:r.right.path,literals:[r.left]})}j_(r,n)},"visit");return n(e),t}s(K_,"comparedLiterals");function H2(e,t,n){for(let{ident:r,literals:i}of K_(e)){let o=J2(r,i,t);o!==null&&n.push(o)}}s(H2,"literalIssues");function cw(e,t){let n;try{n=Rt(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of K_(n)){let a=Qs(i);if(!(a===null||t.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(cw,"liveLiterals");function J2(e,t,n){let r=n.fields[M_(e)]?.valueSet;if(r?.kind==="unstable")return Ut("condition/literalOnUnstable",`'${e}' ist nicht \xFCber Umgebungen stabil \u2014 vergleiche ihn mit keinem festen Wert; verzweige stattdessen \xFCber ein stabiles Merkmal`,`'${e}' is not stable across environments \u2014 compare it to no literal; branch on a stable attribute instead`);if(r?.kind!=="fixed")return null;let i=t.flatMap(a=>a.kind==="str"&&!r.values.includes(a.value)?[`'${a.value}'`]:[]);if(i.length===0)return null;let o=r.values.map(a=>`'${a}'`).join(", ");return Ut("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(J2,"valueSetIssue");function j_(e,t){switch(e.kind){case"binary":t(e.left),t(e.right);return;case"unary":t(e.operand);return;case"call":e.args.forEach(t);return;case"arr":e.items.forEach(t);return;case"if":t(e.cond),t(e.then),t(e.else);return;default:return}}s(j_,"forEachChild");function V_(e){return e.kind==="binary"&&(e.op==="=="||e.op==="!=")&&(e.left.kind==="ident"&&e.right.kind==="null"||e.left.kind==="null"&&e.right.kind==="ident")}s(V_,"isNullTest");function B_(e){return ea(e).flatMap(t=>{let n=U_(t);return n===null?[]:[n]})}s(B_,"guardsOf");function Ll(e,t,n){switch(e.kind){case"ident":return q_(t,e.path)&&!n.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=Ll(r,t,n);if(i!==null)return i}return null;case"if":return Ll(e.then,t,new Set([...n,...B_(e.cond)]))??Ll(e.else,t,n);default:return null}}s(Ll,"unguardedNullSource");function U_(e){return!V_(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(U_,"guardedIdent");function Xs(e,t,n,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(n);for(let o of ea(e)){Xs(o,t,i,r);let a=U_(o);a!==null&&i.add(a)}return}if(e.kind==="if"){Xs(e.cond,t,n,r),Xs(e.then,t,new Set([...n,...B_(e.cond)]),r),Xs(e.else,t,n,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=Ll(e.left,t,n)??Ll(e.right,t,n);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!V_(e.operand)){let i=It(e.operand).filter(o=>q_(t,o)&&!n.has(o));i.length>0&&r(i[0],"!")}j_(e,i=>Xs(i,t,n,r))}s(Xs,"nullableReads");function uw(e,t){Zs(t);let n=[];return Xs(e,t,new Set,(r,i)=>{n.some(o=>o.identifier===r)||n.push({identifier:r,op:i})}),n}s(uw,"unguardedNullableReads");function Ut(e,t,n){return{severity:"error",code:e,message:{de:`[${e}] ${t}`,en:`[${e}] ${n}`}}}s(Ut,"error");function Ml(e){let t=Array.isArray(e.nodes)?e.nodes:[],n=new Set;for(let r of t)for(let i of Rf(r))i.key!==null&&qs[i.leaf].involves&&n.add(i.key);return n}s(Ml,"declaredGroupKeys");var ta=of;var Q2="unit.key",Z2="offer.key";function G_(e,t){return e===Q2?t.unitKeys:e===Z2?t.offerKeys:null}s(G_,"liveKeyUniverse");function Hf(e){return[ht,...[...Ml(e)].sort((t,n)=>t.localeCompare(n)).map(ff)]}s(Hf,"requiredSlots");var ji=`${af("applicant.channel")} == 'staff'`;var pw=["strict","leastLoaded"];var fw=2;function z_(e){return e.some(t=>t.length===0)?{de:"nennt einen leeren Personenschl\xFCssel",en:"names an empty person key"}:new Set(e).size!==e.length?{de:"nennt eine Person zweimal",en:"names a person twice"}:e.length<fw?{de:`braucht mindestens ${fw} Personen`,en:`needs at least ${fw} people`}:null}s(z_,"rotationPoolProblem");function X2(e,t){let n=t===null?-1:e.indexOf(t);return[...e.slice(n+1),...e.slice(0,n+1)]}s(X2,"strictOrder");function W_(e){let t=X2(e.pool,e.previous).filter(i=>e.eligible.has(i));if(t.length===0)return null;if(e.mode==="strict")return t[0];let n=e.openCounts;n===void 0&&F("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=n.get(i);return o===void 0&&F(`[assignment/rotation] no open count for '${i}'`),o},"load");return t.reduce((i,o)=>r(o)<r(i)?o:i)}s(W_,"pickFromPool");function H_(e){return e.map(t=>({slot:pI(t.slot),rules:[...t.rules]}))}s(H_,"rulesOfStored");function J_(e){return e.map(t=>({slot:eY(t.slot),rules:[...t.rules]}))}s(J_,"storedOfRules");function eY(e){let t=mf(e);return t===null&&F(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),t}s(eY,"slotOf");function Q_(e,t){let n=e?.assignmentRules;n===void 0&&F(`[assignment/noRules] ${t}: the workflow has no assignment rule`);let r=tN(n);return r.length>0&&F(`${r.join("; ")} (${t})`),H_(n)}s(Q_,"rulesOfGraph");function tY(e){return e===ht?{slot:e,rules:[{when:ji,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(tY,"defaultSlotRules");function Z_(e,t){let n=new Set(e.map(o=>o.slot)),r=t.filter(o=>!n.has(o)).map(tY);return[...r.filter(o=>o.slot===ht),...e,...r.filter(o=>o.slot!==ht)]}s(Z_,"withRequiredSlots");function _t(e,t){return t===void 0?`slot '${e}'`:`slot '${e}' row #${t+1}`}s(_t,"where");function Cn(e,t){return t===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${t+1}`}s(Cn,"whereDe");function vn(e,t,n={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${t.de}`,en:`[${e}] ${t.en}`},...n}}s(vn,"issue");function Y_(e){if(e===ht)return!0;let t=pf(e);return t!==null&&t.length>0}s(Y_,"isKnownSlot");function nY(e,t){Zs(ta);let n=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;Y_(l)||n.push(vn("assignment/unknownSlot",{de:`'${l}' ist keine Liste \u2014 'responsible' oder 'team:<teamKey>'`,en:`'${l}' is no slot \u2014 'responsible' or 'team:<teamKey>'`},{slot:l})),r.has(l)&&n.push(vn("assignment/duplicateSlot",{de:`${Cn(l)} steht zweimal da`,en:`${_t(l)} is listed twice`},{slot:l})),r.add(l),l===ht&&a!==0&&n.push(vn("assignment/responsibleFirst",{de:`'${ht}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${ht}' must be the first slot \u2014 team rows copy it`},{slot:l})),n.push(...rY(o))});for(let o of t)r.has(o)||n.push(vn("assignment/slotMissing",{de:`${Cn(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${_t(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(t);for(let{slot:o}of e)o!==ht&&!i.has(o)&&Y_(o)&&n.push(vn("assignment/unusedSlot",{de:`${Cn(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${_t(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return n}s(nY,"validateRules");function rY({slot:e,rules:t}){let n=[];return(t.length===0||t[t.length-1].when!==null)&&n.push(vn("assignment/defaultRowMissing",{de:`${Cn(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${_t(e)} must end with a row without condition ("otherwise")`},{slot:e})),t.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<t.length-1&&n.push(vn("assignment/ruleAfterDefault",{de:`${Cn(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${_t(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=Yf(a,ta,[ji]);for(let c of d)n.push({...c,message:{de:`${c.message.de} (${Cn(e,i)})`,en:`${c.message.en} (${_t(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){L_(a)||n.push(vn("assignment/shadowedRule",{de:`${Cn(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${_t(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=t.slice(0,i).findIndex(u=>u.when!==null&&D_(u.when,a));c!==-1&&n.push(vn("assignment/shadowedRule",{de:`${Cn(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${_t(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===ht&&l.kind==="slot"&&n.push(vn("assignment/slotForwardRef",{de:`${Cn(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${ht}'`,en:`${_t(e,i)} copies '${l.slot}' \u2014 only a team slot after '${ht}' may`},o)),e===ht&&l.kind==="queue"&&n.push(vn("assignment/queueOnProcessSlot",{de:`${Cn(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${_t(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&n.push(vn("assignment/targetMissing",{de:`${Cn(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${_t(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=z_(l.configKeys);d!==null&&n.push(vn("assignment/rotationPool",{de:`${Cn(e,i)}: die Reihum-Liste ${d.de}`,en:`${_t(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!P_(a,ji))&&n.push(vn("assignment/unguardedTarget",{de:`${Cn(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${ji}' ist (oder enth\xE4lt)`,en:`${_t(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${ji}'`},o))}),n}s(rY,"rowIssues");function X_(e,t){for(let r of t)e.some(i=>i.slot===r)||F(`[assignment/slotMissing] ${_t(r)} has no rule list`);let n=new Set(t);return e.filter(r=>n.has(r.slot))}s(X_,"selectSlots");function iY(e,t){return F_(X_(e,t).flatMap(n=>n.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(iY,"contextKeysOfRules");function eN(e,t,n,r){Zs(ta);let i=X_(e,n),o=iY(e,n),a=Gf(ta.types,t,o);__(ta,a,o);let l=[];for(let{slot:d,rules:c}of i){let u=c.findIndex((h,w)=>{if(h.when===null)return!0;for(let k of It(ei(h.when)))Object.hasOwn(a,k)||F(`[condition/unknownIdentifier] ${_t(d,w)} reads '${k}', which the context does not carry`);return VI(h.when,{values:a})});u===-1&&F(`[assignment/defaultRowMissing] ${_t(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:oY(d,u,p,l,r)})}return l}s(eN,"evaluateRules");function oY(e,t,n,r,i){switch(n.kind){case"person":return{kind:"value",value:i.person(n.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(n,{slot:e,row:t})};case"unassigned":return F(`[assignment/targetMissing] ${_t(e,t)} names no one`);case"queue":return e===ht&&F(`[assignment/queueOnProcessSlot] ${_t(e,t)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===ht?void 0:r.find(a=>a.slot===n.slot);return o===void 0&&F(`[assignment/slotForwardRef] ${_t(e,t)} copies '${n.slot}', which is not decided before it`),o.value}}}s(oY,"resolveTarget");var mw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function sY(e){if(typeof e!="object"||e===null)return!1;let{kind:t,groupKey:n,...r}=e;return Object.keys(r).length>0?!1:t==="responsible"?n===void 0:t==="team"&&typeof n=="string"&&n.length>0}s(sY,"isStoredSlot");function tN(e){let t=[],n=s((r,i)=>t.push(`[assignment/shape] ${r}: ${i}`),"bad");return Array.isArray(e)?(e.forEach((r,i)=>{let o=`slots[${i}]`;if(typeof r!="object"||r===null)return n(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&n(o,`unknown field(s) ${Object.keys(d).join(", ")}`),sY(a)||n(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return n(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return n(p,"must be { when, assign }");let{when:h,assign:w,...k}=c;Object.keys(k).length>0&&n(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&n(p,"when must be a condition string or null (\u201Esonst\u201C)");let y=w?.kind;if(typeof w!="object"||w===null||typeof y!="string"||!Object.hasOwn(mw,y))return n(p,`assign must be one of ${Object.keys(mw).map(I=>`{kind:'${I}'}`).join(", ")}`);let v=mw[y],A=Object.keys(w);(A.some(I=>!v.includes(I))||v.some(I=>!A.includes(I)))&&n(p,`a '${y}' target has exactly the field(s) ${v.join(", ")}`);let E=w;if(y==="person"&&(typeof E.configKey!="string"||E.configKey.length===0)&&n(p,"a 'person' target needs a non-empty configKey"),y==="rotation"){let I=E.configKeys;(!Array.isArray(I)||I.some(C=>typeof C!="string"))&&n(p,"a 'rotation' target needs configKeys, a list of person keys"),pw.includes(E.mode)||n(p,`a 'rotation' target's mode is one of ${pw.map(C=>`'${C}'`).join(", ")}`)}y==="slot"&&E.slot!==ht&&n(p,`a 'slot' target copies '${ht}' and nothing else`)})}),t):(n("slots","must be a list of { slot, rules }"),t)}s(tN,"ruleShapeIssues");function nN(e){let t=e??{},n=[];if(t.teamOwnerBindings!==void 0&&n.push({de:"[assignment/legacyBindings] der Workflow tr\xE4gt noch teamOwnerBindings \u2014 die Zust\xE4ndigkeitsregel ersetzt sie; das Feld entfernen",en:"[assignment/legacyBindings] the workflow still carries teamOwnerBindings \u2014 the assignment rule replaces them; remove the field"}),t.assignmentRules===void 0)return n.push({de:"[assignment/noRules] der Workflow hat keine Zust\xE4ndigkeitsregel (graph.assignmentRules) \u2014 jeder Workflow muss sagen, wer zust\xE4ndig wird",en:"[assignment/noRules] the workflow has no assignment rule (graph.assignmentRules) \u2014 every workflow must say who becomes responsible"}),n;let r=tN(t.assignmentRules);if(r.length>0)return[...n,...r.map(o=>({de:o,en:o}))];let i=Hf({nodes:Array.isArray(t.nodes)?t.nodes:[]});for(let o of nY(H_(t.assignmentRules),i))o.severity==="error"&&n.push(o.message);return n}s(nN,"workflowAssignmentIssues");function Jf(e,t){let o=new Map;for(let d of e)o.set(d,0);let a=new Map,l=[];for(let d of e){if((o.get(d)??0)!==0)continue;let c=[{id:d,edges:t(d),idx:0}];for(o.set(d,1),a.set(d,null);c.length>0;){let u=c[c.length-1];if(u.idx>=u.edges.length){o.set(u.id,2),c.pop();continue}let{target:p,edge:h}=u.edges[u.idx];u.idx++;let w=o.get(p)??0;if(w===1){let k=[p],y=u.id;for(;y&&y!==p;)k.push(y),y=a.get(y)??null;k.reverse(),l.push({edge:h,source:u.id,target:p,cycle:k})}else w===0&&(o.set(p,1),a.set(p,u.id),c.push({id:p,edges:t(p),idx:0}))}}return l}s(Jf,"detectBackEdges");var hw="team:",aY=/^[a-z0-9][a-z0-9-]*$/;function lY(e){if(!e.startsWith(hw))return null;let t=e.slice(hw.length);return t.length>0?t:null}s(lY,"teamKeyOfMember");function Qf(e){return`${hw}${e}`}s(Qf,"teamMember");function na(e){let t=e.channels;return t===void 0?[]:(Array.isArray(t)||F("graph.channels must be an array"),t)}s(na,"readAuthoredChannels");function rN(e){return[...Ml(e)].sort()}s(rN,"derivedChannelTeamKeys");function iN(e,t){let n=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!t.has(n))return n;for(let r=2;;r++){let i=`${n}-${r}`;if(!t.has(i))return i}}s(iN,"mintChannelKey");function oN(e,t){let n=e.channels;if(n===void 0)return[];if(!Array.isArray(n))return[{path:"channels",reason:{de:"[channels/shape] graph.channels muss eine Liste sein.",en:"[channels/shape] graph.channels must be a list."}}];let r=[],i=Ml(e),o=new Set,a=new Map;return n.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||$t(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(A=>typeof A=="string")){r.push({path:c,reason:{de:"[channels/shape] Ein Kanal braucht key, label ({ de, en }) und members (Liste von Texten).",en:"[channels/shape] A channel needs key, label ({ de, en }) and members (a list of texts)."}});return}let p={de:`Kanal "${u.key}"`,en:`Channel "${u.key}"`};aY.test(u.key)||r.push({path:`${c}.key`,reason:{de:`[channels/invalidKey] ${p.de}: Schl\xFCssel nur aus Kleinbuchstaben, Ziffern und Bindestrich.`,en:`[channels/invalidKey] ${p.en}: key only from lowercase letters, digits and hyphens.`}}),o.has(u.key)&&r.push({path:`${c}.key`,reason:{de:`[channels/duplicateKey] ${p.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[channels/duplicateKey] ${p.en}: key is used twice.`}}),o.add(u.key);let h=$t(u.label);if(h!=="not-localized"&&h.length===2?r.push({path:`${c}.label`,reason:{de:`[channels/emptyLabel] ${p.de}: Bezeichnung fehlt.`,en:`[channels/emptyLabel] ${p.en}: name is missing.`}}):h!=="not-localized"&&h.length>0&&r.push({path:`${c}.label`,reason:{de:`[i18n/missingTranslation] ${p.de}: Bezeichnung fehlt in: ${h.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${p.en}: name is missing in: ${h.join(", ")} \u2014 every displayed text needs German and English.`}}),u.members.length===0){r.push({path:`${c}.members`,reason:{de:`[channels/emptyMembers] ${p.de}: mindestens ein Team.`,en:`[channels/emptyMembers] ${p.en}: at least one team.`}});return}let w=[];for(let A of u.members){let E=lY(A);if(E===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${A}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${A}" is not a "team:<key>".`}});continue}if(w.includes(E)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${E}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${E}" is named twice.`}});continue}t!==void 0&&!t.has(E)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${E}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${E}" does not exist at this school (or it is the applicant group).`}}),w.push(E)}if(w.length===0)return;let k=[...w].sort().join("+"),[y]=w;w.length===1&&y!==void 0&&i.has(y)&&r.push({path:`${c}.members`,reason:{de:`[channels/duplicatesDerived] ${p.de}: Team "${y}" ist am Prozess beteiligt und hat seinen Kanal schon automatisch.`,en:`[channels/duplicatesDerived] ${p.en}: team "${y}" takes part in the process and already has its channel automatically.`}});let v=a.get(k);v!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${v}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${v}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(oN,"channelIssues");var rme=Object.freeze({});function dY(e,t){return Object.freeze(Gf(Yr,e,t))}s(dY,"formContextEntries");function sN(e){return e.env??[]}s(sN,"declaredContextKeys");function aN(e,t){return sN(e).every(n=>lN(n,t?.[n]))}s(aN,"scenarioContextComplete");function lN(e,t){return O_(Yr,e,t)}s(lN,"contextValueComplete");function dN(e,t){return dY(t??{},sN(e))}s(dN,"scenarioContextEntries");function yw(e){return Dl(e)}s(yw,"isContextIdentifier");function cY(e,t,n){let r=Uf(Yr,e);if(r!==null)return{severity:"error",path:n,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return t.has(i)?null:{severity:"error",path:n,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(cY,"contextIdentifierIssue");var gw=af("stage.key");function uY(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===gw,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(n(i.left)&&i.right.kind==="str"&&t.push(i.right.value),n(i.right)&&i.left.kind==="str"&&t.push(i.left.value)),i.op==="in"&&n(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&t.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),t}s(uY,"stageKeyLiterals");function Zf(e,t,n){return t===void 0?[]:uY(e).filter(r=>!t.has(r)).map(r=>uN(r,t,n))}s(Zf,"stageKeyAstIssues");function cN(e,t){if(t===void 0)return[];let n=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!t.has(i.key)&&n.push(uN(i.key,t,`scenario:${r.id}/env`))}return n}s(cN,"scenarioStageKeyIssues");function uN(e,t,n){let r=[...t].sort();return{severity:"error",path:n,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${gw}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${gw}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(uN,"unknownStageKeyIssue");function fN(e,t,n){let r=[];for(let i of It(e)){if(!yw(i))continue;let o=cY(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of uw(e,of))r.push({severity:"error",path:n,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(fN,"contextAstIssues");function pN(e,t){let n=[...fY(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Es(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${As.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${As.join(", ")}).`}});continue}t!==void 0&&!t.has(i)&&n.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>Es(a)&&!lN(a,i.env?.[a]));o.length>0&&n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))Es(a)?r.has(a)||n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return n}s(pN,"formContextIssues");function fY(e){let t=[];Object.hasOwn(e,"context")&&t.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let n=e.testScenarios;for(let r of Array.isArray(n)?n:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&t.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return t}s(fY,"retiredContextFields");function Xf(e,t,n){let r=Yf(e,t).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(n?.liveEnvKeys!==void 0)for(let o of cw(e,t)){let a=G_(o.path,n.liveEnvKeys);a===null&&F(`[condition] no live-key universe for '${o.path}' \u2014 extend liveKeyUniverse`),a.has(o.value)||i.push({de:`$env.${o.path} == '${o.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${o.path} == '${o.value}' names no key of this school.`})}for(let o of Zf(Rt(e),n?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(Xf,"envConditionFindings");function ep(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(ep,"isReviewField");function ra(e){let t=[],n=[];function r(y,v){try{return Rt(y)}catch(A){t.push({path:v,src:y,reason:A instanceof Error?A.message:String(A)});return}}s(r,"tryParse");function i(y,v){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,requiredIf:y.requiredIf?r(y.requiredIf,`${v}.requiredIf`):void 0,disabledIf:y.disabledIf?r(y.disabledIf,`${v}.disabledIf`):void 0,defaultValue:y.defaultValue?r(y.defaultValue,`${v}.defaultValue`):void 0}}s(i,"compileField");function o(y,v){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,fields:y.fields.map((A,E)=>i(A,`${v}.fields[${E}]`))}}s(o,"compileGroup");function a(y,v){return{...y,itemTemplate:y.itemTemplate.map((A,E)=>i(A,`${v}.itemTemplate[${E}]`)),effects:y.effects?.map((A,E)=>d(A,`${v}.effects[${E}]`)),itemVisibleIf:y.itemVisibleIf?r(y.itemVisibleIf,`${v}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(y,v){let A=[];return y.fields.forEach((E,I)=>{if(E.externalFlag){n.push({key:E.key,label:E.label,defaultValue:E.defaultValue?r(E.defaultValue,`${v}.fields[${I}].defaultValue`):void 0});return}A.push(i(E,`${v}.fields[${I}]`))}),{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,fields:A,groups:y.groups?.map((E,I)=>o(E,`${v}.groups[${I}]`)),computed:y.computed?.map((E,I)=>{let C=r(E.expression,`${v}.computed[${I}].expression`);return{key:E.key,expression:C??{kind:"null"}}}),subsections:y.subsections?.map((E,I)=>l(E,`${v}.subsections[${I}]`)),repeated:y.repeated?.map((E,I)=>a(E,`${v}.repeated[${I}]`)),validators:y.validators}}s(l,"compileSection");function d(y,v){return{...y,when:y.when?r(y.when,`${v}.when`):void 0}}s(d,"compileEffect");function c(y,v){let A=r(y.when,`${v}.when`);return A?{...y,when:A}:null}s(c,"compileOutcome");let u=e.sections.map((y,v)=>l(y,`sections[${v}]`)),p=(e.effects??[]).map((y,v)=>d(y,`effects[${v}]`)),h=[],w=e.outcomes??[];for(let y=0;y<w.length;y++){let v=w[y],A=c(v,`outcomes[${y}]`);A&&h.push(A)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:n},errors:t}}s(ra,"compileForm");var pY=new Set(["decision","review","governedDocument"]);function hN(e){return pY.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(hN,"isReadinessGatedNode");function mY(e){let t=new Map,n=gY(e),r=s((i,o)=>{let a=ww(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&t.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:hY(d.bucket,n,a),section:a,type:d.type,enumSource:mN(d),repeated:!1,reviewRequired:d.reviewRequired===!0});for(let d of i.repeated??[])for(let c of d.itemTemplate){let u=`${d.key}.${c.key}`;t.set(u,{kind:"entered",key:u,label:c.label,qualifier:ww(d),section:a,type:c.type,enumSource:mN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=It(Rt(d.expression));t.set(d.key,{kind:"computed",key:d.key,label:d.label??{de:d.key,en:d.key},qualifier:a,deps:c})}for(let d of i.subsections??[])r(d,o)},"visit");for(let i of e.sections)r(i,i);return t}s(mY,"formFieldCatalog");function mN(e){return e.type==="enum"?e:null}s(mN,"enumSourceOf");function hY(e,t,n){return e===void 0?n:t.get(e)??n}s(hY,"fieldQualifier");function gY(e){let t=new Map,n=s((r,i)=>{i===void 0||t.has(r)||t.set(r,ww(i))},"add");for(let r of yN(e))r.kind==="person"?n(r.bucket,r.display):r.kind==="organization"&&n(r.id.replace(/^o\./,""),r.display);return t}s(gY,"bucketWordings");function gN(e){return e.flatMap(t=>[t,...gN(t.subsections??[])])}s(gN,"allSections");function yN(e){return[...e.effects,...gN(e.sections).flatMap(t=>(t.repeated??[]).flatMap(n=>n.effects??[]))]}s(yN,"allEffects");function ww(e){return{label:e.label}}s(ww,"wordingOf");function wN(e){return Sl(e).flatMap(({slot:t,address:n})=>{let r=YI(n);return r===null||xl.includes(r.path)?[]:[{slotId:t,owner:r.owner,fieldKey:r.path}]})}s(wN,"admissionBindingLeaves");function yY(e,t){let n=e.get(t);if(n===void 0)return null;let r=[],i=new Set,o=s(a=>{if(!i.has(a.key)&&(i.add(a.key),r.push({fieldKey:a.key,kind:a.kind}),a.kind==="computed"))for(let l of a.deps){let d=e.get(l);d!==void 0&&o(d)}},"walk");return o(n),r}s(yY,"expandKey");function wY(e){let t=new Set;for(let n of yN(e))if(!(n.kind!=="person"||n.contractParty===void 0)&&n.when!==void 0)for(let r of It(Rt(n.when)))t.add(r);return[...t]}s(wY,"contractPartyConditionKeys");function kY(e){return ra(e).compiled.flags.map(t=>({key:t.key,name:t.label}))}s(kY,"formExternalFlags");function kN(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([t,n])=>[t,mY(n)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set(wY(n))])),formFlagKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set(kY(n).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set((n.views??[]).map(r=>r.key))]))}}s(kN,"readinessUniverse");function kw(e,t){let n=new Set;for(let r of t)for(let i of yY(e,r)??[])i.kind==="entered"&&n.add(i.fieldKey);return n}s(kw,"enteredFieldsBehind");var bY=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function vY(e){return bY.has(e)?!0:bN(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(vY,"isTextKey");function bN(e){return/^localized[A-Z]/.test(e)}s(bN,"isLegacyTwinKey");var xY=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),SY=new Set(["inputs","resolver","library"]);function np(e,t){let n=[];return bw(e,t,n),n}s(np,"findUnlocalizedTexts");function bw(e,t,n){if(Array.isArray(e)){e.forEach((i,o)=>bw(i,`${t}[${EY(i,o)}]`,n));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${t}.${i}`;if(!SY.has(i)){if(bN(i)){n.push({path:a,missing:"legacy-twin"});continue}if(vY(i)){AY(o,a,n);continue}if(xY.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&vN(d,`${a}.${l}`,n);continue}bw(o,a,n)}}}s(bw,"walk");function AY(e,t,n){e!=null&&vN(e,t,n)}s(AY,"checkText");function vN(e,t,n){let r=$t(e);(r==="not-localized"||r.length>0)&&n.push({path:t,missing:r})}s(vN,"report");function EY(e,t){if(e!==null&&typeof e=="object"){let n=e;if(typeof n.id=="string")return n.id;if(typeof n.key=="string")return n.key}return String(t)}s(EY,"keyOf");function tp(e,t){return e==="not-localized"?t==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?t==="de"?'ist ein Zwilling der alten Form \u2014 der Text geh\xF6rt in das Feld ohne \u201Elocalized"':'is a twin of the old shape \u2014 the text belongs in the field without "localized"':t==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(tp,"describe");function vw({path:e,missing:t}){return t==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${tp(t,"de")}.`,en:`[i18n/legacyTwin] ${e} ${tp(t,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${tp(t,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${tp(t,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(vw,"unlocalizedTextReason");var TY={engagePush:["engage"]};function $Y(e){let t=TY[e.type];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([n])=>!t.includes(n)))}s($Y,"withoutMachineData");function xN(e,t){return[...np(e.nodes.map($Y),"nodes"),...t===void 0?[]:np(t,`layout.${t.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:vw(r),severity:"error"}))}s(xN,"checkLocalizedTexts");var Io=5,Oo=480;function ii(e){return typeof e=="string"&&e.trim().length>0}s(ii,"isNonEmptyString");function AN(e,t,n){return Object.keys(e).filter(r=>!t.includes(r)).map(r=>({field:`result.${r}`,code:tt.unknownField,message:{de:`Unbekanntes Feld '${r}' im ${n.de}; erlaubt sind: ${t.join(", ")}.`,en:`Unknown field '${r}' in the ${n.en}; allowed: ${t.join(", ")}.`}}))}s(AN,"unknownFieldIssues");function RY(e){let t=[],n=e.title;(n===void 0||typeof n!="object"||n===null||!ii(n.de)||!ii(n.en))&&t.push({field:"result.title",code:tt.appointmentMissingTitle,message:{de:"Ein Termin-Ergebnis braucht einen neutralen Titel in beiden Sprachen ({ de, en }) \u2014 er steht in der Mail und in der Kalenderdatei der Familie, deshalb nie ein Familienname.",en:"An appointment result needs a neutral title in both languages ({ de, en }) \u2014 it appears in the email and in the family's calendar file, so never a family name."}});let r=e.durationMinutes;return(typeof r!="number"||!Number.isInteger(r)||r<Io||r>Oo)&&t.push({field:"result.durationMinutes",code:tt.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Io} bis ${Oo} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Io} to ${Oo}, got ${JSON.stringify(r)}.`}}),t.push(...AN(e,["kind","title","durationMinutes"],{de:"Termin-Ergebnis",en:"appointment result"})),t}s(RY,"appointmentIssues");function SN(e){if(typeof e!="object"||e===null)return!1;let t=e;return ii(t.de)&&ii(t.en)}s(SN,"isBilingual");var xw=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom"];function IY(e){let t=s((i,o)=>({field:i,code:tt.recordFields,message:o}),"issue");if(!Array.isArray(e)||e.length===0)return[t("result.fields",{de:"Eine Erfassung braucht mindestens ein Feld ('result.fields').",en:"A record needs at least one field ('result.fields')."})];let n=[],r=new Set;for(let[i,o]of e.entries()){let a=`result.fields[${i}]`;if(typeof o!="object"||o===null||Array.isArray(o)){n.push(t(a,{de:"Ein Feld der Erfassung muss ein Objekt sein.",en:"A field of the record must be an object."}));continue}let l=o,d=l.key;typeof d!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(d)?n.push(t(`${a}.key`,{de:`Feld-Schl\xFCssel ${JSON.stringify(d)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,en:`Field key ${JSON.stringify(d)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`})):r.has(d)?n.push(t(`${a}.key`,{de:`Feld-Schl\xFCssel "${d}" ist doppelt.`,en:`Field key "${d}" is duplicated.`})):r.add(d);let c=typeof d=="string"?`"${d}"`:`Nr. ${i+1}`,u=typeof d=="string"?`"${d}"`:`no. ${i+1}`;if(gy(l.type)||n.push(t(`${a}.type`,{de:`Feld ${c}: Typ ${JSON.stringify(l.type)} \u2014 erlaubt: ${gf.join(", ")}.`,en:`Field ${u}: type ${JSON.stringify(l.type)} \u2014 allowed: ${gf.join(", ")}.`})),SN(l.label)||n.push(t(`${a}.label`,{de:`Feld ${c} braucht ein Label in beiden Sprachen ({ de, en }).`,en:`Field ${u} needs a label in both languages ({ de, en }).`})),ii(l.writes)||n.push(t(`${a}.writes`,{de:`Feld ${c} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`,en:`Field ${u} writes to no process key ('writes') \u2014 a value nobody can read does not belong in a record.`})),l.type==="enum"){let h=Array.isArray(l.options)?l.options:[],w=h.map(k=>k.key);(h.length<2||w.some(k=>typeof k!="string"||k.length===0)||new Set(w).size!==w.length||h.some(k=>!SN(k.label)))&&n.push(t(`${a}.options`,{de:`Feld ${c} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`,en:`Field ${u} (choice) needs at least 2 options with unique keys and labels in both languages.`}))}else l.options!==void 0&&n.push(t(`${a}.options`,{de:`Feld ${c}: 'options' gibt es nur bei Typ 'enum'.`,en:`Field ${u}: 'options' exists only for type 'enum'.`}));if(l.min!==void 0&&(l.type!=="number"||typeof l.min!="number"||!Number.isInteger(l.min))&&n.push(t(`${a}.min`,{de:`Feld ${c}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`,en:`Field ${u}: 'min' exists only for type 'number', as a whole number.`})),l.evidence!==void 0&&typeof l.evidence!="boolean"&&n.push(t(`${a}.evidence`,{de:`Feld ${c}: 'evidence' ist true oder false.`,en:`Field ${u}: 'evidence' is true or false.`})),l.evidenceFrom!==void 0){let h=typeof l.min=="number"?l.min:0;(l.type!=="number"||l.evidence!==!0||typeof l.evidenceFrom!="number"||!Number.isInteger(l.evidenceFrom)||l.evidenceFrom<=h)&&n.push(t(`${a}.evidenceFrom`,{de:`Feld ${c}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${h}) \u2014 sonst g\xE4lte der Nachweis immer.`,en:`Field ${u}: 'evidenceFrom' exists only for type 'number' with 'evidence', as a whole number above the minimum (${h}) \u2014 otherwise the proof would always apply.`}))}if(l.suggest!==void 0){let h=l.suggest,w=typeof h=="object"&&h!==null?h.kind:void 0;w==="form"&&"address"in h&&Object.keys(h).length===2&&(!xe(h.address)||ct(h.address))||w==="siblingRank"&&Object.keys(h).length===1&&l.type==="number"||n.push({field:`${a}.suggest`,code:tt.recordSuggest,message:{de:`Feld ${c}: Vorschlag ${JSON.stringify(l.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${yy.join(", ")}.`,en:`Field ${u}: suggestion ${JSON.stringify(l.suggest)} \u2014 allowed: { kind: 'form', address: '$node.<form>.admission.<export>' } or { kind: 'siblingRank' } (only for type 'number'); known kinds: ${yy.join(", ")}.`}})}let p=Object.keys(l).filter(h=>!xw.includes(h));p.length>0&&n.push(t(a,{de:`Feld ${c}: unbekannte Angabe ${p.map(h=>`'${h}'`).join(", ")}; erlaubt: ${xw.join(", ")}.`,en:`Field ${u}: unknown entry ${p.map(h=>`'${h}'`).join(", ")}; allowed: ${xw.join(", ")}.`}))}return n}s(IY,"recordFieldIssues");function OY(e,t,n){let r=[],i=t.options;if(e==="choice"){let o=Array.isArray(i)?i:[],a=o.map(l=>l.key);(o.length<2||a.some(l=>typeof l!="string"||l.length===0)||new Set(a).size!==a.length)&&r.push({field:"result.options",code:tt.choiceOptions,message:{de:`Ein Auswahl-Ergebnis braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln, erhalten ${JSON.stringify(a)}.`,en:`A choice result needs at least 2 options with unique keys, got ${JSON.stringify(a)}.`}})}else i!==void 0&&r.push({field:"result.options",code:tt.choiceOptions,message:{de:`'result.options' gibt es nur bei 'choice' \u2014 ${e==="recommendation"?"eine Empfehlung hat die festen Tendenzen Positiv/Neutral/Negativ":"ein Freitext hat keine Auswahl"}.`,en:`'result.options' exists only for 'choice' \u2014 ${e==="recommendation"?"a recommendation has the fixed leanings Positive/Neutral/Negative":"a free text has no choice"}.`}});if(e==="pricedItem"){let o=t.item;if(!ii(o))r.push({field:"result.item",code:tt.pricedItemMissingItem,message:{de:"Ein Preispositions-Ergebnis nennt den Artikel, den es bepreist \u2014 'result.item' (der Schl\xFCssel des Artikels, z. B. 'tuition') fehlt.",en:"A priced-item result names the article it prices \u2014 'result.item' (the article's key, e.g. 'tuition') is missing."}});else if(n.billingItemKeys!==void 0&&!n.billingItemKeys.has(o))r.push({field:"result.item",code:tt.pricedItemUnknownItem,message:{de:`'result.item' "${o}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...n.billingItemKeys].join(", ")||"keine"}).`,en:`'result.item' "${o}" \u2014 no article of this school has this key (known: ${[...n.billingItemKeys].join(", ")||"none"}).`}});else if(n.offerProgram===null)r.push({field:"result.item",code:tt.pricedItemOfferWithoutProgram,message:{de:`'result.item' "${o}" \u2014 das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.`,en:`'result.item' "${o}" \u2014 the offer is not assigned to a program, so no article belongs to it; give the offer a program.`}});else if(n.offerProgram!==void 0&&!n.offerProgram.billingItemKeys.has(o)){let l=n.offerProgram;r.push({field:"result.item",code:tt.pricedItemNotInProgram,message:{de:`'result.item' "${o}" \u2014 der Artikel ist dem Programm \u201E${l.nameDe}\u201C des Angebots nicht zugeordnet (zugeordnet: ${[...l.billingItemKeys].join(", ")||"keine"}); unter Finanzen \u2192 Artikel zuordnen, direkt oder \xFCber ein Paket.`,en:`'result.item' "${o}" \u2014 the article is not assigned to the offer's program "${l.nameDe}" (assigned: ${[...l.billingItemKeys].join(", ")||"none"}); assign it under Finance \u2192 articles, directly or through a package.`}})}let a=t.label;(typeof a!="object"||a===null||!ii(a.de)||!ii(a.en))&&r.push({field:"result.label",code:tt.labelMissing,message:{de:"Ein Preispositions-Ergebnis braucht einen Namen f\xFCr seinen Wert in beiden Sprachen ('result.label', z. B. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 so hei\xDFt er im Workflow und in der Verdrahtung.",en:"A priced-item result needs a name for its value in both languages ('result.label', e.g. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 that is what it is called in the workflow and in the wiring."}})}else t.item!==void 0&&r.push({field:"result.item",code:tt.itemOnNonPricedItem,message:{de:`'result.item' gibt es nur bei 'pricedItem' \u2014 ein ${e}-Ergebnis bepreist keinen Artikel.`,en:`'result.item' exists only for 'pricedItem' \u2014 a ${e} result prices no article.`}});if(e==="record"?(r.push(...IY(t.fields)),t.writes!==void 0&&r.push({field:"result.writes",code:tt.writesOnProse,message:{de:"Eine Erfassung schreibt je Feld ('fields[].writes'), nie als Ganzes ('result.writes').",en:"A record writes per field ('fields[].writes'), never as a whole ('result.writes')."}}),t.label!==void 0&&r.push({field:"result.label",code:tt.unknownField,message:{de:"Eine Erfassung benennt ihre Werte je Feld ('fields[].label'), nicht als Ganzes ('result.label').",en:"A record names its values per field ('fields[].label'), not as a whole ('result.label')."}})):t.fields!==void 0&&r.push({field:"result.fields",code:tt.fieldsOnNonRecord,message:{de:`'result.fields' gibt es nur bei 'record' \u2014 ein ${e}-Ergebnis hat keine Felder.`,en:`'result.fields' exists only for 'record' \u2014 a ${e} result has no fields.`}}),e==="reduction"&&(ii(t.writes)||r.push({field:"result.writes",code:tt.reductionPrices,message:{de:"Eine Reduktion schreibt ihren Betrag in einen Vorgangs-Schl\xFCssel vom Typ reduction ('result.writes') \u2014 sonst l\xE4se ihn kein Preis.",en:"A reduction writes its amount to a process key of type reduction ('result.writes') \u2014 otherwise no price would read it."}})),t.writes!==void 0&&(e==="freetext"||e==="recommendation")&&r.push({field:"result.writes",code:tt.writesOnProse,message:{de:`'result.writes' gibt es nur bei Ergebnissen mit Wert (Auswahl, Preisposition) \u2014 ein ${e}-Ergebnis bleibt im Chat und schreibt nichts in den Vorgang.`,en:`'result.writes' exists only for results with a value (choice, priced item) \u2014 a ${e} result stays in the chat and writes nothing to the process.`}}),e==="freetext"&&t.textRequired!==void 0&&r.push({field:"result.textRequired",code:tt.textRequiredOnFreetext,message:{de:"'textRequired' auf einem Freitext-Ergebnis \u2014 der Text eines Freitexts ist immer Pflicht; die Angabe entfernen.",en:"'textRequired' on a free-text result \u2014 the text of a free text is always required; remove the entry."}}),t.chat===void 0)r.push({field:"result.chat",code:tt.chatMissing,message:{de:"Ein Aufgaben-Ergebnis steht nur im Chat \u2014 'result.chat' fehlt: 'all', 'team:<Gruppe>' oder einen Kanal des Workflows angeben.",en:"A task result appears only in the chat \u2014 'result.chat' is missing: give 'all', 'team:<group>' or a channel of the workflow."}});else{let o=t.chat,a=typeof o=="string"?_s(o):null;o==="external"||a===null?r.push({field:"result.chat",code:tt.chatExternal,message:{de:`'result.chat' ${JSON.stringify(o)} \u2014 ein Aufgaben-Ergebnis bleibt intern: erlaubt sind 'all', 'team:<Gruppe>' oder ein Kanal des Workflows, nie 'external'.`,en:`'result.chat' ${JSON.stringify(o)} \u2014 a task result stays internal: 'all', 'team:<group>' or a channel of the workflow are allowed, never 'external'.`}}):a.kind==="channel"&&!n.channelKeys.has(a.channelKey)&&r.push({field:"result.chat",code:tt.chatUnknownChannel,message:{de:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...n.channelKeys].join(", ")||"keine"}).`,en:`'result.chat' "${a.channelKey}" is neither 'all' nor 'team:<group>' nor a channel of the workflow (known: ${[...n.channelKeys].join(", ")||"none"}).`}})}return r.push(...AN(t,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(OY,"recordedIssues");function EN(e,t,n={channelKeys:new Set}){if(t===void 0)return[];if(e!=="task")return[{field:"result",code:tt.onApproval,message:{de:`'result' gilt nur f\xFCr die Art 'task' \u2014 eine '${e}' wird durch ihr Votum abgeschlossen, nicht durch ein Ergebnis.`,en:`'result' applies only to the kind 'task' \u2014 an '${e}' is completed by its vote, not by a result.`}}];if(typeof t!="object"||t===null||Array.isArray(t))return[{field:"result",code:tt.unknownKind,message:{de:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${Is.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Is.join(", ")}.`}}];let r=t;return NI(r.kind)?r.kind==="appointment"?RY(r):OY(r.kind,r,n):[{field:"result.kind",code:tt.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Is.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Is.join(", ")}.`}}]}s(EN,"taskResultIssues");var Sw=60;function oi(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(oi,"error");function _Y(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"warning"}}s(_Y,"warning");function TN(e){return Array.isArray(e.tasks)?e.tasks:[]}s(TN,"tasksOf");function RN(e,t){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(r=>r.action==="spawnTasks"&&Array.isArray(r.tasks)&&r.tasks.includes(t))}s(RN,"spawnActionsOf");function $N(e,t){return RN(e,t).map(n=>String(n.key)).sort()}s($N,"bindingsOf");function IN(e,t){let n=[],r=TN(e),i=new Map;for(let o of r){if(o.appointment===void 0)continue;let a=typeof o.key=="string"?o.key:"?",l=`nodes.${e.id}.tasks.${a}`,d={de:`Terminaufgabe "${a}" (Knoten "${e.id}")`,en:`Appointment task "${a}" (node "${e.id}")`},c=o.appointment,p=typeof c=="object"&&c!==null&&Object.keys(c).every($=>$==="of"||$==="dueDaysAfterEnd")&&typeof c.of=="string"?c.of:void 0,h=p===void 0?void 0:r.find($=>$.key===p),w=h?.result;if(p===void 0||h===void 0||w?.kind!=="appointment")n.push(oi(`${l}.appointment.of`,{de:`[workItems/appointmentOfUnknown] ${d.de} braucht 'appointment: { of, dueDaysAfterEnd }', und 'of' nennt eine Aufgabe desselben Knotens, die mit einem Termin abschlie\xDFt (result.kind 'appointment'); erhalten ${JSON.stringify(o.appointment)}.`,en:`[workItems/appointmentOfUnknown] ${d.en} needs 'appointment: { of, dueDaysAfterEnd }', and 'of' names a task of the same node that ends with an appointment (result.kind 'appointment'); got ${JSON.stringify(o.appointment)}.`}));else{i.set(p,(i.get(p)??0)+1);let $=h.blocks,b=[...["when","optional"].filter(R=>h[R]!==void 0),...typeof $?.node=="string"&&$.node!==e.id?["blocks"]:[]];b.length>0&&n.push(oi(`nodes.${e.id}.tasks.${p}.${b[0]}`,{de:`[workItems/appointmentTaskShape] "${p}" bucht den Termin f\xFCr ${d.de} und tr\xE4gt ${b.map(R=>R==="blocks"?"ein knoten\xFCbergreifendes 'blocks'":`'${R}'`).join(", ")} \u2014 fiele sie ohne Buchung weg oder \xFCberlebte sie ihren Knoten, wartete die Terminaufgabe f\xFCr immer bzw. f\xE4nde die Buchung keine Terminaufgabe mehr.`,en:`[workItems/appointmentTaskShape] "${p}" books the appointment for ${d.en} and carries ${b.map(R=>R==="blocks"?"a cross-node 'blocks'":`'${R}'`).join(", ")} \u2014 if it dropped out without a booking or outlived its node, the appointment task would wait forever or the booking would find no appointment task any more.`}));for(let R of RN(e,p))R.repeatable!==!0&&n.push(oi(`nodes.${e.id}.optionalActions.${String(R.key)}.repeatable`,{de:`[workItems/appointmentActionRepeatable] Die optionale Aktion "${String(R.key)}" legt "${p}" an, die den Termin f\xFCr ${d.de} bucht, und ist nicht 'repeatable: true'. Eine Absage beendet die Runde; ohne zweite Runde lie\xDFe sich die Aktion nie wieder ausl\xF6sen, und eine Entscheidung, die auf sie wartet (requiresOneOf), bliebe h\xE4ngen.`,en:`[workItems/appointmentActionRepeatable] The optional action "${String(R.key)}" creates "${p}", which books the appointment for ${d.en}, and is not 'repeatable: true'. A cancellation ends the round; without a second round the action could never be triggered again, and a decision waiting for it (requiresOneOf) would hang.`}));$N(e,a).join(",")!==$N(e,p).join(",")&&n.push(oi(`${l}.appointment.of`,{de:`[workItems/appointmentTaskBinding] ${d.de} geh\xF6rt zu anderen optionalen Aktionen als "${p}", die ihren Termin bucht \u2014 beide Zeilen sind eine Runde: entweder beide in derselben Aktion (spawnTasks) oder beide in keiner.`,en:`[workItems/appointmentTaskBinding] ${d.en} belongs to different optional actions than "${p}", which books its appointment \u2014 both rows are one round: either both in the same action (spawnTasks) or both in none.`}))}let k=c?.dueDaysAfterEnd;(typeof k!="number"||!Number.isInteger(k)||k<0||k>Sw)&&n.push(oi(`${l}.appointment.dueDaysAfterEnd`,{de:`[workItems/appointmentTaskDue] ${d.de}: 'dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Sw} \u2014 die Tage nach dem Terminende, bis die Aufgabe f\xE4llig ist; erhalten ${JSON.stringify(k)}.`,en:`[workItems/appointmentTaskDue] ${d.en}: 'dueDaysAfterEnd' is a whole number from 0 to ${Sw} \u2014 the days after the appointment ends until the task is due; got ${JSON.stringify(k)}.`})),o.params?.dueInDays!==void 0&&n.push(oi(`${l}.params.dueInDays`,{de:`[workItems/appointmentTaskDue] ${d.de} tr\xE4gt 'params.dueInDays' neben 'appointment.dueDaysAfterEnd' \u2014 eine Terminaufgabe ist ab dem Terminende f\xE4llig, nie ab ihrer Anlage.`,en:`[workItems/appointmentTaskDue] ${d.en} carries 'params.dueInDays' next to 'appointment.dueDaysAfterEnd' \u2014 an appointment task is due from the end of the appointment, never from its creation.`}));let y=o.result,v=["when","optional","familyRequest","reads","locksEvidence"].filter($=>o[$]!==void 0).map($=>`'${$}'`),A=typeof o.blocks?.node=="string"&&o.blocks.node!==e.id,E=s($=>[...o.kind!=="task"?["'kind: approval'"]:[],...y===void 0||!_i(y.kind)?[$==="de"?"kein erfasstes Ergebnis (Feedback)":"no recorded result (feedback)"]:[],...v,...A?[$==="de"?"ein knoten\xFCbergreifendes 'blocks'":"a cross-node 'blocks'"]:[]],"shapeFaults");E("de").length>0&&n.push(oi(`${l}.appointment`,{de:`[workItems/appointmentTaskShape] ${d.de}: ${E("de").join(", ")} \u2014 eine Terminaufgabe ist eine Aufgabe, die mit ihrem Feedback (Freitext, Empfehlung, Auswahl) abschlie\xDFt, und sie entsteht, weil der Termin entsteht: ohne Bedingung, nicht optional, keine Nachforderung, ohne Belege (nichts l\xE4sst sie ungebunden neu entstehen) und an ihrem Knoten.`,en:`[workItems/appointmentTaskShape] ${d.en}: ${E("en").join(", ")} \u2014 an appointment task is a task that ends with its feedback (free text, recommendation, choice), and it exists because the appointment exists: no condition, not optional, no follow-up request, no evidence (nothing lets it be created again unbound) and on its own node.`}));let I=o.result?.chat,C=o.assign?.group;typeof I=="string"&&I.startsWith("team:")&&typeof C=="string"&&I!==`team:${C}`&&n.push(_Y(`${l}.result.chat`,{de:`[workItems/appointmentChatUnreadable] ${d.de} schreibt ihr Feedback in "${I}", geh\xF6rt aber dem Team "${C}" \u2014 die Gastgeberin bzw. der Gastgeber (ein Mitglied von "${C}") kann das eigene Feedback dort wom\xF6glich nicht lesen. 'team:${C}' oder 'all' w\xE4hlen, oder das Team als Mitglied des Chats sicherstellen.`,en:`[workItems/appointmentChatUnreadable] ${d.en} writes its feedback to "${I}", but belongs to the team "${C}" \u2014 the host (a member of "${C}") may not be able to read their own feedback there. Choose 'team:${C}' or 'all', or make sure the team is a member of the chat.`}));for(let $ of t)for(let b of TN($)){let R=b.blocks;R?.templateKey!==a||(typeof R.node=="string"?R.node:$.id)!==e.id||n.push(oi(`nodes.${$.id}.tasks.${String(b.key)}.blocks.templateKey`,{de:`[workItems/appointmentTaskBlocked] Task "${String(b.key)}" (Knoten "${$.id}") h\xE4lt ${d.de} zur\xFCck \u2014 eine Terminaufgabe wartet nur auf ihren Termin (abgeleitet aus 'appointment.of'); ein 'blocks' auf sie entf\xE4llt.`,en:`[workItems/appointmentTaskBlocked] Task "${String(b.key)}" (node "${$.id}") holds back ${d.en} \u2014 an appointment task only waits for its appointment (derived from 'appointment.of'); a 'blocks' on it is dropped.`}))}}for(let[o,a]of i)a<2||n.push(oi(`nodes.${e.id}.tasks.${o}`,{de:`[workItems/appointmentOfTwice] ${a} Terminaufgaben auf Knoten "${e.id}" geh\xF6ren zum Termin von "${o}" \u2014 ein Termin hat eine Terminaufgabe.`,en:`[workItems/appointmentOfTwice] ${a} appointment tasks on node "${e.id}" belong to the appointment of "${o}" \u2014 an appointment has one appointment task.`}));return n}s(IN,"appointmentTaskIssues");var NY="optionalAction:";function ON(e){return`${NY}${e}:trigger`}s(ON,"optionalActionTriggerActionId");var CY="processDecide";function _N(e){let t=e.optionalActions;return t==null?[]:(Array.isArray(t)||F(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof t}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),t)}s(_N,"optionalActionBindings");function NN(e){return _N(e).map(t=>({id:ON(t.key),kind:"internal",label:t.label,surface:CY,placement:"overflow",superUserOnly:!0}))}s(NN,"optionalActionTriggers");function CN(e){let t=new Set;for(let n of _N(e))if(n.action==="spawnTasks")for(let r of n.tasks??[])t.add(r);return t}s(CN,"referencedTaskTemplateKeys");var xn={notOptionalAction:"[workItems/familyRequestNotOptionalAction]",notTask:"[workItems/familyRequestNotTask]",closedOtherwise:"[workItems/familyRequestClosedOtherwise]",blocks:"[workItems/familyRequestBlocks]",noDeadline:"[workItems/familyRequestNoDeadline]",fields:"[workItems/familyRequestFields]",unknownField:"[workItems/familyRequestUnknownField]",shape:"[workItems/familyRequestShape]",twicePerAction:"[workItems/familyRequestTwicePerAction]",deadlock:"[workItems/familyRequestOnlyWayButAsked]"};function Sn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${t} ${n.de}`,en:`${t} ${n.en}`},severity:"error"}}s(Sn,"issue");function PY(e,t,n){return e.flatMap(r=>(Array.isArray(r.tasks)?r.tasks:[]).filter(i=>{let o=i.blocks,a=typeof o?.node=="string"?o.node:r.id;return o?.templateKey===n&&a===t}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(PY,"blockersOf");function PN(e){let{graph:t,node:n,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${n.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(t,n.id,"de")}\u201C (${n.id})`,en:`Task "${o}" on node "${_e(t,n.id,"en")}" (${n.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[Sn(`${a}.familyRequest`,xn.shape,{de:`${l.de}: 'familyRequest' muss ein Objekt { fields } oder { from } sein.`,en:`${l.en}: 'familyRequest' must be an object { fields } or { from }.`})];let c=Object.keys(i).filter(k=>k!=="fields"&&k!=="from");c.length>0&&d.push(Sn(`${a}.familyRequest.${c[0]}`,xn.shape,{de:`${l.de}: 'familyRequest' kennt nur 'fields' oder 'from', nicht ${c.map(k=>`'${k}'`).join(", ")} \u2014 was angefordert wird und der Text an die Familie werden beim Ausl\xF6sen gew\xE4hlt.`,en:`${l.en}: 'familyRequest' only knows 'fields' or 'from', not ${c.map(k=>`'${k}'`).join(", ")} \u2014 what is requested and the text to the family are chosen when the action is triggered.`}));let{fields:u,from:p}=i;u===void 0==(p===void 0)&&d.push(Sn(`${a}.familyRequest`,xn.shape,{de:`${l.de}: 'familyRequest' nennt genau eines \u2014 'fields' (die anforderbaren Felder) oder 'from' (das Formular, dessen Dateifelder alle zur Wahl stehen).`,en:`${l.en}: 'familyRequest' names exactly one \u2014 'fields' (the fields that can be requested) or 'from' (the form whose file fields are all available).`})),e.onTrigger.has(o)||d.push(Sn(`${a}.familyRequest`,xn.notOptionalAction,{de:`${l.de} fordert bei der Familie an, geh\xF6rt aber zu keiner optionalen Aktion (spawnTasks) \u2014 nur deren Ausl\xF6sen \xF6ffnet die Anfrage an die Familie.`,en:`${l.en} requests from the family but belongs to no optional action (spawnTasks) \u2014 only triggering one opens the request to the family.`})),r.kind!=="task"&&d.push(Sn(`${a}.kind`,xn.notTask,{de:`${l.de} fordert bei der Familie an und muss die Art 'task' haben, nicht ${JSON.stringify(r.kind)}.`,en:`${l.en} requests from the family and must have the kind 'task', not ${JSON.stringify(r.kind)}.`}));for(let k of["result","when","locksEvidence","gatesNode"])r[k]!==void 0&&d.push(Sn(`${a}.${k}`,xn.closedOtherwise,{de:`${l.de} wartet auf die Familie und erledigt sich mit ihrer Antwort \u2014 '${k}' passt nicht dazu.`,en:`${l.en} waits for the family and completes with their answer \u2014 '${k}' does not fit that.`}));r.blocks!==void 0&&d.push(Sn(`${a}.blocks`,xn.blocks,{de:`${l.de} wartet auf die Familie und darf nichts zur\xFCckhalten ('blocks') \u2014 sie h\xE4lt ihren Knoten schon als Aufgabe einer optionalen Aktion.`,en:`${l.en} waits for the family and must not hold anything back ('blocks') \u2014 as the task of an optional action it already holds its node.`}));for(let k of PY(t.nodes,n.id,o))d.push(Sn(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,xn.blocks,{de:`Task "${k.key}" auf Knoten "${k.nodeId}" h\xE4lt ${l.de} zur\xFCck \u2014 eine Nachforderung darf nie zur\xFCckgehalten werden: zur\xFCckgehalten h\xE4tte sie keine Frist und k\xF6nnte mit der Antwort der Familie nicht erledigt werden.`,en:`Task "${k.key}" on node "${k.nodeId}" holds back ${l.en} \u2014 a follow-up request must never be held back: held back, it would have no deadline and could not be completed by the family's answer.`}));let h=r.params?.dueInDays;if((typeof h!="number"||!Number.isInteger(h)||h<1)&&d.push(Sn(`${a}.params.dueInDays`,xn.noDeadline,{de:`${l.de} fordert bei der Familie an und braucht eine Frist in ganzen Tagen ('params.dueInDays' \u2265 1) \u2014 sie ist die Frist der Familie und Anlass der Erinnerung.`,en:`${l.en} requests from the family and needs a deadline in whole days ('params.dueInDays' \u2265 1) \u2014 it is the family's deadline and the reason for the reminder.`})),u===void 0)return d;if(!Array.isArray(u)||u.length===0)return d.push(Sn(`${a}.familyRequest.fields`,xn.fields,{de:`${l.de}: 'familyRequest.fields' muss mindestens ein Feld eines Formulars nennen \u2014 oder statt dessen 'from' das Formular, dann stehen alle seine Dateifelder zur Wahl.`,en:`${l.en}: 'familyRequest.fields' must name at least one field of a form \u2014 or 'from' the form instead, then all its file fields are available.`})),d;let w=new Set;for(let k of u){if(!xe(k))continue;let y=pe(k);if(w.has(y)){d.push(Sn(`${a}.familyRequest.fields`,xn.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(t,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(t,k,"en")} more than once.`}));continue}w.add(y),ct(k)||d.push(Sn(`${a}.familyRequest.fields`,xn.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(t,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(t,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(PN,"familyRequestIssues");function DN(e){let t=new Set((Array.isArray(e.tasks)?e.tasks:[]).flatMap(r=>r.familyRequest!==void 0&&typeof r.key=="string"?[r.key]:[]));return(Array.isArray(e.optionalActions)?e.optionalActions:[]).flatMap((r,i)=>{if(r.action!=="spawnTasks"||!Array.isArray(r.tasks))return[];let o=r.tasks.filter(a=>typeof a=="string"&&t.has(a));return o.length<=1?[]:[Sn(`nodes.${e.id}.optionalActions.${i}.tasks`,xn.twicePerAction,{de:`Optionale Aktion \u201E${String(r.key)}\u201C auf Knoten "${e.id}" startet ${o.length} Nachforderungen (${o.join(", ")}) \u2014 ein Ausl\xF6sen fragt die Familie nach EINER Sache; h\xF6chstens eine Nachforderung je Aktion.`,en:`Optional action "${String(r.key)}" on node "${e.id}" starts ${o.length} follow-up requests (${o.join(", ")}) \u2014 one trigger asks the family for ONE thing; at most one follow-up request per action.`})]})}s(DN,"familyRequestActionIssues");function FN(e,t){let n=e.nodes,r=new Map;for(let a of n)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)ct(l)&&r.set(pe(l),l);if(r.size===0)return[];let i=s(a=>{let l=ni(t,a);return l===void 0||l!==null&&l.kind==="entered"&&l.type==="docRef"},"isFileField"),o=s(a=>{let{fields:l,from:d}=a??{};return Array.isArray(l)?l.filter(ct):!xe(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return n.flatMap(a=>{let l=Array.isArray(a.requiresOneOf)?a.requiresOneOf:[],c=(Array.isArray(a.optionalActions)?a.optionalActions:[]).filter(h=>l.includes(h.key)),u=Array.isArray(a.tasks)?a.tasks:[];return c.filter(h=>Array.isArray(h.tasks)&&c.every(w=>w===h||w.when!==void 0)).flatMap(h=>u.flatMap(w=>{if(w.familyRequest===void 0||!h.tasks.includes(w.key))return[];let k=o(w.familyRequest).filter(y=>r.has(pe(y)));return k.length===0?[]:[{...Sn(`nodes.${a.id}.requiresOneOf`,xn.deadlock,{de:`Auf Knoten \u201E${_e(e,a.id,"de")}\u201C (${a.id}) ist die Nachforderung \u201E${String(h.key)}\u201C der einzige Weg durch 'requiresOneOf', und eine Vollst\xE4ndigkeitspr\xFCfung fragt dieselben Felder an (${k.map(y=>je(e,y,"de")).join(", ")}). Ist deren Anfrage offen, lassen sich diese Felder nicht nachfordern \u2014 die Entscheidung bliebe gesperrt. Eine zweite Aktion in 'requiresOneOf' oder andere Felder l\xF6sen das.`,en:`On node "${_e(e,a.id,"en")}" (${a.id}) the follow-up request "${String(h.key)}" is the only way through 'requiresOneOf', and a completeness check asks for the same fields (${k.map(y=>je(e,y,"en")).join(", ")}). While its request is open, these fields cannot be requested \u2014 the decision would stay locked. A second action in 'requiresOneOf' or other fields solve this.`}),severity:"warning"}]}))})}s(FN,"familyRequestDeadlockWarnings");var Aw={key:!0,kind:!0,title:!0,assign:!0,gatesNode:!0,blocks:!0,completableIf:!0,result:!0,when:!0,onConditionReturn:!0,reads:!0,locksEvidence:!0,feedback:!0,description:!0,documents:!0,formView:!0,familyRequest:!0,optional:!0,appointment:!0,params:!0};function DY(e){let t=Ye(e);return new Map((typeof t.workItemTemplates=="function"?t.workItemTemplates(e):[]).map(n=>[n.key,n]))}s(DY,"intrinsicTemplatesOf");function LN(e,t,n){if(n!==void 0&&typeof n!="string")return null;let r=n??t,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=Ye(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:DY(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(LN,"resolveBlocksTargetNode");function FY(e){let t=new Map;for(let r of Zn(e.nodes)){let i=t.get(r.source)??[];i.push(r.target),t.set(r.source,i)}let n=new Map;return r=>{let i=n.get(r);if(i!==void 0)return i;let o=new Set,a=[...t.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...t.get(l)??[]))}return n.set(r,o),o}}s(FY,"reachability");function MN(e){let t=[],n=new Map;for(let o of e.nodes){let a=o;for(let l of Array.isArray(a.tasks)?a.tasks:[]){let d=typeof l.key=="string"?l.key:void 0,c=l.blocks;if(d===void 0||typeof c?.templateKey!="string")continue;let u=typeof c.node=="string"?c.node:o.id;n.set(`${o.id}::${d}`,`${u}::${c.templateKey}`)}}let r=new Map,i=s((o,a)=>{if(r.get(o)==="done")return;if(r.get(o)==="visiting"){let d=[...a.slice(a.indexOf(o)),o],[c,u]=o.split("::");t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${c}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksCycle] Zyklus im 'blocks'-Graphen: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 jedes Mitglied w\xFCrde auf ein anderes warten, keines w\xFCrde je frei.`,en:`[workItems/blocksCycle] Cycle in the 'blocks' graph: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 every member would wait for another, none would ever be released.`},severity:"error"});return}r.set(o,"visiting");let l=n.get(o);l!==void 0&&n.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of n.keys())i(o,[]);return t}s(MN,"checkBlocksCycles");function LY(e){let{requiresOneOf:t,optionalActions:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return new Set;let r=new Set(t.filter(o=>typeof o=="string")),i=new Set;for(let o of n)if(!(typeof o.key!="string"||!r.has(o.key)||!Array.isArray(o.tasks)))for(let a of o.tasks)typeof a=="string"&&i.add(a);return i}s(LY,"tasksOfRequiresOneOf");function qN(e){if(typeof e!="object"||e===null)return!1;let{de:t,en:n}=e;return typeof t=="string"&&t.trim().length>0&&typeof n=="string"&&n.trim().length>0}s(qN,"isFilledBilingual");var MY=["blocks","gatesNode","locksEvidence","completableIf"];function qY(e,t){let n={de:`Task "${t.key}" (Knoten "${t.nodeId}")`,en:`Task "${t.key}" (node "${t.nodeId}")`},r=[];e.feedback!==!0&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${n.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${n.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;(e.kind!=="task"||i?.kind!=="freetext")&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackNeedsFreetext] ${n.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext ('result: { kind: "freetext" }'); erhalten ${e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}`}.`,en:`[workItems/feedbackNeedsFreetext] ${n.en} is a feedback task, so it closes with free text ('result: { kind: "freetext" }'); got ${e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}`}.`}));let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest","appointment"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${n.de} ist eine Feedback-Aufgabe; die Antwort kommt von einer Seite ohne weitere Daten und darf deshalb nicht von ${o.join(", ")} abh\xE4ngen.`,en:`[workItems/feedbackSteersProcess] ${n.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(qY,"feedbackTaskIssues");function KY(e,t){let n=[],r={de:`Task "${t.key}" (Knoten "${t.nodeId}")`,en:`Task "${t.key}" (node "${t.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!qN(i.skipLabel))&&n.push(St(`${t.base}.optional.skipLabel`,{de:`[workItems/optionalSkipLabel] ${r.de} ist optional, braucht daf\xFCr '{ skipLabel: { de, en } }' \u2014 die Worte des Knopfs, mit dem die zust\xE4ndige Person ohne Ergebnis abschlie\xDFt (\u201EKeine Einsch\xE4tzung abgeben"); erhalten ${JSON.stringify(i)}.`,en:`[workItems/optionalSkipLabel] ${r.en} is optional and needs '{ skipLabel: { de, en } }' for that \u2014 the words of the button the responsible person uses to finish without a result ("Give no assessment"); got ${JSON.stringify(i)}.`})),e.kind!=="task"&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalOnApproval] ${r.de} ist eine Freigabe \u2014 optional ist nur eine Aufgabe; eine Freigabe schlie\xDFt mit ihrem Urteil.`,en:`[workItems/optionalOnApproval] ${r.en} is an approval \u2014 only a task can be optional; an approval ends with its verdict.`}));let a=e.result;(a===void 0||typeof a.kind!="string"||!CI({kind:a.kind,writes:a.writes}))&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalNeedsProseResult] ${r.de} ist optional, schlie\xDFt aber ${a===void 0?"ohne Ergebnis":`mit einem ${String(a.kind)}-Ergebnis${a.writes!==void 0?" mit Wert":""}`} \u2014 optional ist nur eine Aufgabe mit Freitext, Empfehlung oder einer Auswahl ohne 'writes': einen Wert, den ein sp\xE4terer Schritt liest, g\xE4be es dann nie.`,en:`[workItems/optionalNeedsProseResult] ${r.en} is optional but ends ${a===void 0?"without a result":`with a ${String(a.kind)} result${a.writes!==void 0?" with a value":""}`} \u2014 only a task with free text, a recommendation or a choice without 'writes' can be optional: a value a later step reads would then never arrive.`}));let l=MY.filter(d=>e[d]!==void 0);return l.length>0&&n.push(St(`${t.base}.${l[0]}`,{de:`[workItems/optionalHolds] ${r.de} ist optional und tr\xE4gt ${l.map(d=>`'${d}'`).join(", ")} \u2014 auf eine optionale Aufgabe wartet nichts: sie h\xE4lt keinen Schritt zur\xFCck. Entweder optional oder zur\xFCckhaltend.`,en:`[workItems/optionalHolds] ${r.en} is optional and carries ${l.map(d=>`'${d}'`).join(", ")} \u2014 nothing waits for an optional task: it holds no step back. Either optional or holding back.`})),t.requiredByRule&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalInRequiresOneOf] ${r.de} ist optional, geh\xF6rt aber zu einer Aktion, die 'requiresOneOf' verlangt \u2014 \u201EKeine Einsch\xE4tzung abgeben" w\xFCrde die Regel erf\xFCllen, ohne dass etwas geschehen ist.`,en:`[workItems/optionalInRequiresOneOf] ${r.en} is optional but belongs to an action that 'requiresOneOf' requires \u2014 "Give no assessment" would satisfy the rule without anything having happened.`})),n}s(KY,"optionalTaskIssues");function St(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(St,"issue");function KN(e,t){let n=[],r=FY(e),i=new Set(na(e).map(o=>o.key));n.push(...FN(e,t));for(let o of e.nodes){let a=o,l=CN(a);n.push(...DN(a));let d=LY(a);n.push(...IN(a,e.nodes));for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=typeof c.key=="string"?c.key:"?",p=`nodes.${o.id}.tasks.${u}`,h=c.kind,w=c.result,k=c.blocks,y=typeof k?.node=="string"&&k.node!==o.id?k.node:void 0;if(typeof k?.templateKey=="string"){let R=typeof k.node=="string"?k.node:o.id,q=e.nodes.find(Y=>Y.id===R),J=(Array.isArray(q?.tasks)?q.tasks:[]).find(Y=>Y.key===k.templateKey)?.blocks;typeof J?.node=="string"&&J.node!==R&&n.push(St(`${p}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${u}" auf Knoten "${o.id}" h\xE4lt "${k.templateKey}" auf Knoten "${R}" zur\xFCck \u2014 das ist selbst eine knoten\xFCbergreifende Aufgabe, die ihren Knoten \xFCberlebt; zur\xFCckgehalten k\xF6nnte sie nach dessen Verlassen weder bearbeitet noch freigegeben werden. Nur Aufgaben, die an ihrem Knoten bleiben, und intrinsische Vorlagen sind Ziele.`,en:`[workItems/blocksCrossNodeTask] Task "${u}" on node "${o.id}" holds back "${k.templateKey}" on node "${R}" \u2014 that is itself a cross-node task that outlives its node; held back, it could be neither worked nor released after the node is left. Only tasks that stay on their node and intrinsic templates are targets.`}))}if(y!==void 0){let R=y;e.nodes.some(q=>q.id===R)&&!r(o.id).has(R)&&n.push(St(`${p}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${u}" auf Knoten "${o.id}" blockiert Knoten "${R}", der von hier aus nicht erreichbar ist \u2014 die Aufgabe entst\xFCnde erst, wenn ihr Ziel schon hinter dem Prozess liegt. Ziel ist derselbe Knoten oder ein sp\xE4terer.`,en:`[workItems/blocksTargetNotAfter] Task "${u}" on node "${o.id}" blocks node "${R}", which cannot be reached from here \u2014 the task would only be created when its target is already behind the process. The target is the same node or a later one.`})),(w===void 0||!_i(w.kind))&&n.push(St(`${p}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${u}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${R}"), hat aber kein 'result' \u2014 eine knoten\xFCbergreifende Aufgabe \xFCberlebt ihren Knoten und wird \xFCber ihr Ergebnis abgeschlossen (Freitext, Empfehlung oder Auswahl).`,en:`[workItems/crossNodeBlocksNeedsResult] Task "${u}" on node "${o.id}" blocks another node ("${R}") but has no 'result' \u2014 a cross-node task outlives its node and is completed through its result (free text, recommendation or choice).`})),l.has(u)&&n.push(St(`${p}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${u}" geh\xF6rt zu einer optionalen Aktion (spawnTasks) auf Knoten "${o.id}" und darf keinen anderen Knoten blockieren \u2014 ihre Zeilen sind die Runde der Aktion.`,en:`[optionalAction/crossNodeBlocks] Task "${u}" belongs to an optional action (spawnTasks) on node "${o.id}" and must not block another node \u2014 its rows are the round of the action.`}))}for(let R of EN(String(h),w,{channelKeys:i,...t?.billingItemKeys!==void 0?{billingItemKeys:t.billingItemKeys}:{},...t?.offerProgram!==void 0?{offerProgram:t.offerProgram}:{}}))n.push(St(`${p}.${R.field}`,{de:`${R.code} ${R.message.de} (Task "${u}" auf Knoten "${o.id}").`,en:`${R.code} ${R.message.en} (task "${u}" on node "${o.id}").`}));let v=c.when,A=s((R,q,_)=>{!xe(q)||ct(q)||n.push(St(R,{de:`[workItems/evidenceNotFormField] ${_} auf Task "${u}" (Knoten "${o.id}") nennt ${je(e,q,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${_} on task "${u}" (node "${o.id}") names ${je(e,q,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");v!==void 0?(A(`${p}.when`,v,"'when'"),c.onConditionReturn!=="respawn"&&c.onConditionReturn!=="stayClosed"&&n.push(St(`${p}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${u}" (Knoten "${o.id}") hat eine Bedingung, aber kein 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 was bei der R\xFCckkehr der Bedingung geschieht, muss entschieden sein.`,en:`[workItems/whenNeedsOnConditionReturn] Task "${u}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):c.onConditionReturn!==void 0&&n.push(St(`${p}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${u}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${u}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let E=c.reads;if(E!==void 0)if(!Array.isArray(E))n.push(St(`${p}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${u}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${u}" (node "${o.id}") must be a list of field addresses.`}));else for(let[R,q]of E.entries())A(`${p}.reads.${R}`,q,"'reads'");let I=c.locksEvidence,C=s((R,q)=>n.push(St(`${p}.locksEvidence`,{de:`[workItems/${R}] Task "${u}" (Knoten "${o.id}") ${q.de}`,en:`[workItems/${R}] Task "${u}" (node "${o.id}") ${q.en}`})),"lockIssue");I!==void 0&&I!==!0&&C("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(I)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(I)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),I===!0&&(E===void 0&&v===void 0&&C("locksEvidenceWithoutEvidence",{de:"sperrt seine Belege, hat aber weder 'reads' noch 'when' \u2014 es gibt nichts, worauf die Entscheidung beruht.",en:"locks its evidence but has neither 'reads' nor 'when' \u2014 there is nothing the decision rests on."}),(w===void 0||!_i(w.kind))&&C("locksEvidenceNeedsRecordedResult",{de:"sperrt seine Belege, schlie\xDFt aber nicht mit einem erfassten Ergebnis (Freitext, Empfehlung, Auswahl) \u2014 nur eine Entscheidung, die das Team wieder\xF6ffnen kann, darf Belege sperren (ein Termin bleibt gebucht).",en:"locks its evidence but does not end with a recorded result (free text, recommendation, choice) \u2014 only a decision the team can reopen may lock evidence (an appointment stays booked)."}),l.has(u)&&C("locksEvidenceOnOptionalAction",{de:"geh\xF6rt zu einer optionalen Aktion (spawnTasks) \u2014 ihre Zeilen sind die Runde der Aktion, wieder\xF6ffnen l\xE4sst sie sich nicht; Belege sperrt nur eine Knotenaufgabe.",en:"belongs to an optional action (spawnTasks) \u2014 its rows are the round of the action and cannot be reopened; only a node task locks evidence."})),n.push(...PN({graph:e,node:a,task:c,onTrigger:l,specCtx:t}));let $=Object.keys(c).filter(R=>!Object.hasOwn(Aw,R));$.length>0&&n.push(St(`${p}.${$[0]}`,{de:`[workItems/unknownKey] Task "${u}" (Knoten "${o.id}") tr\xE4gt ${$.map(R=>`'${R}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(Aw).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${u}" (node "${o.id}") carries ${$.map(R=>`'${R}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(Aw).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let b=c.description;b!==void 0&&!qN(b)&&n.push(St(`${p}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${u}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(b)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${u}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(b)}.`})),c.feedback!==void 0&&n.push(...qY(c,{key:u,nodeId:o.id,base:p})),c.optional!==void 0&&n.push(...KY(c,{key:u,nodeId:o.id,base:p,requiredByRule:d.has(u)}))}}return n}s(KN,"checkNodeTasks");function jN(e){let t=e.indexOf(":"),n=t===-1?"":e.slice(0,t),r=t===-1?"":e.slice(t+1).trim();if(n==="artifact"&&r.length>0)return{kind:n,key:r};let i=mo(r);return(n==="field"||n==="document")&&i!==null?{kind:n,address:i}:ae("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel>, field:$node.<Formular>.admission.<Feld> oder document:$node.<Knoten>.document.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key>, field:$node.<form>.admission.<field> or document:$node.<node>.document.`})}s(jN,"parseTaskDocumentRef");function Ew(e){return e.kind==="artifact"?`artifact:${e.key}`:`${e.kind}:${pe(e.address)}`}s(Ew,"taskDocumentId");function si(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(si,"issue");function VN(e){return Array.isArray(e.tasks)?e.tasks:[]}s(VN,"tasksOf");function jY(e){let t=new Map;for(let n of e){let{id:r,artifacts:i}=n;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&t.set(o.key,[...t.get(o.key)??[],{nodeId:r,slot:o}])}return t}s(jY,"artifactSlotDeclarations");function VY(e){return e.flatMap(t=>{let{id:n,artifacts:r}=t;return(Array.isArray(r)?r:[]).filter(i=>!Ff(i?.type)).map(i=>({nodeId:String(n),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(VY,"unknownArtifactSlotTypes");function BN(e){let t=[];for(let{nodeId:n,slotKey:r,type:i}of VY(e.nodes))t.push(si(`nodes.${n}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${n}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${Ws.join(", ")}.`,en:`[artifact/unknownType] Node "${n}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${Ws.join(", ")}.`}));for(let[n,r]of jY(e.nodes))for(let i of r.slice(1))t.push(si(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${n}", den schon "${r[0].nodeId}" deklariert \u2014 jeder Slot-Schl\xFCssel geh\xF6rt genau einem Knoten.`,en:`[governedDocument/slotKeyTaken] Node "${i.nodeId}" declares the document slot "${n}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return t}s(BN,"checkArtifactSlotKeys");function UN(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){let r=typeof n=="object"&&n!==null?n:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)t.push({kind:"artifact",key:r.key});else if((r.kind==="field"||r.kind==="document")&&i==="address,kind")t.push({kind:r.kind,address:r.address});else return null}return t}s(UN,"authoredRefs");function BY(e){return e.scope==="node"&&(e.key===bl||e.key===Cs||e.key===Ps)&&e.path===void 0}s(BY,"isDocumentAddress");function GN(e){let t=[];for(let n of e.nodes)for(let r of VN(n)){if(r.documents===void 0)continue;let i=typeof r.key=="string"?r.key:"?",o=`nodes.${n.id}.tasks.${i}.documents`,a={de:`Task "${i}" (Knoten "${n.id}")`,en:`Task "${i}" (node "${n.id}")`},l=UN(r.documents);if(l===null){t.push(si(o,{de:`[workItems/documentsInvalid] 'documents' auf ${a.de} muss eine nicht leere Liste von { kind: 'artifact', key } (eigener Slot), { kind: 'field', address } (Dateifeld eines Formulars) oder { kind: 'document', address } (Dokument eines anderen Knotens) sein, erhalten ${JSON.stringify(r.documents)}.`,en:`[workItems/documentsInvalid] 'documents' on ${a.en} must be a non-empty list of { kind: 'artifact', key } (own slot), { kind: 'field', address } (file field of a form) or { kind: 'document', address } (document of another node), got ${JSON.stringify(r.documents)}.`}));continue}let d=new Set;for(let c of l){if(c.kind!=="artifact"&&!xe(c.address))continue;let u=c.kind==="artifact"?Ew(c):Ew({kind:c.kind,address:c.address});d.has(u)&&t.push(si(o,{de:`[workItems/documentsDuplicate] ${a.de} verweist zweimal auf ${u}.`,en:`[workItems/documentsDuplicate] ${a.en} refers to ${u} twice.`})),d.add(u),c.kind==="artifact"&&!nO(n,c.key)&&t.push(si(o,{de:`[workItems/documentsUnknownArtifact] ${a.de} verweist auf das Dokument "${c.key}", aber der Knoten deklariert keinen solchen Slot \u2014 das Dokument eines anderen Knotens ist { kind: 'document', address: $node.<knoten>.document }.`,en:`[workItems/documentsUnknownArtifact] ${a.en} refers to the document "${c.key}", but the node declares no such slot \u2014 the document of another node is { kind: 'document', address: $node.<node>.document }.`})),c.kind==="field"&&!ct(c.address)&&t.push(si(o,{de:`[workItems/documentsInvalid] ${a.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,c.address,"de")}.`,en:`[workItems/documentsInvalid] ${a.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,c.address,"en")}.`})),c.kind==="document"&&!BY(c.address)&&t.push(si(o,{de:`[workItems/documentsInvalid] ${a.de}: ein Dokument eines anderen Knotens ist dessen ganzes Dokument ($node.<knoten>.document), nicht ${pe(c.address)}.`,en:`[workItems/documentsInvalid] ${a.en}: a document of another node is that node's whole document ($node.<node>.document), not ${pe(c.address)}.`}))}}return t}s(GN,"checkTaskDocuments");function zN(e,t){let n=[];for(let r of e.nodes)for(let i of VN(r)){let o=UN(i.documents);if(o===null)continue;let a=typeof i.key=="string"?i.key:"?",l=`nodes.${r.id}.tasks.${a}.documents`;for(let d of o){if(d.kind!=="field"||!ct(d.address))continue;let c=ni(t,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Vs("taskDocument",js(c));if(p==="repeated"){n.push(si(l,{de:`[workItems/documentsUnknownField] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Dokument der Anmeldung.`,en:`[workItems/documentsUnknownField] Task "${a}" (node "${r.id}") refers to the field ${u.en} \u2014 a field in a repeated group is not a single document of the application.`}));continue}p==="notDocument"&&n.push(si(l,{de:`[workItems/documentsNotDocument] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de}, das keine Datei enth\xE4lt \u2014 nur Datei-Felder (docRef) sind Dokumente.`,en:`[workItems/documentsNotDocument] Task "${a}" (node "${r.id}") refers to the field ${u.en}, which holds no file \u2014 only file fields (docRef) are documents.`}))}}return n}s(zN,"checkTaskDocumentFields");var Tw=["form","documents"],UY=/^[a-z][a-zA-Z0-9_-]*$/;function GY(e){let t=new Map,n=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])t.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){t.set(i.key,"other");for(let o of i.itemTemplate)t.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(GY,"fieldPlaces");function WN(e,t,n){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!UY.test(o)){r.push({severity:"error",path:`${n(a)}.key`,code:"view.invalid-key",message:{de:`${t.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${t.en}: '${String(o)}' is no valid key (a lower-case letter first, then letters, digits, - or _).`}});return}i.has(o)&&r.push({severity:"error",path:`${n(a)}.key`,code:"view.duplicate-key",message:{de:`${t.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${t.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(WN,"keyIssues");function zY(e,t,n){return e==="document"?null:e===void 0?{severity:"error",path:n,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${t}'.`,en:`View: the form has no field '${t}'.`}}:e==="row"?{severity:"error",path:n,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${t}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${t}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:n,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${t}' enth\xE4lt keine Datei.`,en:`View: the field '${t}' holds no file.`}}}s(zY,"fieldIssue");function WY(e,t,n){let r=[];Tw.includes(e.key)&&r.push({severity:"error",path:`${t}.key`,code:"view.reserved-key",message:{de:`Der Ansichtsschl\xFCssel '${e.key}' ist f\xFCr die Standardansicht reserviert.`,en:`The view key '${e.key}' is reserved for the standard view.`}});let i=e.groups;i.length===0&&r.push({severity:"error",path:`${t}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...WN(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${t}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${t}.groups[${l}]`,c=a.fields;c.length===0&&r.push({severity:"error",path:`${d}.fields`,code:"view.empty",message:{de:`Gruppe '${a.key}' der Ansicht '${e.key}' hat keine Felder.`,en:`Group '${a.key}' of view '${e.key}' has no fields.`}}),c.forEach((u,p)=>{let h=`${d}.fields[${p}]`,w=zY(n.get(u),u,h);w!==null&&r.push(w),o.has(u)&&r.push({severity:"error",path:h,code:"view.field-twice",message:{de:`Ansicht '${e.key}': Das Feld '${u}' steht mehrfach; eine Datei hat einen Platz.`,en:`View '${e.key}': the field '${u}' is listed more than once; a file has one place.`}}),o.add(u)})}),r}s(WY,"viewIssues");function YY(e){if(!Array.isArray(e))return"views";for(let[t,n]of e.entries()){let r=n?.groups;if(!Array.isArray(r))return`views[${t}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${t}].groups[${i}].fields`}}return null}s(YY,"malformedAt");function YN(e){let t=e.views;if(t===void 0)return[];let n=YY(t);if(n!==null)return[{severity:"error",path:n,code:"view.malformed",message:{de:`${n} hat nicht die Form einer Ansicht: views ist eine Liste von { key, label, groups }, groups eine Liste von { key, label, fields }, fields eine Liste von Feldschl\xFCsseln.`,en:`${n} is not shaped like a view: views is a list of { key, label, groups }, groups a list of { key, label, fields }, fields a list of field keys.`}}];let r=GY(e);return[...WN(t.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...t.flatMap((i,o)=>WY(i,`views[${o}]`,r))]}s(YN,"formViewIssues");function rp(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(rp,"issue");function HN(e,t,n,r){let i=e;if(i===null||typeof i!="object"||typeof i.form!="string"||typeof i.key!="string")return[rp(t,{de:`[workItems/formViewInvalid] 'formView' auf ${n.de} muss { form: <Formularknoten>, key: <Ansicht> } sein.`,en:`[workItems/formViewInvalid] 'formView' on ${n.en} must be { form: <form node>, key: <view> }.`})];let o=r?.formViewKeysByFormNode;if(o===void 0)return[];let a=o.get(i.form);return a===void 0?[rp(t,{de:`[workItems/formViewUnknownForm] ${n.de} nennt das Formular "${i.form}", aber kein Formularknoten hei\xDFt so.`,en:`[workItems/formViewUnknownForm] ${n.en} names the form "${i.form}", but no form node has that id.`})]:a.has(i.key)||Tw.includes(i.key)?[]:[rp(t,{de:`[workItems/formViewUnknown] ${n.de} nennt die Ansicht "${i.key}", aber das Formular "${i.form}" hat keine solche Ansicht.`,en:`[workItems/formViewUnknown] ${n.en} names the view "${i.key}", but the form "${i.form}" has no such view.`})]}s(HN,"viewIssues");function JN(e,t){let n=[];for(let r of e.nodes){if(r.formView!==void 0){let i={de:`Knoten "${r.id}"`,en:`node "${r.id}"`};r.type!=="decision"?n.push(rp(`nodes.${r.id}.formView`,{de:`[workItems/formViewInvalid] ${i.de}: 'formView' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[workItems/formViewInvalid] ${i.en}: 'formView' on a node applies to a decision only; a task carries its own.`})):n.push(...HN(r.formView,`nodes.${r.id}.formView`,i,t))}for(let i of Array.isArray(r.tasks)?r.tasks:[]){if(i.formView===void 0)continue;let o=String(i.key);n.push(...HN(i.formView,`nodes.${r.id}.tasks.${o}.formView`,{de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},t))}}return n}s(JN,"checkTaskFormViews");var Pn="traeger",QN={de:"Tr\xE4ger",en:"Provider"};function ia(e){let t=e.inputs?.[Pn];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(ia,"traegerKeyOfNode");var ip={name:"input.traeger.name",address:"input.traeger.anschrift"},Lhe=Object.values(ip);var ZN="governedDocument",_o="prepareDocument",ql="prepareDocument:revision",Fr="releaseApproval",No="documentResponse",oa="coverLetterResponse",op="confirmCoverLetter",sp="requestCoverLetterRevision",sa="coverLetterConfirmation",Lr="responseCheck",ap="returnSigned";var XN="requestApproval";var eC="issueDocument",tC="correctInPlace",nC="rescindAndReissue",lp="requestChange";var aa="releaseArtifact",cn="signingRecovery",dp="resendESignature",Co="switchToPaper";var $w=new Set([_o,ql]),rC=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],cp=["upload","resolver","template","none"],Po=1,Do=366,ai="responseDueInDays";function Fo(e){let t=e.inputs?.[sa];return t?.kind==="literal"&&t.value===!0}s(Fo,"coverLetterConfirmationOf");function Kl(e){let t=e.inputs?.[ai];return t?.kind==="literal"&&jl(t.value)?t.value:void 0}s(Kl,"responseDueInDaysForVocabulary");function jl(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Po&&e<=Do}s(jl,"isValidResponseDueInDays");var up=["generatedAt","responseDueInDays","countersignature"],Lo=["release","none"],fp=["confirm","signedUpload","signedUploadChecked","eSignature"];var HY={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},iC={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},oC={...iC,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},JY={...oC,kind:"eSignature",issuesBy:"provider"},li={confirm:HY,signedUpload:iC,signedUploadChecked:oC,eSignature:JY};function di(e){let t=e.responseStrategy;if(typeof t=="string"&&t in li)return li[t];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(t)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(di,"responseStrategyOf");function pp(e){if(e.type!==ZN||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in li?li[t].acceptEvent==="contractEvent":!1}s(pp,"isFamilySignedContractNode");function da(e){return e.label}s(da,"governedDocTitle");function Rw(e){return e.approval==="release"?XN:eC}s(Rw,"submitActionId");function sC(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Rw(e)],gatesNode:!0,advancesNode:!0}}s(sC,"producerTemplate");function QY(e){return e.titles?.respond??e.label}s(QY,"responseTitle");var la={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Iw(e){let t=di(e),n=[];if(e.production!=="none"&&n.push(sC(e,_o,e.titles?.prepare??la),sC(e,ql,e.titles?.revise??la)),e.approval==="release"&&n.push({key:Fr,recipient:"internal",title:e.titles?.approve??la,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:No,recipient:"external",title:QY(e),unlocks:t.producesResponseArtifact?[t.checksReturn?ap:t.acceptOutcomeId,t.declineOutcomeId,lp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...Kl(e)!==void 0?{dueInDays:Kl(e)}:{}}),Fo(e)){let r=da(e);n.push({key:oa,recipient:"external",title:{de:`${r.de}: Schreiben best\xE4tigen`,en:`${r.en}: confirm the letter`},unlocks:[op,sp,t.declineOutcomeId],advancesNode:!0,...Kl(e)!==void 0?{dueInDays:Kl(e)}:{}})}if(t.checksReturn&&n.push({key:Lr,recipient:"internal",title:e.titles?.check??la,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=da(e);n.push({key:cn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[dp,Co],gatesNode:!1,advancesNode:!1})}return n}s(Iw,"governedDocIntrinsicTemplates");function ZY(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let t=e.artifacts??[];t.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${t.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let n=t[0];return(typeof n.key!="string"||n.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),n}s(ZY,"governedDocSlot");function mp(e){return ZY(e).key}s(mp,"governedDocSlotKey");var Xn="processFooter";var hp="countersign",Ow="countersign",aC="countersigned",lC="countersigning",dC="countersigned";var cC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},Vl=["scan","eSignature"],gp="service_provider:1",uC=["countersigning","awaitingSignature","signatureStalled","done"],fC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function pC(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(pC,"traegerSignatoryMissingReason");function er(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(er,"issue");function yp(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&xe(r)&&r.scope==="node"&&r.owner===t})}s(yp,"countersignersOf");function Bl(e){return e.signing==="eSignature"}s(Bl,"isElectronic");function XY(e,t){if(t===void 0||t.sendable||!Bl(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[er(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${n}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${t.reason.en}`})]}s(XY,"countersignProviderIssues");function eH(e,t,n){if(n.scope!=="node")return[];let r=e.nodes.find(o=>o.id===n.owner);if(r===void 0)return[];let i=[];return pp(r)||i.push("sourceNotCheckedContract"),yp(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s(eH,"countersignContractRefusals");function mC(e){let t=e.inputs?.dueInDays;return t?.kind==="literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&t.value>=1?t.value:void 0}s(mC,"validDueInDays");function tH(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!Vl.includes(o))return[er(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[cn];if(!Bl(e))return a===void 0?[]:[er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...nH(e,t,n),...rH(e,t,n),...XY(e,n?.signingProvider)),l}s(tH,"signingIssues");function gC(e,t){let n=e.contract;if(!(!xe(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(gC,"contractNodeOf");function nH(e,t,n){let r=gC(e,t),i=r===void 0?null:ia(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[er(e,"signing",pC(o.name))]}s(nH,"traegerSignatoryIssues");function rH(e,t,n){let r=gC(e,t);if(r===void 0)return[];let i=n?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(gp)||l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${gp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${gp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(rH,"traegerAnchorIssues");var _w=100;async function iH(e,t){let n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",t.node.id)).take(_w+1);n.length>_w&&F(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${_w} rows`);let r=n.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===cn)?"signatureStalled":r.some(o=>i(o)===hp)?"countersigning":Bl(t.node)?"awaitingSignature":"done"}s(iH,"countersignCurrentState");var hC={[lC]:{label:ne("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:ne("Gegenzeichnung","Countersignature"),scope:"node"},external:Ze(ne("Vertrag unterschrieben","Contract signed"),"blue",ne("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),ne("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},yC={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:aC,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:hC,progressEvents:Ft(hC),notificationEvents:s(()=>[{id:dC,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:Ow,kind:"internal",label:cC,surface:Xn,availableIn:["countersigning"]},...Bl(e)?[{id:Co,kind:"internal",surface:Xn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:hp,recipient:"internal",title:e.titles?.countersign??la,unlocks:[Ow],advancesNode:!0,...mC(e)!==void 0?{dueInDays:mC(e)}:{}},...Bl(e)?[{key:cn,recipient:"internal",title:fC,unlocks:[Co],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:uC,currentState:iH,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[hp];(typeof a!="string"||a.length===0)&&r.push(er(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Ti(e.titles?.countersign)||r.push(er(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(er(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...tH(e,t,n));let d=e.contract;if(!xe(d))return r;let c=eH(t,e.id,d);if(c.length===0)return r;let u=t.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(er(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let p=yp(t,u.id).filter(h=>h.id!==e.id);r.push(er(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${p.map(h=>`"${h.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${p.map(h=>`"${h.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};function oH(e){return pp(e)?ia(e):null}s(oH,"traegerSignerOf");var sH=s(e=>e.type==="end"&&To(e)==="approved","isApprovedEnd");function wC(e){let t=[];for(let n of e.nodes){let r=oH(n);if(r===null)continue;let i=yp(e,n.id).map(u=>u.id),o=DO(e,n.id,new Set(i),sH);if(o===null)continue;let a=n.label?.de||n.id,l=n.label?.en||n.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${n.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${n.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${n.id}) erzeugt einen Vertrag, den der Tr\xE4ger \u201E${r}\u201C mitunterschreibt, aber keine Gegenzeichnung nennt ihn \u2014 der Vertrag w\xFCrde nie unterschrieben und nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${n.id}) generates a contract the legal entity "${r}" co-signs, but no countersignature names it \u2014 the contract would never be signed and never billed. ${d.en}`}:{de:`[countersign/missingForContract] \u201E${a}\u201C (${n.id}): ein Weg erreicht das Ende \u201E${o}\u201C (Ergebnis approved), ohne durch die Gegenzeichnung ${i.map(u=>`\u201E${u}\u201C`).join(", ")} zu laufen \u2014 dort bliebe der Vertrag ohne Unterschrift des Tr\xE4gers \u201E${r}\u201C und w\xFCrde nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${n.id}): a path reaches the end "${o}" (outcome approved) without passing the countersignature ${i.map(u=>`"${u}"`).join(", ")} \u2014 there the contract would lack the signature of the legal entity "${r}" and never be billed. ${d.en}`};t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}`,reason:c,severity:"error"})}return t}s(wC,"checkCountersignCoverage");function aH(e){let t="error",n=new Map;for(let a of Zn(e.nodes)){let l=n.get(a.source)??[];l.push({id:a.id,target:a.target}),n.set(a.source,l)}let r=[],i=new Set,o=Jf(e.nodes.map(a=>a.id),a=>(n.get(a)??[]).map(({id:l,target:d})=>({target:d,edge:l})));for(let a of o)i.has(a.edge)||(i.add(a.edge),r.push({layer:"GRAPH",kind:"cycle",path:`edge.${a.edge}`,reason:{de:`Zyklus \xFCber Kante ${a.source} \u2192 ${a.target}`,en:`Cycle through edge ${a.source} \u2192 ${a.target}`},severity:t}));return r}s(aH,"checkAcyclic");function lH(e){let t=[],n=new Set(e.nodes.map(i=>i.id)),r="error";for(let i of e.nodes){let o=i.next;if(o)for(let[a,l]of Object.entries(o))n.has(l.to)||t.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.next.${a}`,reason:{de:`${i.label.de}: next.${a} verweist auf nicht-existenten Knoten '${l.to}'`,en:`${i.label.en}: next.${a} points to a node that does not exist: '${l.to}'`},severity:"error"});if(i.type!=="end"&&!(!i.outcomes||i.outcomes.length===0))for(let a of i.outcomes)(!o||!(a.id in o))&&t.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.outcome.${a.id}`,reason:{de:`${i.label.de}: Outcome '${a.label.de}' fehlt im next-Mapping`,en:`${i.label.en}: outcome '${a.label.en}' is missing from the next mapping`},severity:r})}return t}s(lH,"checkNextTargets");function dH(e){let t=[];for(let n of e.nodes){let r=n.next;if(!r)continue;let i=zy(n),o=new Set(i?i.map(a=>a.id):[Ys]);for(let a of Object.keys(r))o.has(a)||t.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${n.id}.next.${a}`,reason:{de:`${n.label.de}: next-Schl\xFCssel '${a}' ist kein g\xFCltiges Outcome dieses Knotens (erlaubt: ${[...o].join(", ")}) \u2014 die Kante w\xFCrde im Editor verschwinden`,en:`${n.label.en}: next key '${a}' is not a valid outcome of this node (allowed: ${[...o].join(", ")}) \u2014 the edge would disappear in the editor`},severity:"error"})}return t}s(dH,"checkNextOutcomesKnown");function cH(e){let t=[],n=new Set(Zn(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!n.has(o.id));return r.length===0?t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:`Mehrere Start-Knoten (${r.map(o=>o.label.de).join(", ")})`,en:`Multiple start nodes (${r.map(o=>o.label.en).join(", ")})`},severity:"warning"}),e.nodes.filter(o=>o.type==="end").length===0&&t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),t}s(cH,"checkStartEnd");function uH(e){let t=new Map;for(let r of Zn(e.nodes))t.set(r.source,(t.get(r.source)??0)+1);let n=[];for(let r of e.nodes)r.type!=="end"&&(t.get(r.id)??0)===0&&n.push({layer:"GRAPH",kind:"startEnd",path:`node.${r.id}`,reason:{de:`${r.label.de}: keine ausgehende Kante`,en:`${r.label.en}: no outgoing edge`},severity:"warning"});return n}s(uH,"checkNoOutgoingEdge");function fH(e){return e.nodes.filter(t=>!Qg(t.id)).map(t=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${t.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${mr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${t.id}": a node id is an identifier without a dot (${mr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(fH,"checkNodeIdFormat");function pH(e){let t=new Set(e.nodes.map(r=>r.id)),n=[];for(let r of Zn(e.nodes))t.has(r.source)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Quelle '${r.source}' nicht gefunden`,en:`Edge ${r.id}: source '${r.source}' not found`},severity:"error"}),t.has(r.target)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Ziel '${r.target}' nicht gefunden`,en:`Edge ${r.id}: target '${r.target}' not found`},severity:"error"});return n}s(pH,"checkEdgeEndpoints");var mH=new Set(["countersignature"]);function hH(e){let t=[],n=s((o,a)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:{de:`[graph/retiredField] ${a.de}`,en:`[graph/retiredField] ${a.en}`},severity:"error"})},"retired"),r={de:"Preise rechnet der Vertragsgenerator (`prices`), nicht der Workflow \u2014 binde Rang und Reduktion an seine Eing\xE4nge.",en:"Prices are computed by the contract generator (`prices`), not the workflow \u2014 bind rank and reduction to its inputs."},i=e;"pricingRules"in i&&n("pricingRules",r);for(let[o,a]of(Array.isArray(i.processStore)?i.processStore:[]).entries())for(let l of["derive","absentValue"])a!==null&&typeof a=="object"&&l in a&&n(`processStore.${o}.${l}`,r);for(let o of e.nodes)for(let a of o.tasks??[]){let l=a.result;l!==null&&typeof l=="object"&&"prices"in l&&n(`nodes.${o.id}.tasks.${a.key}.result.prices`,r)}for(let o of e.nodes){let a=o,l={de:`Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id})`,en:`Node "${_e(e,o.id,"en")}" (${o.id})`};for(let[c,u]of Object.entries(a.next??{}))u!==null&&typeof u=="object"&&"emits"in u&&n(`nodes.${o.id}.next.${c}.emits`,{de:`${l.de}: \`next.${c}.emits\` gibt es nicht mehr \u2014 ein Ausgang routet nur; ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`next.${c}.emits\` no longer exists \u2014 an outcome only routes; a node reads data through addresses in its own fields.`});for(let c of Array.isArray(a.outcomes)?a.outcomes:[])c!==null&&typeof c=="object"&&"emits"in c&&n(`nodes.${o.id}.outcomes.${String(c.id)}.emits`,{de:`${l.de}: \`emits\` am Ausgang "${String(c.id)}" gibt es nicht mehr \u2014 ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`emits\` on the outcome "${String(c.id)}" no longer exists \u2014 a node reads data through addresses in its own fields.`});"targetFormNodeId"in a&&n(`nodes.${o.id}.targetFormNodeId`,{de:`${l.de}: \`targetFormNodeId\` gibt es nicht mehr \u2014 welches Formular freigeschaltet wird, sagt die Adresse, an die der Eingang \`inputs.target\` gebunden ist ($node.<formular>.admission).`,en:`${l.en}: \`targetFormNodeId\` no longer exists \u2014 the address the input \`inputs.target\` is bound to says which form is unlocked ($node.<form>.admission).`}),"wires"in a&&n(`nodes.${o.id}.wires`,{de:`${l.de}: Datenkanten (\`wires\`) gibt es nicht mehr \u2014 jedes Feld, das Daten eines anderen Knotens liest, tr\xE4gt selbst die volle Adresse ($node.\u2026, $task.\u2026, $env.\u2026).`,en:`${l.en}: data edges (\`wires\`) no longer exist \u2014 every field that reads data of another node carries the full address itself ($node.\u2026, $task.\u2026, $env.\u2026).`});for(let[c,u]of Object.entries(a.inputs??{}))u!==null&&typeof u=="object"&&u.kind==="binding"&&"path"in u&&n(`nodes.${o.id}.inputs.${c}.path`,{de:`${l.de}: Der Eingang \u201E${c}\u201C ist \xFCber einen Pfad (\`path\`) gebunden \u2014 eine Bindung tr\xE4gt die volle Adresse (\`address\`) dessen, was sie liest.`,en:`${l.en}: The input "${c}" is bound through a path (\`path\`) \u2014 a binding carries the full address (\`address\`) of what it reads.`});o.type==="governedDocument"&&"resolver"in a&&n(`nodes.${o.id}.resolver`,{de:`${l.de}: \`resolver\` gibt es nicht mehr \u2014 der Generator ist der Eingang \`inputs.contractGenerator\` ({ kind, key }), seine Parameter stempelt die Plattform (\`generatorStamp\`), ein im Cockpit erg\xE4nzter Parameter ist sein Eingang \`{ kind: "cockpit" }\`.`,en:`${l.en}: \`resolver\` no longer exists \u2014 the generator is the input \`inputs.contractGenerator\` ({ kind, key }), the platform stamps its parameters (\`generatorStamp\`), a parameter completed in the cockpit is its input \`{ kind: "cockpit" }\`.`});let d=a.template;if(o.type==="governedDocument"&&d!==null&&typeof d=="object")for(let c of["key","cockpitFields"])c in d&&n(`nodes.${o.id}.template.${c}`,{de:`${l.de}: \`template.${c}\` gibt es nicht mehr \u2014 ${c==="key"?"die Vorlage ist der Eingang `inputs.documentTemplate`":'ein im Cockpit erg\xE4nzter Parameter ist sein Eingang `{ kind: "cockpit" }`'}.`,en:`${l.en}: \`template.${c}\` no longer exists \u2014 ${c==="key"?"the template is the input `inputs.documentTemplate`":'a parameter completed in the cockpit is its input `{ kind: "cockpit" }`'}.`});if(o.type==="setFlag")for(let c of["target","flagKey","value"])c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es am setFlag-Knoten nicht mehr \u2014 Formular, Merkmal und Wert sind die Eing\xE4nge \`inputs.target\` (gebunden an die Adresse $node.<formular>.admission), \`inputs.flagKey\` und \`inputs.value\` (feste Werte).`,en:`${l.en}: \`${c}\` no longer exists on a setFlag node \u2014 form, flag and value are the inputs \`inputs.target\` (bound to the address $node.<form>.admission), \`inputs.flagKey\` and \`inputs.value\` (literals).`});for(let c of Object.keys(Oy[o.type]??{}))c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es als Knoteneigenschaft nicht mehr \u2014 es ist der Eingang \`inputs.${c}\` (ein fester Wert im Parameter-Bereich).`,en:`${l.en}: \`${c}\` no longer exists as a node property \u2014 it is the input \`inputs.${c}\` (a fixed value among the parameters).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.assign;u===null||typeof u!="object"||!("userId"in u)||n(`nodes.${o.id}.tasks.${String(c.key)}.assign.userId`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${String(c.key)}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`})}for(let c of _y[o.type]??[])c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es nicht mehr \u2014 dieser Knotentyp liest es nicht.`,en:`${l.en}: \`${c}\` no longer exists \u2014 this node type does not read it.`});for(let[c,u]of Object.entries(vO[o.type]??{}))c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&n(`nodes.${o.id}.adoptForm`,{de:`${l.de}: \`adoptForm: true\` gibt es nicht mehr \u2014 \`adoptForm\` ist die Adresse des \xFCbernommenen Formulars ($node.<anlegender Formularknoten>.admission).`,en:`${l.en}: \`adoptForm: true\` no longer exists \u2014 \`adoptForm\` is the address of the adopted form ($node.<creating form node>.admission).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.result?.kind;typeof u=="string"&&mH.has(u)&&n(`nodes.${o.id}.tasks.${String(c.key)}.result`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: das Ergebnis \u201E${u}" gibt es nicht mehr \u2014 die Gegenzeichnung ist der Knotentyp \u201EUnterschrift (intern)" (countersign).`,en:`Task "${String(c.key)}" on ${l.en}: the result "${u}" no longer exists \u2014 the countersignature is the node type "Signature (internal)" (countersign).`})}}return t}s(hH,"checkRetiredDataFields");function ca(e,t){return t?.wiring&&t.layout?{wiring:t.wiring,layout:t.layout}:null}s(ca,"resolveLayoutContext");function gH(e,t){let n=ca(e,t);if(!n)return e.nodes.some(o=>(Ye(o)?.progressEvents?.length??0)>0)?[{layer:"GRAPH",kind:"progressState",path:"graph.progressWiring",reason:{de:`Graph emittiert Progress-Events, aber (Layout, Wiring) konnte nicht aufgel\xF6st werden (Wiring ${t?.wiring?"vorhanden":"fehlt"}, Layout ${t?.layout?"vorhanden":"fehlt"}) \u2014 der Engine wirft beim Spiegeln zur Laufzeit. Der Workflow-Entwurf muss progressLayout und progressWiring tragen.`,en:`The graph emits progress events, but (layout, wiring) could not be resolved (wiring ${t?.wiring?"present":"missing"}, layout ${t?.layout?"present":"missing"}) \u2014 the engine throws at runtime when mirroring. The workflow draft must carry progressLayout and progressWiring.`},severity:"error"}]:[];let r=[];for(let i of e.nodes){let a=Ye(i)?.progressEvents;if(a)for(let l of a){let d=Bs(n.wiring,{id:i.id,type:i.type},l);if(!d){r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Progress-Event '${l}' ist im Wiring (Layout '${n.layout.id}') keinem (Bus, State) zugeordnet \u2014 der Engine wirft beim Spiegeln`,en:`${i.type} '${i.id}': progress event '${l}' is not mapped to any (bus, state) in the wiring (layout '${n.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=_f(n.layout,d.bus)}catch{r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf unbekannten Bus '${d.bus}' im Layout '${n.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${n.layout.id}'`},severity:"error"});continue}Tl(c,d.state)||r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf State '${d.state}', der nicht im Bus '${d.bus}' deklariert ist`,en:`${i.type} '${i.id}': event '${l}' points to state '${d.state}', which is not declared in bus '${d.bus}'`},severity:"error"})}}return r}s(gH,"checkProgressEventMappings");function yH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses){if(!i.boards||i.boards.length===0)continue;let o=new Set(i.unboarded??[]),a=new Set;for(let l of i.boards)for(let d of l.columns)for(let c of d.states)a.add(c),Tl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${l.id}.column.${d.id}.${c}`,reason:{de:`Board '${l.id}', Spalte '${d.id}' referenziert State '${c}', der nicht im Bus '${i.key}' deklariert ist`,en:`Board '${l.id}', column '${d.id}' references state '${c}', which is not declared in bus '${i.key}'`},severity:"error"});for(let l of i.states)a.has(l.id)||o.has(l.id)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${l.id}`,reason:{de:`State '${l.id}' (${l.label.de}) erscheint in keiner Board-Spalte und nicht in 'unboarded' \u2014 nicht darstellbar`,en:`State '${l.id}' (${l.label.en}) appears in no board column and not in 'unboarded' \u2014 it cannot be displayed`},severity:"error"})}return r}s(yH,"checkProgressBoardCoverage");function wH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of ze){let l=new Map;for(let d of o.columns){if(!Ti(d.label))continue;let c=d.label[a],u=c.trim().toLocaleLowerCase(a),p=l.get(u);if(p===void 0){l.set(u,d.id);continue}r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${o.id}.column.${d.id}.label.${a}`,reason:{de:`Board '${o.id}' hat zwei Spalten mit dem Label '${c}' (${a}) ('${p}' und '${d.id}') \u2014 f\xFCr Lesende nicht unterscheidbar. F\xFChre die Spalten zusammen (states beider in EINE Spalte) oder vergib unterschiedliche Labels.`,en:`Board '${o.id}' has two columns with the label '${c}' (${a}) ('${p}' and '${d.id}') \u2014 readers cannot tell them apart. Merge the columns (put the states of both into ONE column) or give them different labels.`},severity:"error"})}}return r}s(wH,"checkProgressBoardDistinctLabels");function kH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses)for(let o of i.states){let a=Nf(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`Terminal-State '${o.id}' hat keine Terminal-Semantik im Bus '${i.key}' \u2014 der Engine wirft beim Versiegeln`,en:`Terminal state '${o.id}' has no terminal semantics in bus '${i.key}' \u2014 the engine throws when sealing`},severity:"error"}),!o.terminal&&a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`State '${o.id}' ist nicht terminal, hat aber Terminal-Semantik im Bus '${i.key}' \u2014 Inkonsistenz`,en:`State '${o.id}' is not terminal but has terminal semantics in bus '${i.key}' \u2014 inconsistent`},severity:"error"})}return r}s(kH,"checkProgressTerminalSemantics");function bH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Tl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat.${a}`,reason:{de:`holdsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`holdsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let a of i.commitsSeat??[])Tl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat '${a}' ist nicht in holdsSeat \u2014 ein fest belegter Platz muss auch belegt sein`,en:`commitsSeat '${a}' is not in holdsSeat \u2014 a firmly committed seat must also be held`},severity:"error"}):r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`commitsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let[a,l]of Object.entries(i.terminalSemantics??{}))l.outcome==="approved"&&(o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat`,reason:{de:`Endzustand '${a}' schlie\xDFt den Prozess positiv ab (outcome 'approved'), steht aber nicht in holdsSeat \u2014 damit z\xE4hlt er als Absage und f\xE4llt aus dem Fortschrittsbalken. Nimm '${a}' in holdsSeat (und in commitsSeat, wenn der Platz damit wirklich belegt ist) auf.`,en:`Final state '${a}' ends the process positively (outcome 'approved'), but is not in holdsSeat \u2014 so it counts as a rejection and drops out of the progress bar. Add '${a}' to holdsSeat (and to commitsSeat, if the seat is really taken by it).`},severity:"error"}))}return r}s(bH,"checkProgressSeatStates");var wp={de:"Abhilfe: nach dem Formularknoten einen review-Knoten einf\xFCgen und dessen 'reviewing' auf diesen Zustand mappen",en:"Remedy: insert a review node after the form node and map its 'reviewing' to this state"};function vH(e){return e==="both"?{de:`${wp.de} \u2014 die Spalte ist auch der Schritt, den die Familie sieht; den Zustand in die Spalte des Nachfolgers zu legen, n\xE4hme ihr diesen Schritt.`,en:`${wp.en} \u2014 the column is also the step the family sees; moving the state into the successor's column would take that step away from them.`}:{de:`${wp.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${wp.en}, or move the state into the successor's column.`}}s(vH,"passThroughRemedy");function xH(e,t){let n=ca(e,t);if(!n)return[];let{layout:r,wiring:i}=n;if(!r.buses.some(v=>v.key==="process"))return[];let o=VO(r);if(!o)return[];let a=new Map(e.nodes.map(v=>[v.id,v])),l=s(v=>Ye(v).progressEvents??[],"eventsOf"),d=s(v=>Object.values(v.next??{}).map(A=>A.to),"routesOf"),c=s((v,A)=>{let E=a.get(v);if(!E||A.has(v))return null;if(l(E).length>0)return[E];if(bC[E.type]!==!1)return null;let I=d(E);if(I.length===0)return null;let C=[];for(let $ of I){let b=c($,new Set([...A,v]));if(!b)return null;C.push(...b)}return C},"firstProgressNodes"),u=s((v,A)=>{let E=[];for(let I of l(v)){let C=Bs(i,v,I);if(!C||C.bus!==A.bus||C.state===A.state)return null;E.push(C.state)}return[...new Set(E)].join("' / '")},"overwrites"),p=s((v,A)=>{let E=d(v);if(E.length===0)return null;let I=[];for(let C of E){let $=c(C,new Set([v.id]));if(!$)return null;for(let b of $){let R=u(b,A);if(R===null)return null;I.push({de:`'${b.id}' (${b.type}) mit '${R}'`,en:`'${b.id}' (${b.type}) with '${R}'`})}}return[...new Map(I.map(C=>[C.de,C])).values()]},"submitOverwrittenBy"),h=new Map;for(let v of e.nodes)for(let A of l(v)){let E=Bs(i,v,A);if(!E||E.bus!=="process")continue;let I=v.type==="form"&&A===ef?p(v,E):null,C=I?{de:`'${v.id}'.${A} erreicht ihn, und ${I.map($=>$.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${v.id}'.${A} reaches it, and ${I.map($=>$.en).join(", ")} overwrites it in the same transaction`}:null;h.set(E.state,[...h.get(E.state)??[],C])}let w=_f(r,"process"),k=new Map;for(let[v,A]of h){if(!A.every(I=>I!==null))continue;let E=[...new Map(A.map(I=>[I.de,I])).values()];k.set(v,{de:E.map(I=>I.de).join("; "),en:E.map(I=>I.en).join("; ")})}let y=[];for(let v of o.columns){if(v.states.length===0||!v.states.every(I=>k.has(I)))continue;let A=v.states.map(I=>{let C=w.holdsSeat?.includes(I)===!0,$=k.get(I);return{de:`Zustand '${I}'${C?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${$.de}`,en:`State '${I}'${C?" (is in holdsSeat, but never takes a seat)":""}: ${$.en}`}}),E=vH(o.audience);y.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${v.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${v.label.de}" ('${v.id}', Board '${o.id}') bleibt immer leer \u2014 ${A.map(I=>I.de).join("; ")}. ${E.de}`,en:`[progress/passThroughState] Column "${v.label.en}" ('${v.id}', board '${o.id}') always stays empty \u2014 ${A.map(I=>I.en).join("; ")}. ${E.en}`},severity:"warning"})}return y}s(xH,"checkProgressPassThroughColumns");function SH(e){let t=["workItems","workitems","work_items","taskTemplates"],n=[];for(let r of e.nodes){let i=r;for(let o of t){let a=i[o];a!=null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.${o}`,reason:{de:`[workItems/misnamedTasksKey] Knoten "${r.id}" deklariert "${o}" \u2014 komponierte Aufgaben werden ausschlie\xDFlich unter "tasks" gelesen. So wie es dasteht, w\xFCrde die Aufgabenkette stillschweigend nie entstehen. Benenne den Schl\xFCssel in "tasks" um.`,en:`[workItems/misnamedTasksKey] Node "${r.id}" declares "${o}" \u2014 composed tasks are read only from "tasks". As it stands, the task chain would silently never be created. Rename the key to "tasks".`},severity:"error"})}}return n}s(SH,"checkMisnamedTasksKey");function AH(e){let t=[];for(let n of e.nodes){let r=n,i=Array.isArray(r.tasks)?r.tasks:[],o=new Set;for(let c of i){let u=typeof c.key=="string"?c.key:void 0;u!==void 0&&(o.has(u)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}`,reason:{de:`[workItems/duplicateTemplateKey] Doppelter Template-Key "${u}" auf Knoten "${r.id}".`,en:`[workItems/duplicateTemplateKey] Duplicate template key "${u}" on node "${r.id}".`},severity:"error"}),o.add(u))}let a=new Set;for(let c of Array.isArray(r.artifacts)?r.artifacts:[])typeof c.key=="string"&&a.add(`${c.key}Uploaded`);let l=Ye(n),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(n):[]).map(c=>[c.key,c]));for(let c of i){let u=typeof c.key=="string"?c.key:"?",p=typeof c.kind=="string"?c.kind:void 0;if(p===void 0||!Cl.has(p)){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.kind`,reason:{de:`[workItems/invalidKind] Task "${u}" auf Knoten "${r.id}" hat Art ${JSON.stringify(c.kind)}; komponierbar sind: ${[...Cl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Cl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.gatesNode`,reason:{de:`[workItems/gatesNodeOnTask] 'gatesNode' ist nur f\xFCr die Art 'approval' zul\xE4ssig \u2014 eine Task gated ihren Knoten nie direkt. Um eine gatende Freigabe zur\xFCckzuhalten, 'blocks' verwenden (Task "${u}" auf Knoten "${r.id}").`,en:`[workItems/gatesNodeOnTask] 'gatesNode' is only allowed for the kind 'approval' \u2014 a task never gates its node directly. To hold back a gating approval, use 'blocks' (task "${u}" on node "${r.id}").`},severity:"error"});let h=c.blocks,w=h===void 0?void 0:LN(e,r.id,h.node);if(h!==void 0&&w===null)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.node`,reason:{de:`[workItems/blocksUnknownNode] 'blocks.node' auf Task "${u}" (Knoten "${r.id}") nennt ${JSON.stringify(h.node)} \u2014 diesen Knoten gibt es im Workflow nicht.`,en:`[workItems/blocksUnknownNode] 'blocks.node' on task "${u}" (node "${r.id}") names ${JSON.stringify(h.node)} \u2014 there is no such node in the workflow.`},severity:"error"});else if(h!==void 0&&w!==void 0&&w!==null){let y=w.node.id===r.id,v=w.node.id,A=y?o:w.composedKeys,E=y?d:w.intrinsicByKey,I=w.node.assign??{};p==="approval"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksOnApproval] 'blocks' ist auf der Art 'approval' verboten \u2014 nur Task-Zeilen d\xFCrfen einen Geschwister-Spawn zur\xFCckhalten (Approval "${u}" auf Knoten "${r.id}").`,en:`[workItems/blocksOnApproval] 'blocks' is forbidden on the kind 'approval' \u2014 only task rows may hold back a sibling spawn (approval "${u}" on node "${r.id}").`},severity:"error"});let C=h.templateKey,$=[...new Set([...A,...E.keys()])].filter(R=>!y||R!==u).join(", "),b={de:$||"keine",en:$||"none"};if(typeof C!="string"||y&&C===u||!A.has(C)&&!E.has(C))t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnknownTarget] 'blocks' muss ein Template auf dem Zielknoten benennen \u2014 komponiert ODER intrinsisch (nie sich selbst, nie ohne 'templateKey': die zielfreie Form geh\xF6rt der Maschine, nicht dem Autor). Ziel ${JSON.stringify(C)} auf Knoten "${v}"; zul\xE4ssige Ziele: ${b.de}.`,en:`[workItems/blocksUnknownTarget] 'blocks' must name a template on the target node \u2014 composed OR intrinsic (never itself, never without 'templateKey': the target-less form belongs to the engine, not the author). Target ${JSON.stringify(C)} on node "${v}"; allowed targets: ${b.en}.`},severity:"error"});else if(w.refuse(C)!==null)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:w.refuse(C),severity:"error"});else{let R=E.get(C);h.except!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.except`,reason:{de:`[workItems/blocksExceptRetired] 'blocks.except' auf Task "${u}" (Knoten "${r.id}") gibt es nicht mehr: eine blockierende Aufgabe sperrt die ganze Aktionsgruppe ihres Ziels (bei einer Entscheidung Freigeben, Warteliste, Ablehnen und das Nachr\xFCcken). 'except' entfernen.`,en:`[workItems/blocksExceptRetired] 'blocks.except' on task "${u}" (node "${r.id}") no longer exists: a blocking task locks the whole action group of its target (for a decision: approve, waitlist, reject and promote). Remove 'except'.`},severity:"error"}),R!==void 0&&R.recipient!=="external"&&R.verdictResolved!==!0&&typeof I[C]!="string"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnwiredTarget] Task "${u}" auf Knoten "${r.id}" h\xE4lt "${C}" (Knoten "${v}") zur\xFCck, aber der Knoten weist "${C}" keiner Gruppe zu \u2014 ohne 'assign.${C}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${C}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${C}" (node "${v}"), but the node assigns "${C}" to no group \u2014 without 'assign.${C}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${C}' or remove the 'blocks'.`},severity:"error"})}}{let y=c.completableIf;if(typeof y=="string"&&y.trim().length>0){let v=y.trim().replace(/^!/,"").trim();a.has(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${y}" verweist auf unbekannten Node-Export "${v}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${y}" refers to unknown node export "${v}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.commentRequired`,reason:{de:"[workItems/removedParam] 'params.commentRequired' wurde entfernt \u2014 Kommentar-Pflichten werden am Decision-Node ('commentRequired') autorisiert.",en:"[workItems/removedParam] 'params.commentRequired' was removed \u2014 comment requirements are authored on the decision node ('commentRequired')."},severity:"error"}),p!=="approval"){let y=[];k?.onReject!==void 0&&y.push("params.onReject"),k?.revisionGroup!==void 0&&y.push("params.revisionGroup");for(let v of y)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${v}`,reason:{de:`[workItems/approvalOnlyField] '${v}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${v}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.onReject`,reason:{de:`[workItems/invalidOnReject] Erwartet 'spawnRevision', erhalten ${JSON.stringify(k.onReject)}.`,en:`[workItems/invalidOnReject] Expected 'spawnRevision', got ${JSON.stringify(k.onReject)}.`},severity:"error"}),k?.onReject==="spawnRevision"&&(typeof k.revisionGroup!="string"||k.revisionGroup.length===0)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.revisionGroup`,reason:{de:`[workItems/spawnRevisionNoTarget] Approval "${u}" mit 'params.onReject: spawnRevision' ohne 'params.revisionGroup' \u2014 die \xDCberarbeitung h\xE4tte keine Ziel-Gruppe.`,en:`[workItems/spawnRevisionNoTarget] Approval "${u}" with 'params.onReject: spawnRevision' but no 'params.revisionGroup' \u2014 the revision would have no target group.`},severity:"error"})}}return t.push(...MN(e)),t}s(AH,"checkWorkItemTemplates");var EH=new Set(["complete","approve","reject"]),bC={form:!0,decision:!0,review:!0,waitlist:!0,completenessCheck:!0,collectPayment:!0,eventTrigger:!0,join:!1,roleAssign:!1,setFlag:!1,if:!1,end:!1,countersign:!0,engagePush:!1,governedDocument:!0};function TH(e){let t=[];for(let n of e.nodes){let r=n,i=Ye(n),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(n)??[];if(o+a.length>0){let v=bC[r.type];v===void 0?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/unknownParkSemantics] Knotentyp "${r.type}" hat keine bekannte Park-Semantik \u2014 NODE_TYPE_PARKS in validators.ts erg\xE4nzen.`,en:`[workItems/unknownParkSemantics] Node type "${r.type}" has no known parking semantics \u2014 add it to NODE_TYPE_PARKS in validators.ts.`},severity:"error"}):v||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/templatesOnNonParkingNode] Knoten "${r.id}" (Typ "${r.type}") parkt nie \u2014 seine Work-Item-Templates w\xFCrden im selben Dispatch gespawnt und storniert (totes Muster).`,en:`[workItems/templatesOnNonParkingNode] Node "${r.id}" (type "${r.type}") never parks \u2014 its work-item templates would be spawned and cancelled in the same dispatch (dead pattern).`},severity:"error"})}let l=i.actions?.(n)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(v=>[v.id,v]));for(let v of l)EH.has(v.id)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${v.id}" \u2014 reserviert f\xFCr den generischen Complete-/Verdict-Pfad (complete, approve, reject); die Spec muss eine andere Action-Id w\xE4hlen.`,en:`[capability/reservedActionId] Node type "${r.type}" declares the action "${v.id}" \u2014 reserved for the generic complete/verdict path (complete, approve, reject); the spec must choose a different action id.`},severity:"error"});let c=new Set(i.states??[i_]);for(let v of l)if(v.availableIn!==void 0)for(let A of v.availableIn)c.has(A)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${v.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${A}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${v.id}" on node type "${r.type}" is declared for state "${A}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=zy(n),p=new Set(u?u.map(v=>v.id):[Ys]);for(let v of l){if(v.external===void 0)continue;let A=r_(v.external.event),E={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},I=A?v.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${v.external.event}") \u2014 such actions are "internal"`}:v.outcome!==void 0?{de:`nennt das Outcome "${v.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${v.outcome}", but does not resolve the node (event "${v.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:v.label===void 0?E:null:v.kind!=="advance"?{de:`ist als "${v.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${v.kind}" (external actions resolve the node and must be "advance")`}:v.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(v.outcome)?v.label===void 0?E:null:{de:`verweist auf das unbekannte Outcome "${v.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${v.outcome}" (declared: ${[...p].join(", ")||"none"})`};I!==null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${v.id}" auf Knotentyp "${r.type}" ${I.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${v.id}" on node type "${r.type}" ${I.en}.`},severity:"error"})}for(let v of a){let A=v.unlocks;if(A.length===0&&v.verdictResolved!==!0&&v.informational!==!0){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${v.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${v.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let E of A)d.get(E)===void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${v.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${E}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${v.key}" on node "${r.id}" unlocks the unknown action "${E}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(v=>v.key));for(let v of Object.keys(r.assign??{}))h.has(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${v}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${v}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${v}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});let w=l.filter(v=>v.teamAssignable===!0).map(v=>v.id);for(let v of Object.keys(r.actionTeams??{}))w.includes(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${v}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${v}", aber diese Aktion l\xE4sst sich hier keinem Team geben; m\xF6glich: ${w.join(", ")||"keine"}.`,en:`[capability/unknownActionTeam] Node "${r.id}" names a team for "${v}", but this action cannot be given to a team here; possible: ${w.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let v of a)if(v.recipient==="external"||typeof(r.assign??{})[v.key]=="string")for(let E of v.unlocks)k.add(E);let y=i.strictActionCoverage===!0;for(let v of l){if(k.has(v.id)||v.superUserOnly===!0)continue;let A=a.find(I=>I.unlocks.includes(v.id)),E=A!==void 0?{de:` Fehlt die Zuweisung assign.${A.key}?`,en:` Is the assignment assign.${A.key} missing?`}:{de:"",en:""};t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/superUserOnly] Action "${v.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${E.de}`,en:`[capability/superUserOnly] Action "${v.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${E.en}`},severity:y?"error":"warning"})}}return t}s(TH,"checkNodeCapabilityWiring");function $H(e){let t=new Set(zI()),n=[];for(let r of e.nodes)t.has(r.type)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.type`,reason:{de:`[graph/unknownNodeType] Knoten "${r.id}" hat den unbekannten Typ "${String(r.type)}". Registrierte Typen: ${[...t].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...t].join(", ")}.`},severity:"error"});return n}s($H,"checkKnownNodeTypes");function RH(e,t){let n=[],r=s((a,l)=>{n.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=tI(e),o=s(a=>typeof a=="object"&&a!==null&&Object.values(a).some(l=>typeof l=="string"&&l.trim().length>0),"hasText");for(let a of e.nodes){let l=a,d=Array.isArray(l.optionalActions)?l.optionalActions:[];if(n.push(...VH(l,d)),d.length===0)continue;let c=Ye(a),u=new Set(c.optionalActionKinds??[]),p=Array.isArray(l.tasks)?l.tasks:[],h=new Map;for(let y of p)typeof y.key=="string"&&h.set(y.key,y);let w=new Set,k=new Map;for(let y of d){let v=y.key,A=typeof v=="string"&&v.trim().length>0?v:void 0,E=A??"?",I=`nodes.${l.id}.optionalActions.${E}`,C=typeof y.action=="string"?y.action:void 0;if(y.when!==void 0){let $=s(b=>r(`${I}.when`,{de:`[optionalAction/when] Optionale Aktion "${E}" auf Knoten "${l.id}": ${b.de}`,en:`[optionalAction/when] Optional action "${E}" on node "${l.id}": ${b.en}`}),"conditionFinding");if(typeof y.when!="string"||y.when.trim()==="")$({de:"Die Bedingung ist leer \u2014 ohne Bedingung das Feld weglassen.",en:"The condition is empty \u2014 without a condition, omit the field."});else for(let b of Xf(y.when,i,t))$(b)}if((C===void 0||!u.has(C))&&r(`${I}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${E}" auf Knoten "${l.id}" hat die Art ${JSON.stringify(y.action)} \u2014 `+(u.size===0?`Knotentyp "${l.type}" deklariert keine Familien (spec.optionalActionKinds fehlt).`:`Knotentyp "${l.type}" deklariert nur: ${[...u].join(", ")}.`),en:`[optionalAction/kindNotDeclared] Optional action "${E}" on node "${l.id}" has the kind ${JSON.stringify(y.action)} \u2014 `+(u.size===0?`node type "${l.type}" declares no families (spec.optionalActionKinds is missing).`:`node type "${l.type}" only declares: ${[...u].join(", ")}.`)}),A===void 0?r(`${I}.key`,{de:`[optionalAction/missingKey] Optionale Aktion auf Knoten "${l.id}" ohne (oder mit leerem) 'key' \u2014 Trigger-Action und Template-Keys w\xE4ren namenlos ('optionalAction::\u2026').`,en:`[optionalAction/missingKey] Optional action on node "${l.id}" without (or with an empty) 'key' \u2014 the trigger action and template keys would be nameless ('optionalAction::\u2026').`}):(w.has(A)&&r(`${I}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${A}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${A}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),w.add(A)),o(y.label)||r(`${I}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${E}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${E}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),C==="spawnTasks"){y.except!==void 0&&r(`${I}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${E}" auf Knoten "${l.id}" tr\xE4gt 'except' \u2014 das gibt es nicht mehr: solange die Aufgaben offen sind, ist die ganze Aktionsgruppe des Knotens gesperrt. 'except' entfernen.`,en:`[optionalAction/exceptRetired] Optional action "${E}" on node "${l.id}" carries 'except' \u2014 that no longer exists: while the tasks are open, the node's whole action group is locked. Remove 'except'.`});let $=Array.isArray(y.tasks)?y.tasks:void 0;if($===void 0||$.length===0)r(`${I}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${E}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let b=new Set,R=new Set($.filter(q=>typeof q=="string"));for(let q of $){let _=typeof q=="string"?q:void 0;if(_===void 0||_.length===0){r(`${I}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(b.has(_)){r(`${I}.tasks.${_}`,{de:`[optionalAction/duplicateTaskRef] Template "${_}" ist in der Aktion "${E}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${_}" is referenced twice in the action "${E}" on node "${l.id}".`});continue}b.add(_);let J=h.get(_);if(J===void 0){r(`${I}.tasks.${_}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert das Template "${_}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" references the template "${_}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let Y=k.get(_);Y!==void 0&&Y!==E?r(`${I}.tasks.${_}`,{de:`[optionalAction/taskDoublyBound] Template "${_}" auf Knoten "${l.id}" ist bereits von der Aktion "${Y}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${_}" on node "${l.id}" is already referenced by the action "${Y}" \u2014 a template belongs to at most one optional action.`}):k.set(_,E);let ue=J.blocks?.templateKey;typeof ue=="string"&&!R.has(ue)&&r(`${I}.tasks.${_}`,{de:`[optionalAction/taskRefBlocks] Template "${_}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${ue}", das nicht zur selben Aktion "${E}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${_}" on node "${l.id}" carries 'blocks' on "${ue}", which does not belong to the same action "${E}" \u2014 a reference may only hold back a reference of the SAME action (checklist order), never a template outside it.`});for(let Q of p){let re=typeof Q.key=="string"?Q.key:void 0;Q.blocks?.templateKey===_&&(re!==void 0&&R.has(re)||r(`${I}.tasks.${_}`,{de:`[optionalAction/taskRefBlocks] Template "${_}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${E}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${_}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${E}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return n}s(RH,"checkOptionalActions");function IH(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(IH,"literalValueType");function OH(e,t){let n=[],r=t?.notificationTemplates;for(let i of e.nodes){let o=i,a=E_(i,Ye(i)),l=o.notifications??{};if(a.length===0&&Object.keys(l).length===0)continue;let d=new Map(a.map(c=>[c.id,c]));for(let c of Object.keys(l))d.has(c)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c}`,reason:{de:`[notification/unknownEvent] Knoten "${o.id}" bindet einen Brief an das Ereignis "${c}", das der Knotentyp "${o.type}" nicht kennt. Angeboten werden: ${a.map(u=>u.id).join(", ")||"(keine)"}.`,en:`[notification/unknownEvent] Node "${o.id}" binds a letter to the event "${c}", which the node type "${o.type}" does not know. Offered: ${a.map(u=>u.id).join(", ")||"(none)"}.`},severity:"error"});for(let c of a){let u=l[c.id];if(c.required===!0&&(u===void 0||u.disabled===!0)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c.id}`,reason:{de:`[notification/missingBinding] Knoten "${o.id}" muss beim Ereignis "${c.label.de}" (${c.id}) einen Brief verschicken \u2014 es ist ${u===void 0?"keiner gebunden":"einer gebunden, aber abgeschaltet"}.`,en:`[notification/missingBinding] Node "${o.id}" must send a letter on the event "${c.label.en}" (${c.id}) \u2014 ${u===void 0?"none is bound":"one is bound, but switched off"}.`},severity:"error"});continue}if(u===void 0||u.disabled===!0)continue;let p=`nodes.${o.id}.notifications.${c.id}`;if(c.audience!=="external"){n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/internalAudienceUnsupported] Knoten "${o.id}": das Ereignis "${c.id}" richtet sich an die Schule, und Briefe an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 der gebundene Brief "${u.templateId}" w\xFCrde den Vorgang beim Versand abbrechen.`,en:`[notification/internalAudienceUnsupported] Node "${o.id}": the event "${c.id}" is addressed to the school, and letters to the school cannot be delivered yet \u2014 the bound letter "${u.templateId}" would abort the process when it is sent.`},severity:"error"});continue}if(r===void 0)continue;let h=r.get(u.templateId);if(h===void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": der Brief "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the letter "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/audienceMismatch] Der Brief "${h.id}" ist f\xFCr ${h.audience==="internal"?"die Schule":"die Familie"} geschrieben, das Ereignis "${c.id}" richtet sich aber an die Familie.`,en:`[notification/audienceMismatch] The letter "${h.id}" is written for ${h.audience==="internal"?"the school":"the family"}, but the event "${c.id}" is addressed to the family.`},severity:"warning"});let w=b_(c),k=new Set(h.params.map(y=>y.key));for(let y of Object.keys(u.args??{}))k.has(y)||n.push({layer:"GRAPH",kind:"nodeRule",path:`${p}.args.${y}`,reason:{de:`[notification/unknownArg] Der Brief "${h.id}" hat kein Argument "${y}" \u2014 erwartet werden: ${h.params.map(v=>v.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The letter "${h.id}" has no argument "${y}" \u2014 expected: ${h.params.map(v=>v.key).join(", ")||"(none)"}.`},severity:"error"});for(let y of h.params){let v=u.args?.[y.key],A=`${p}.args.${y.key}`;if(v!==void 0&&"literal"in v){let I=IH(v.literal);y.type!==void 0&&!sw(I,y.type)&&n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/argTypeMismatch] "${y.key}" erwartet ${_l(y.type).de}, festgelegt ist aber ${JSON.stringify(v.literal)} (${I}).`,en:`[notification/argTypeMismatch] "${y.key}" expects ${_l(y.type).en}, but ${JSON.stringify(v.literal)} (${I}) is set.`},severity:"error"});continue}if(v!==void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unsupportedArg] "${y.key}" ist an ${JSON.stringify(v)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${kC(w,"de")} kommen.`,en:`[notification/unsupportedArg] "${y.key}" is bound to ${JSON.stringify(v)} \u2014 a letter argument can only be a fixed value ({ literal }) or come automatically from ${kC(w,"en")}.`},severity:"error"});continue}let E=v_(y,w.get(y.key)??[]);if(!(E.status==="resolved"||E.status==="unused")){if(E.status==="sometimes"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}" immer, ${E.source.source} liefert es aber nur manchmal. In notifications.${c.id}.args.${y.key} einen Festwert benennen \u2014 oder einen Brief w\xE4hlen, der ohne "${y.key}" auskommt.`,en:`[notification/unresolvedArg] The letter "${h.id}" always needs "${y.key}", but ${E.source.source} provides it only sometimes. Name a fixed value in notifications.${c.id}.args.${y.key} \u2014 or choose a letter that works without "${y.key}".`},severity:"error"});continue}if(E.status==="ambiguous"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/ambiguousArg] "${y.key}" hat mehrere passende Quellen \u2014 ${E.matches.map(I=>I.source).join(", ")}. In notifications.${c.id}.args.${y.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${y.key}" has several matching sources \u2014 ${E.matches.map(I=>I.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${y.key}.`},severity:"error"});continue}n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}"${y.type!==void 0?` (${_l(y.type).de})`:""}, und der Knoten hat daf\xFCr ${E.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${E.rejected.map(I=>`${I.source} (${I.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The letter "${h.id}" needs "${y.key}"${y.type!==void 0?` (${_l(y.type).en})`:""}, and the node has ${E.rejected.length===0?"no source for it":`only unsuitable sources for it: ${E.rejected.map(I=>`${I.source} (${I.type})`).join(", ")}`}.`},severity:"error"})}}}}return n}s(OH,"checkNotificationBindings");function _H(e){return nN(e).map(t=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:t,severity:"error"}))}s(_H,"checkAssignmentRules");function kC(e,t){let n=[...e.keys()].sort();return n.length===0?t==="de"?"(nichts)":"(nothing)":n.join(", ")}s(kC,"describeCandidates");function NH(e,t){return oN(e,t?.teamKeys).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(NH,"checkChannels");function CH(e){return rI(e).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(CH,"checkStaffInputs");function PH(e,t){let n=[];for(let r of e.nodes){let i=r.reads;if(i===void 0)continue;let o=`nodes.${r.id}.reads`,a={de:`Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id})`,en:`Node "${_e(e,r.id,"en")}" (${r.id})`},l=s(c=>{n.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!hN(r)){l({de:`[readiness/readsNotGated] ${a.de} (${r.type}) deklariert \`reads\`, aber die Bereitschaftspr\xFCfung h\xE4lt nur Entscheidungs-Knoten und Dokument-Knoten mit Produktion \u2014 hier w\xFCrde \`reads\` nichts bewirken.`,en:`[readiness/readsNotGated] ${a.en} (${r.type}) declares \`reads\`, but the readiness check only holds decision nodes and document nodes with production \u2014 here \`reads\` would have no effect.`});continue}if(!Array.isArray(i)){l({de:`[readiness/readsDuplicate] \`reads\` von ${a.de} muss eine Liste von Feldadressen sein, erhalten ${JSON.stringify(i)}.`,en:`[readiness/readsDuplicate] \`reads\` of ${a.en} must be a list of field addresses, got ${JSON.stringify(i)}.`});continue}let d=new Set;for(let c of i){if(!xe(c))continue;let u=pe(c);if(d.has(u)){l({de:`[readiness/readsDuplicate] ${a.de} liest ${je(e,c,"de")} mehrfach.`,en:`[readiness/readsDuplicate] ${a.en} reads ${je(e,c,"en")} more than once.`});continue}if(d.add(u),!ct(c)){l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 \`reads\` nennt nur Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 \`reads\` only names fields of a form ($node.<form>.admission.<field>).`});continue}let p=ni(t,c);p!=null&&Vs("nodeReads",js(p))==="repeated"&&l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Feld der Anmeldung und kann nicht gelesen werden.`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 a field in a repeated group is not a single field of the application and cannot be read.`})}}return n}s(PH,"checkReadinessReads");function DH(e,t){let n=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=oO(r),o=bf(r);if(i===null||o===null)continue;let a=t?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${Ot.flagKey}`,reason:{de:`[setFlag/unknownFlag] Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id}) setzt \u201E${o}\u201C, aber das Formular von \u201E${_e(e,i,"de")}\u201C hat kein externes Merkmal dieses Namens`+(l.length>0?` (vorhanden: ${l.join(", ")}).`:" \u2014 es deklariert gar keins."),en:`[setFlag/unknownFlag] Node "${_e(e,r.id,"en")}" (${r.id}) sets "${o}", but the form of "${_e(e,i,"en")}" has no external flag of that name`+(l.length>0?` (present: ${l.join(", ")}).`:" \u2014 it declares none at all.")},severity:"error"})}return n}s(DH,"checkSetFlagKeys");function FH(e,t){let n=t?.readinessFormFieldsByFormNode,r=t?.readinessPartyConditionKeysByFormNode;if(n===void 0||r===void 0)return[];let i=[];for(let o of e.nodes){if(o.type!=="governedDocument"||o.production!=="resolver")continue;let a=o.form;if(!xe(a)||!wr(a))continue;let l=n.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=kw(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(y=>ct(y)&&y.owner===a.owner),h=kw(l,[...p.map(y=>y.path),...wN(o).filter(y=>y.owner===a.owner).map(y=>y.fieldKey)]),w=[...c].filter(y=>!h.has(y)).sort();if(w.length===0)continue;let k={de:_e(e,a.owner,"de"),en:_e(e,a.owner,"en")};i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.reads`,reason:{de:`[readiness/readsMissesPartyCondition] Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id}) erzeugt ein Dokument, dessen Vertragsparteien von Angaben im Formular \u201E${k.de}\u201C abh\xE4ngen, die er weder liest noch bindet: ${w.join(", ")}. Eine Korrektur darauf h\xE4lt den Knoten nicht an und kann nach der Ausstellung eine Vertragspartei entfernen \u2014 die Felder (oder den berechneten Schl\xFCssel) aus \u201E${k.de}\u201C in \`reads\` erg\xE4nzen.`,en:`[readiness/readsMissesPartyCondition] Node "${_e(e,o.id,"en")}" (${o.id}) generates a document whose contract parties depend on answers in the form "${k.en}" that it neither reads nor binds: ${w.join(", ")}. A correction to them does not hold the node and can remove a contract party after issuing \u2014 add the fields (or the computed key) from "${k.en}" to \`reads\`.`},severity:"warning"})}return i}s(FH,"checkReadinessPartyConditions");function Nw(e){let t=Object.keys(e.inputs??{});if(t.length===0)return[];let n=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(n?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(zs(e).map(l=>l.id));return t.filter(l=>!a.has(l))}s(Nw,"undeclaredInputKeys");function LH(e,t){return e.nodes.flatMap(n=>[...qH(e,n,zs(n),t),...MH(e,n,t)])}s(LH,"checkUnknownResources");function MH(e,t,n){let r=[],i=new Set((Ye(t).workItemTemplates?.(t)??[]).map(a=>a.key)),o=new Set((t.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of Rf(t)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=qs[a.leaf],d=`nodes.${t.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,t.id,"en")}" (${t.id}), ${l.what.en} "${a.owner}"`,"where");if(a.missing){if(!l.required){r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/emptyReference] ${c("de")}: der Eintrag ist leer oder kein Schl\xFCssel \u2014 ${l.consequence.de}. Team w\xE4hlen oder den Eintrag entfernen.`,en:`[inputs/emptyReference] ${c("en")}: the entry is empty or no key \u2014 ${l.consequence.en}. Choose a team or remove the entry.`}});continue}r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[workItems/needsTeam] ${c("de")}: kein Team gew\xE4hlt \u2014 ${l.consequence.de}. Jede Aufgabe geh\xF6rt der Warteschlange eines Teams.`,en:`[workItems/needsTeam] ${c("en")}: no team chosen \u2014 ${l.consequence.en}. Every task belongs to a team's queue.`}});continue}if(a.key===null)continue;let u=n?.teamKeys;if(u===void 0||u.has(a.key))continue;let p=[...u].sort().join(", ")||"\u2014";r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/unknownResource] ${c("de")}: \u201E${a.key}\u201C ist kein Team dieses Mandanten \u2014 ${l.consequence.de}. Teams: ${p}.`,en:`[inputs/unknownResource] ${c("en")}: "${a.key}" is no team of this school \u2014 ${l.consequence.en}. Teams: ${p}.`}})}return r}s(MH,"referenceIssues");function qH(e,t,n,r){let i=[];for(let o of n){if(!vf(o.type))continue;let a=Fs[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=t.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=Fs[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) nennt im Eingang \u201E${o.label.de}\u201C ${c.de} \u201E${d.value}\u201C \u2014 diesen Schl\xFCssel kennt dieser Mandant nicht.`,en:`[inputs/unknownResource] Node "${_e(e,t.id,"en")}" (${t.id}) names the ${c.en.toLowerCase()} "${d.value}" in its input "${o.label.en}", which does not exist in this school.`},severity:"error"})}return i}s(qH,"unknownResourceIssues");function KH(e){let t=[];for(let n of e.nodes)for(let r of Nw(n))t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) hat einen Eingang \u201E${r}\u201C, den sein Typ nicht deklariert \u2014 ein Rest einer fr\xFCheren Einstellung (z. B. eines anderen Generators). Im Parameter-Bereich ist er nicht sichtbar; entfernen.`,en:`[inputs/undeclared] Node "${_e(e,n.id,"en")}" (${n.id}) has an input "${r}" its type does not declare \u2014 a leftover of an earlier setting (e.g. another generator). It is not visible among the parameters; remove it.`},severity:"error"});return t}s(KH,"checkUndeclaredInputs");function jH(e){let t=[];for(let n of e.nodes){let r=new Set;for(let i of zs(n)){if(!r.has(i.id)){r.add(i.id);continue}t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) hat den Eingang \u201E${i.id}\u201C zweimal \u2014 ein Parameter des Generators oder der Vorlage tr\xE4gt den Namen eines Eingangs des Knotentyps. Den Parameter umbenennen.`,en:`[inputs/duplicateSlot] Node "${_e(e,n.id,"en")}" (${n.id}) has the input "${i.id}" twice \u2014 a parameter of the generator or template carries the name of an input of the node type. Rename the parameter.`},severity:"error"})}}return t}s(jH,"checkDuplicateSlots");function vC(e,t,n){let r=[],i=$H(e);if(i.length>0)return i;r.push(...fH(e)),r.push(...cH(e)),r.push(...pH(e)),r.push(...uH(e)),r.push(...aH(e)),r.push(...lH(e)),r.push(...dH(e)),r.push(...hH(e)),r.push(...WO(e,t)),r.push(...gH(e,t)),r.push(...yH(e,t)),r.push(...wH(e,t)),r.push(...xN(e,t?.layout)),r.push(...kH(e,t)),r.push(...bH(e,t)),r.push(...xH(e,t)),r.push(...MO(e,n)),r.push(...QO(e)),r.push(...n_(e)),r.push(...HO(e)),r.push(...JO(e)),r.push(...KH(e)),r.push(...LH(e,n)),r.push(...jH(e)),r.push(...SH(e)),r.push(...AH(e)),r.push(...KN(e,n)),r.push(...GN(e)),r.push(...BN(e)),r.push(...zN(e,n)),r.push(...JN(e,n)),r.push(...TH(e)),r.push(...OH(e,n)),r.push(...RH(e,n)),r.push(..._H(e)),r.push(...PH(e,n)),r.push(...FH(e,n)),r.push(...DH(e,n)),r.push(...NH(e,n)),r.push(...CH(e)),r.push(...wC(e));for(let o of e.nodes){let a=Ye(o);a.validate&&r.push(...a.validate(o,e,n))}return r}s(vC,"checkGraph");function VH(e,t){let n=e.requiresOneOf;if(n===void 0)return[];let r=`nodes.${e.id}.requiresOneOf`,i=s(d=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:d,severity:"error"}),"issue");if(e.type!=="decision")return[i({de:`[decision/requiresOneOfNotDecision] Knoten "${e.id}" (Typ "${e.type}") tr\xE4gt 'requiresOneOf' \u2014 die Regel gilt nur an Entscheidungsknoten (decision).`,en:`[decision/requiresOneOfNotDecision] Node "${e.id}" (type "${e.type}") carries 'requiresOneOf' \u2014 the rule only applies to decision nodes (decision).`})];if(!Array.isArray(n)||n.length===0||n.some(d=>typeof d!="string"||d.length===0))return[i({de:`[decision/requiresOneOfEmpty] 'requiresOneOf' an Knoten "${e.id}" muss eine nicht-leere Liste von Aktions-Keys sein \u2014 sonst Feld weglassen.`,en:`[decision/requiresOneOfEmpty] 'requiresOneOf' on node "${e.id}" must be a non-empty list of action keys \u2014 otherwise omit the field.`})];let o=t.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of n){if(l.has(d)){a.push(i({de:`[decision/requiresOneOfDuplicate] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}" doppelt.`,en:`[decision/requiresOneOfDuplicate] 'requiresOneOf' on node "${e.id}" names "${d}" twice.`}));continue}l.add(d),o.includes(d)||a.push(i({de:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}", aber dieser Knoten hat keine optionale Aktion mit diesem Key \u2014 die Regel w\xE4re nie erf\xFCllbar. `+(o.length===0?"Der Knoten hat keine optionalen Aktionen.":`Optionale Aktionen dieses Knotens: ${o.join(", ")}.`),en:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' on node "${e.id}" names "${d}", but this node has no optional action with that key \u2014 the rule could never be met. `+(o.length===0?"The node has no optional actions.":`Optional actions of this node: ${o.join(", ")}.`)}))}return a}s(VH,"checkRequiresOneOf");function BH(e){return e.nodes.flatMap(t=>Nw(t).map(n=>({nodeId:t.id,key:n,binding:t.inputs?.[n]?.kind==="binding"})))}s(BH,"undeclaredInputCells");function xC(e,t){let n=BH(e).filter(o=>t.bindings||!o.binding);if(n.length===0)return{graph:e,dropped:n};let r=new Map;for(let o of n)r.set(o.nodeId,(r.get(o.nodeId)??new Set).add(o.key));let i=e.nodes.map(o=>{let a=r.get(String(o.id));if(a===void 0)return o;let l=Object.fromEntries(Object.entries(o.inputs).filter(([d])=>!a.has(d)));return{...o,inputs:l}});return{graph:{...e,nodes:i},dropped:n}}s(xC,"dropUndeclaredInputs");function Cw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Cw,"isObject");function SC(e){return Cw(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(SC,"oldShape");function AC(e){return(e?.nodes??[]).some(SC)}s(AC,"needsTemplateStampMove");function UH(e){let t=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(t)?t:null;let n=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(n)?n:null}s(UH,"stampedFields");function GH(e){let t=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:t,reason:"templateAndStamp"}};let n={...e},r=[];if("template"in e){let{template:i}=e;if(delete n.template,Cw(i))n.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:t,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete n.cockpitFields;let o=Cw(e.inputs)?{...e.inputs}:{},a=UH(n);if(a===null&&i.length>0)return{unmoved:{nodeId:t,key:i[0],reason:"noStamp"}};for(let l of i){let d=l in o&&o[l]?.kind!=="unset",c=(a??[]).find(u=>u.key===l);if(c===void 0)r.push({nodeId:t,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:t,key:l,reason:"processSource"}):d?r.push({nodeId:t,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}n.inputs=o}return{node:n,reports:r}}s(GH,"moveNode");function EC(e){let t=[],n=[],r=[],i=e.nodes.map(o=>{if(!SC(o))return o;let a=GH(o);return"unmoved"in a?(r.push(a.unmoved),o):(t.push(String(o.id)),n.push(...a.reports),a.node)});return t.length===0?{graph:e,moved:t,reports:n,unmoved:r}:{graph:{...e,nodes:i},moved:t,reports:n,unmoved:r}}s(EC,"moveTemplateStampAndCockpit");var TC=tf,zH="applicant.applicationSubmitted";function kp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(kp,"isObject");function $C(e){return kp(e)&&e.type==="form"&&typeof e.id=="string"&&!kn(e)}s($C,"isCreatingFormNode");function WH(e){return kp(e.notifications)&&TC in e.notifications}s(WH,"hasSubmittedBinding");function Pw(e){let t={toBind:[],alreadyBound:[],malformed:[]};for(let n of e?.nodes??[])$C(n)&&(n.notifications!==void 0&&!kp(n.notifications)?t.malformed.push(n.id):WH(n)?t.alreadyBound.push(n.id):t.toBind.push(n.id));return t}s(Pw,"submitReceiptInventory");function RC(e){let{toBind:t}=Pw(e);if(t.length===0)return{graph:e,bound:[]};let n=new Set(t),r=e.nodes.map(i=>{if(!$C(i)||!n.has(i.id))return i;let o=kp(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[TC]:{templateId:zH}}}});return{graph:{...e,nodes:r},bound:t}}s(RC,"bindSubmitReceipt");var Mo=["park","advance"],tr="whenNothingOwed",IC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function OC(e){let t=e.inputs?.[tr],n=t?.kind==="literal"?t.value:void 0;return Dw(n)?n:null}s(OC,"reviewModeOrNull");function Dw(e){return Mo.includes(e)}s(Dw,"isReviewMode");function Fw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Fw,"isObject");function _C(e){return Fw(e)&&e.type==="review"&&!(Fw(e.inputs)&&tr in e.inputs)}s(_C,"lacksMode");function NC(e){return(e?.nodes??[]).some(_C)}s(NC,"needsReviewMode");function CC(e){let t=[],n=e.nodes.map(r=>{if(!_C(r))return r;t.push(r.id);let i=Fw(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[tr]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:n},set:t}}s(CC,"setReviewModePark");function bp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(bp,"isObject");function PC(e){let{notifications:t,bound:n}=Vf(e.notifications,{tasks:[]},e);return{next:t,bound:n}}s(PC,"bindingsFor");function DC(e){let t={toBind:[],malformed:[]};for(let n of e?.nodes??[])if(!(!bp(n)||typeof n.id!="string"||Js(n).length===0)){if(n.notifications!==void 0&&!bp(n.notifications)){t.malformed.push(n.id);continue}for(let r of PC(n).bound)t.toBind.push(`${n.id}.${r}`)}return t}s(DC,"appointmentLetterInventory");function FC(e){let t=[],n=!1,r=e.nodes.map(i=>{if(!bp(i)||typeof i.id!="string"||Js(i).length===0||i.notifications!==void 0&&!bp(i.notifications))return i;let{next:o,bound:a}=PC(i);return a.length===0?i:(n=!0,t.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return n?{graph:{...e,nodes:r},bound:t}:{graph:e,bound:[]}}s(FC,"bindAppointmentLetters");function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ua,"isObject");var LC=["id","label","dataFlow"],MC=["audience","populates","stages","expectedOutcomes"];function qC(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(t=>ua(t)&&typeof t.slot=="string")}s(qC,"carriesStringSlots");function KC(e){return(e.nodes??[]).some(t=>ua(t)&&t.type==="form"&&MC.some(n=>n in t))}s(KC,"carriesRetiredFormNodeKey");var YH=[{key:"generatorPin",editor:!0,holds:RI,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:cO,what:{de:"Formular und Merkmal eines \u201EFlag setzen\u201C-Knotens als Eigenschaften",en:'form and flag of a "Set flag" node as properties'}},{key:"scalarProperties",editor:!0,holds:gO,what:{de:"Einstellungen eines Knotens als Eigenschaften statt als Eing\xE4nge",en:"a node's settings as properties instead of inputs"}},{key:"nodeConfigProperties",editor:!0,holds:AO,what:{de:"Hinweis einer Zahlung als Eigenschaft oder ein entferntes Muster-Dokument",en:"a payment's note as a property, or a removed sample document"}},{key:"outcomeWithoutSemantic",editor:!0,holds:wI,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:xI,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:AC,what:{de:"Parameter einer Vorlage am Knoten oder Cockpit-Felder als Liste",en:"a template's parameters on the node, or cockpit fields as a list"}},{key:"reviewWithoutMode",editor:!0,holds:NC,what:{de:"Pr\xFCfknoten ohne \u201EWenn nichts zu pr\xFCfen ist\u201C",en:'review nodes without "When nothing is owed"'}},{key:"taskAssignUser",editor:!1,holds:s(e=>$f(e).length>0,"holds"),what:{de:"eine Aufgabe mit fester Person (`assign.userId`)",en:"a task with a fixed person (`assign.userId`)"}},{key:"retiredGraphKey",editor:!1,holds:s(e=>LC.some(t=>t in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:qC,what:{de:"Zust\xE4ndigkeitsregeln mit Slot als Text (`responsible` / `team:<Schl\xFCssel>`)",en:"assignment rules with a slot as text (`responsible` / `team:<key>`)"}},{key:"retiredFormNodeKey",editor:!1,holds:KC,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function jC(e){if(!ua(e)||!Array.isArray(e.nodes))return[];let t=e;return YH.filter(n=>n.holds(t)).map(({key:n,what:r,editor:i})=>({key:n,what:r,editor:i}))}s(jC,"legacyGraphShapes");function VC(e,t){let n=t.answers??{},r=[],i=[],o=e,a=LC.filter($=>$ in o);if(a.length>0){let $={...o};for(let b of a)delete $[b],r.push({message:`graph.${b}: deleted (read by nothing)`});o=$}if(KC(o)&&(o={...o,nodes:o.nodes.map($=>{if(!ua($)||$.type!=="form")return $;let b=MC.filter(q=>q in $);if(b.length===0)return $;let R={...$};for(let q of b)delete R[q];return r.push({nodeId:String($.id),message:`form node: deleted ${b.map(q=>`\`${q}\``).join(", ")} (read by nothing)`}),R})}),qC(o)){let $=o.assignmentRules.map((b,R)=>{if(!ua(b)||typeof b.slot!="string")return b;let q=mf(b.slot);return q===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${R}].slot "${b.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),b):(r.push({message:`assignmentRules[${R}].slot "${b.slot}" \u2192 ${JSON.stringify(q)}`}),{...b,slot:q})});o={...o,assignmentRules:$}}let l=II(o);o=l.graph;for(let $ of l.moved)r.push({nodeId:$,message:"generator / template pin moved into its input"});for(let $ of l.unmoved)i.push({code:`generatorPin/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${$.reason}) \u2014 edit the node by hand`});let d=uO(o);o=d.graph;for(let $ of d.moved)r.push({nodeId:$,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let $ of d.unmoved)i.push({code:`setFlag/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${$.reason}) \u2014 edit the node by hand`});let c=yO(o);o=c.graph;for(let $ of c.moved)r.push({nodeId:$,message:"scalar settings moved into inputs"});for(let $ of c.unmoved)i.push({code:`scalar/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let u=EO(o);o=u.graph;for(let $ of u.moved)r.push({nodeId:$,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let $ of u.unmoved)i.push({code:`nodeConfig/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let p=EC(o);o=p.graph;for(let $ of p.moved){let b=o.nodes.find(_=>ua(_)&&_.id===$),R=b?.inputs?.documentTemplate,q=R?.kind==="literal"&&typeof R.value=="string"?R.value:null;r.push({nodeId:$,message:b!==void 0&&"templateStamp"in b&&q!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${q}\` must declare the same parameters (tenant catalog \`documentTemplates[].parameters\` / \`templates:setParameters\`) before publish, else [governedDocument/templateWithoutParameters]`:"cockpit list moved into `{ kind: 'cockpit' }` cells"})}for(let $ of p.reports)r.push({nodeId:$.nodeId,message:`cockpit field \`${$.key??""}\` deleted (${$.reason}: ${$.reason==="unknownKey"?"the stamp declares no such parameter":$.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let $ of p.unmoved)i.push({code:`templateStamp/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="noStamp"?"the cockpit list cannot be judged: the node carries no parameter stamp \u2014 run `offer workflow restamp-pins` against the environment, then upgrade again":$.reason==="templateAndStamp"?"the node carries both `template` and `templateStamp` \u2014 delete one by hand":"`template` is no object \u2014 edit the node by hand"});let h=SI(o);o=h.graph;for(let $ of h.moved)r.push({nodeId:$,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let $ of h.unmoved)i.push({code:`eventTrigger/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${$.reason}) \u2014 edit the node by hand`});let w=kI(o,n.semantics);o=w.graph;for(let $ of w.written){if($.source==="formerDefault"){r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,value:$.semantic}});continue}r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (${$.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let $ of w.refused)i.push({code:$.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:$.nodeId,answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,candidates:$.allowed,message:$.answer===void 0?`${$.nodeType} outcome \`${$.outcomeId}\` ran as "${py($.outcomeId)??""}", which a ${$.nodeType} outcome may no longer carry \u2014 say which one it is`:`${$.nodeType} outcome \`${$.outcomeId}\`: "${$.answer}" is not a meaning a ${$.nodeType} outcome may carry`});for(let $ of w.invalid)i.push({code:"outcome/semanticInvalid",nodeId:$.nodeId,answer:"edit",candidates:wn,message:`outcome \`${$.outcomeId}\` carries the semantic "${$.value}", which is no meaning \u2014 edit it`});let k=TI(o,t.selection,n.waitlistPolicy);o=k.graph;for(let $ of k.moved){let b=$.policy.waitlistOrder;r.push({nodeId:$.nodeId,message:`waitlist policy into inputs: ${HH($.policy)} (${$.source==="answer"?"answered":$.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...$.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:$.nodeId,value:b}}:{}})}for(let $ of k.refused)i.push({code:`waitlist/${$.reason}`,nodeId:$.nodeId,answer:"waitlistPolicy",answerKey:$.nodeId,candidates:Hn,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});if($O(o)){let $=RO(o,n.payee);o=$.graph;for(let b of $.set)r.push({nodeId:b.nodeId,message:`online payment: payee "${b.payee}" (answered)`});for(let b of $.refused)i.push({code:"collectPayment/payeeMissing",nodeId:b,answer:"payee",answerKey:b,message:"an online payment names the Tr\xE4ger its money goes to \u2014 say its key (a `legal_entities.configKey` of the tenant)"})}for(let $ of Pw(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:$,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let y=RC(o);o=y.graph;for(let $ of y.bound)r.push({nodeId:$,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let v=CC(o);o=v.graph;for(let $ of v.set)r.push({nodeId:$,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let $ of DC(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:$,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let A=FC(o);o=A.graph;for(let $ of A.bound){let b=$.indexOf(".");r.push({nodeId:$.slice(0,b),message:`appointment letter bound to \`notifications.${$.slice(b+1)}\` (the standard letter, sent by code before)`})}let E=$f(o).filter($=>!$.hasTeam);for(let $ of E)i.push({code:"task/userWithoutTeam",nodeId:$.nodeId,answer:"edit",message:`task \`${$.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let I=IO(o);o=I.graph;for(let $ of I.dropped.filter(b=>b.hasTeam))r.push({nodeId:$.nodeId,message:`task \`${$.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let C=xC(o,{bindings:!0});o=C.graph;for(let $ of C.dropped){if(!$.binding){r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (DEFAULT \u2014 a binding no slot declares: no slot handed its value to the node, but the readiness gate waited for it; the node no longer waits for that value)`,defaulted:{answer:"undeclaredBinding",answerKey:`${$.nodeId}.${$.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(VC,"upgradeGraph");function HH(e){return`waitlistOrder=${e.waitlistOrder}`}s(HH,"formatPolicy");function ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ci,"isObject");var BC="admission.generic",UC=Object.keys(uf).filter(e=>e!=="label");function GC(e){return ci(e.smartforms)?Object.entries(e.smartforms):[]}s(GC,"smartformEntries");function JH(e){let t=[];GC(e.index).some(([,i])=>ci(i)&&"outcomeFnRef"in i)&&t.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let n=Object.keys(e.manifest).filter(i=>Object.hasOwn(wl,i));if(n.length>0){let i=n.map(o=>`\`${o}\``).join(", ");t.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>UC.some(o=>o in i))&&t.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(ci(r.progressWiring)&&"layoutId"in r.progressWiring&&t.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),t.push(...jC(r.graph).map(i=>i.what))),t}s(JH,"legacyBundleShapes");function xp(e,t){let n=JH(e);n.length!==0&&ae("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${t} stammt aus einem \xE4lteren Bundle-Format (${n.map(r=>r.de).join("; ")}). Zuerst \`plexus-cli offer upgrade --dir <Bundle>\` ausf\xFChren (Probelauf, beantwortet die offenen Fragen), dann mit \`--write\` schreiben und erneut pr\xFCfen.`,en:`offer: ${t} is in an older bundle format (${n.map(r=>r.en).join("; ")}). Run \`plexus-cli offer upgrade --dir <bundle>\` first (a dry run that asks what it cannot decide), then write with \`--write\` and validate again.`})}s(xp,"assertBundleCurrent");function vp(e){let t=s(n=>Array.isArray(n)?n.map(t):ci(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n,"sort");return JSON.stringify(t(e))}s(vp,"canonical");function zC(e,t={}){let n=[],r=[],i=e.index,o=GC(i);if(o.some(([,u])=>ci(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!ci(h)||Object.keys(h).length===0){u[p]=h;continue}let{outcomeFnRef:w,...k}=h;if(Object.keys(k).length>0||w!==void 0&&w!==BC){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(y=>`\`${y}\``).join(", ")} \u2014 only \`outcomeFnRef: ${BC}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}n.push({file:"bundle.yaml",message:`smartforms.${p}.outcomeFnRef deleted (a form routes by its own declared outcomes)`}),u[p]={}}i={...i,smartforms:u}}let a={},l=e.workflow,d;for(let[u,p]of Object.entries(e.manifest)){if(u==="selection"){d=p,n.push({file:"manifest.json",message:"`selection` deleted (its queue policy goes to the waitlist node's inputs; release strategy and deadline were read by nothing)"});continue}if(u==="progressLayout"){l===void 0?n.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},n.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):vp(l.progressLayout)===vp(p)?n.push({file:"manifest.json",message:"`progressLayout` deleted (workflow.json carries the same layout)"}):(r.push({file:"manifest.json",code:"manifest/progressLayoutTwice",answer:"edit",message:"`progressLayout` differs from workflow.json `progressLayout` \u2014 keep one by hand"}),a[u]=p);continue}let h=Object.hasOwn(wl,u)?wl[u]:void 0;if(h===void 0){r.push({file:"manifest.json",code:"manifest/unknownKey",answer:"edit",message:`unknown key \`${u}\` \u2014 manifest.json carries no key; decide by hand where it belongs`}),a[u]=p;continue}n.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(ci(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},n.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(ci(u)&&Array.isArray(u.nodes)){let p=VC(u,{selection:d,answers:t});l={...l,graph:p.graph},n.push(...p.changes.map(h=>({...h,file:"workflow.json"}))),r.push(...p.refusals.map(h=>({...h,file:"workflow.json"})))}else r.push({file:"workflow.json",code:"workflow/graphShape",answer:"edit",message:"`graph` is no object with a node list"})}let c=e.smartforms;if(c!==void 0){let u={};for(let[p,h]of Object.entries(c)){let w={...h},k=`smartforms/${p}.json`;for(let y of UC)if(y in h){if(y==="outcomeIds"){let v=Array.isArray(h.outcomes)?h.outcomes.map(A=>ci(A)?A.id:void 0):[];if(vp([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==vp(v.map(String).sort())){r.push({file:k,code:"smartform/outcomeIdsDiffer",answer:"edit",message:"`outcomeIds` differs from the ids of `outcomes[]` \u2014 reconcile them by hand"});continue}}delete w[y],n.push({file:k,message:`\`${y}\` deleted (${uf[y].en})`})}u[p]=w}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:n,refusals:r}}s(zC,"upgradeOfferBundle");var QH={createManifest:x.workflow.createManifest,publishManifest:x.workflow.publishManifest,publishOfferInternal:x.workflow.publishOfferInternal,publishOfferExternal:x.workflow.publishOfferExternal,getOfferPublishState:x.workflow.getOfferPublishState,upsertCustomField:x.admission.upsertCustomField,upsertDerivedAttributeRule:x.admission.upsertDerivedAttributeRule,createSmartForm:x.forms.createSmartForm,getSmartFormBySlug:x.forms.getSmartFormBySlug,saveSmartFormDraft:x.forms.saveSmartFormDraft,publishSmartForm:x.forms.publishSmartForm,createWorkflow:x.workflow.createWorkflow,getWorkflowGraph:x.workflow.getWorkflowGraph,saveWorkflowDraft:x.workflow.saveWorkflowDraft,publishWorkflow:x.workflow.publishWorkflow},Qye={createManifest:Xt.workflow.createManifestInternal,publishManifest:Xt.workflow.publishManifestInternal,publishOfferInternal:Xt.workflow.publishOfferInternalInternal,publishOfferExternal:Xt.workflow.publishOfferExternalInternal,getOfferPublishState:Xt.workflow.getOfferPublishStateInternal,upsertCustomField:Xt.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:Xt.admission.upsertDerivedAttributeRuleInternal,createSmartForm:Xt.forms.createSmartFormInternal,getSmartFormBySlug:Xt.forms.getSmartFormBySlugInternal,saveSmartFormDraft:Xt.forms.saveSmartFormDraftInternal,publishSmartForm:Xt.forms.publishSmartFormInternal,createWorkflow:Xt.workflow.createWorkflowInternal,getWorkflowGraph:Xt.workflow.getWorkflowGraphInternal,saveWorkflowDraft:Xt.workflow.saveWorkflowDraftInternal,publishWorkflow:Xt.workflow.publishWorkflowInternal};function Lw(e,t){for(let[n,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&ae("INVALID",{de:`offer: ${t}: smartforms.${n} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${t}: smartforms.${n} must be an empty mapping ({}).`});let i=Object.keys(r);if(i.length===0)continue;let o=i.map(l=>`\`${l}\``).join(", "),a=i.includes("outcomeFnRef");ae("INVALID",{de:`offer: ${t}: smartforms.${n} enth\xE4lt unbekannte Schl\xFCssel ${o} \u2014 der Eintrag muss leer sein ({}).${a?" `outcomeFnRef` geh\xF6rt nicht mehr zum Bundle-Format: ein Formular entscheidet \xFCber seine eigenen Ergebnisse. Die Zeile l\xF6schen.":""}`,en:`offer: ${t}: smartforms.${n} carries unknown key(s) ${o} \u2014 the entry must be empty ({}).${a?" `outcomeFnRef` is no longer part of the bundle format: a form routes by its own declared outcomes. Delete the line.":""}`})}}s(Lw,"assertSmartformEntries");function WC(e){let t=s(n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n,"sort");return JSON.stringify(t(e))}s(WC,"canonicalJson");function YC(e,t){return t==null?!0:WC(e)!==WC(t)}s(YC,"changed");async function HC(e,t,n,r={},i=QH){let{index:o}=t;xp({index:o,manifest:t.manifest,...t.smartforms!==void 0?{smartforms:t.smartforms}:{},...t.workflow!==void 0?{workflow:t.workflow}:{}},`bundle of ${o.slugs.manifest}`),Lw(o,`bundle of ${o.slugs.manifest}`);let a=cf(t.manifest);a.length>0&&ae("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
|
|
11206
|
+
{{einstellungenLink}}`}}]},rw=[jW,WW,JW,QW,ZW,r1,n1,E1,$1,M1,K1,V1,G1,Y1,J1,X1,n2,o2,a2,R1,I1,O1,l2,d2,c2,i1,o1,l1,d1,f1,h1,w1,S1,D1,O2,N2,BW,GW,f2,m2,g2,w2,v2,S2,E2];function iw(e){let t=rw.find(n=>n.id===e);return t===void 0&&F(`notifications: unknown letter "${e}"`),t}s(iw,"letterDefFor");function ow(e){return rw.some(t=>t.id===e)}s(ow,"hasLetterDef");function sw(e,t){return t===void 0?!0:xf(e,t)}s(sw,"letterArgCompatible");function _l(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${bn(e)} (${e})`,en:`${bn(e)} (${e})`}}s(_l,"letterArgTypeLabel");function b_(e){let t=new Map,n=s((r,i)=>{let o=t.get(r);o===void 0?t.set(r,[i]):o.push(i)},"add");for(let r of e.args)n(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of o_)n(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return t}s(b_,"eventArgSources");function v_(e,t){let n=e.type===void 0?[...t]:t.filter(r=>sw(r.type,e.type));if(n.length>1)return{status:"ambiguous",matches:n};if(n.length===1){let r=n[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...t]}:{status:"unused"}}s(v_,"resolveLetterParam");var aw=["booked","rescheduled","cancelled"],C2={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},S_=":";function A_(e,t){return`${e}${S_}${t}`}s(A_,"appointmentEventId");function P2(e){let t=e.lastIndexOf(S_);if(t<=0)return null;let n=e.slice(t+1);return aw.includes(n)?{taskKey:e.slice(0,t),kind:n}:null}s(P2,"parseAppointmentEventId");var x_={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function Js(e){return Array.isArray(e.tasks)?e.tasks.filter(t=>typeof t?.key=="string"&&t.result?.kind==="appointment"):[]}s(Js,"appointmentTasksOf");function D2(e){return aw.map(t=>({id:A_(e.key,t),label:{de:`${x_[t].de} \u2013 \u201E${e.title.de}\u201C`,en:`${x_[t].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(D2,"appointmentTaskEvents");function E_(e,t){let n=t.notificationEvents?.(e)??[],r=Js(e).flatMap(D2);return r.length===0?n:[...n,...r]}s(E_,"nodeNotificationEvents");function F2(e){return Object.fromEntries(aw.map(t=>[A_(e,t),{templateId:C2[t]}]))}s(F2,"defaultAppointmentBindings");function L2(e,t){if(e===void 0)return{notifications:e,dropped:[]};let n=[],r={};for(let[i,o]of Object.entries(e))P2(i)?.taskKey===t?n.push(i):r[i]=o;return n.length===0?{notifications:e,dropped:n}:{notifications:Object.keys(r).length===0?void 0:r,dropped:n}}s(L2,"withoutAppointmentBindings");function Vf(e,t,n){let r=new Set(Js(t).map(d=>d.key)),i=new Set(Js(n).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=L2(o,d);o=c.notifications,a.push(...c.dropped)}let l=[];for(let d of i)if(!r.has(d))for(let[c,u]of Object.entries(F2(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(Vf,"syncAppointmentBindings");function M2(e){return e.kind==="task"&&!("title"in e)}s(M2,"isLegacyFreeTodoContext");function lw(e){let{context:t}=e;if(M2(t)&&F(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),t.kind==="task")return{...e,context:t,kind:"task",createdVia:"human",partyId:t.partyId};let{anchor:n,task:r,kind:i,title:o,description:a,...l}=t,d=n.scope==="node"?{nodeId:n.nodeId,templateKey:n.templateKey,gatesNode:n.gatesNode,blocks:n.blocks}:n.scope==="application"?{scope:"application",templateKey:n.templateKey}:n.scope==="crossNode"?{scope:"application",nodeId:n.nodeId,templateKey:n.templateKey,blocks:n.blocks}:{};return{...e,context:t,...l,...d,...r??{},kind:i}}s(lw,"readWorkItem");async function Nl(e,t){let n;if(t.nodeId!==void 0){let r=t.nodeId;n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(t.isOpen!==void 0){let r=t.isOpen;n=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",t.applicationId).eq("isOpen",r)).collect()}else n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",t.applicationId)).collect();return n.filter(r=>t.isOpen===void 0||r.isOpen===t.isOpen).map(lw)}s(Nl,"listWorkItemsForApplication");var cpe=m.union(m.literal("approved"),m.literal("rejected")),Cl=new Set(["task","approval"]);function q2(e,t){switch(e){case"task":return t?.gatesNode===!0&&F("expandComposedTask: gatesNode is approval-only \u2014 a 'task' template never gates its node (use blocks to hold a gating sibling back)"),{kind:"task",recipient:"internal",gatesNode:!1};case"approval":return{kind:"approval",recipient:"internal",isApproval:!0,gatesNode:t?.gatesNode??!0};default:F(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Cl].join(", ")}`)}}s(q2,"expandComposedTask");for(let e of["task","approval"]){let t=q2(e);t.kind==="approval"!=(t.isApproval===!0)&&F(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var T_=Ri,qi=`${T_}.`,K2=new Set(["text","number","date","boolean","option","edge"]);function Bf(e,t){let n=e[t];return n===void 0&&F(`[env/unknownKey] no environment key '${t}'`),typeof n=="string"?null:Object.keys(n)}s(Bf,"contextFields");function $_(e,t){return Object.hasOwn(e,t)}s($_,"isContextKey");function R_(e){let t=[];for(let n of Object.keys(e)){let r=Bf(e,n);if(r===null)t.push(n);else for(let i of r)t.push(`${n}.${i}`)}return t}s(R_,"leafPaths");function Pl(e,t){let[n="",r,...i]=t.split(".");if(!$_(e,n)||i.length>0)return;let o=e[n];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Pl,"leafType");function I_(e){let t=new Set;for(let n of e){let r=Qs(n);r!==null&&t.add(r.split(".")[0])}return[...t]}s(I_,"contextKeysOf");function Qs(e){return e.startsWith(qi)?e.slice(qi.length):null}s(Qs,"contextPathOf");function Dl(e){return e===T_||e.startsWith(qi)}s(Dl,"isContextIdentifier");function Uf(e,t){let n=Qs(t)??"",[r=""]=n.split("."),i=Object.keys(e);if(!$_(e,r))return{code:"env/unknownKey",message:{de:`'${t}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${t}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Pl(e,n)!==void 0)return null;let o=Bf(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${t}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${qi}${r}'.`,en:`'${t}': environment key '${r}' is a single value \u2014 read it as '${qi}${r}'.`}:{de:`'${t}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${t}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s(Uf,"identifierIssue");function Gf(e,t,n=Object.keys(e)){let r={};for(let i of n){let o=Bf(e,i),a=Object.hasOwn(t,i)?t[i]:void 0;if(a===void 0&&F(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${qi}${i}`]=a;continue}for(let l of o){let d=typeof a=="object"&&a!==null&&Object.hasOwn(a,l)?a[l]:void 0;d===void 0&&F(`[env/missing] context key '${i}' carries no '${l}'`),r[`${qi}${i}.${l}`]=d}}return r}s(Gf,"flatten");function O_(e,t,n){if(n===void 0)return!1;let r=Bf(e,t);return r===null?!0:typeof n=="object"&&n!==null&&r.every(i=>n[i]!==void 0)}s(O_,"contextValueComplete");function j2(e,t){switch(t){case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e);default:return typeof e=="string"}}s(j2,"valueMatchesDataType");function __(e,t,n=Object.keys(e.types)){let r=new Set(n);for(let i of R_(e.types)){if(!r.has(i.split(".")[0]))continue;let o=t[`${qi}${i}`];o===void 0&&F(`[env/missing] context path '${i}' was not supplied`);let a=e.fields[i];if(o===null){a.nullable||F(`[env/null] context path '${i}' is not nullable but carries null`);continue}let l=bn(Pl(e.types,i));j2(o,l)||F(`[env/type] context path '${i}' expects ${l}, got ${JSON.stringify(o)}`),a.valueSet.kind==="fixed"&&!a.valueSet.values.includes(o)&&F(`[env/value] context path '${i}' carries '${String(o)}', outside ${a.valueSet.values.join(" | ")}`)}}s(__,"assertContextValues");function V2(e){let t=[],n=R_(e.types);for(let r of n){let i=Pl(e.types,r),o=bn(i);if(!Ci(i)||o===void 0||!K2.has(o)){t.push(`'${r}' has type '${String(i)}', not a scalar value type`);continue}let a=Object.hasOwn(e.fields,r)?e.fields[r]:void 0;if(a===void 0){t.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&t.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&t.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))n.includes(r)||t.push(`field spec '${r}' names no leaf of the schema`);return t}s(V2,"schemaIssues");function Zs(e){let t=V2(e);t.length>0&&F(`[env/schema] ${t.join("; ")}`)}s(Zs,"assertSchema");var zf={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function Ki(e){return JSON.stringify(e)}s(Ki,"canonical");function ea(e){return e.kind==="binary"&&e.op==="&&"?[...ea(e.left),...ea(e.right)]:[e]}s(ea,"conjuncts");function P_(e,t){let n;try{n=Rt(e)}catch{return!1}let r=Ki(Rt(t));return ea(n).some(i=>Ki(i)===r)}s(P_,"hasConjunct");function D_(e,t){try{return Ki(Rt(e))===Ki(Rt(t))}catch{return!1}}s(D_,"sameCondition");function F_(e){let t=[];for(let n of e)t.push(...It(ei(n)));return I_(t)}s(F_,"contextKeysRead");function L_(e){try{return It(Rt(e)).some(Dl)}catch{return!1}}s(L_,"readsContext");var B2=/^\d{4}-\d{2}-\d{2}$/,U2=new Set(["==","!=","<","<=",">",">=","in"]),G2=new Set(["<","<=",">",">="]);function Yf(e,t,n=[]){Zs(t);let r;try{r=Rt(e)}catch(a){let l=a.message;return[Ut("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of It(r)){if(!Dl(a)){i.push(Ut("condition/foreignIdentifier",`'${a}' ist kein Umgebungswert \u2014 Bedingungen lesen nur '$env.*'`,`'${a}' is not a context identifier \u2014 conditions read only '$env.*'`));continue}let l=Uf(t.types,a);l!==null&&i.push(Ut("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Dr(r,t,i);Fl(o)||i.push(Ut("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),H2(r,t,i);for(let{identifier:a,op:l}of uw(r,t))i.push(Ut("condition/unguardedNullable",`'${l}' \xFCber '${a}', das leer sein kann, braucht davor eine Absicherung '${a} != null &&'`,`'${l}' over '${a}', which may be null, needs a guard '${a} != null &&' before it`));return i.push(...z2(r,n)),i}s(Yf,"conditionIssues");function z2(e,t){let n=ea(e).map(Ki);return t.flatMap(r=>{let i=Rt(r),o=W2(i);return o===null||!n.includes(Ki(o))?[]:[{severity:"info",code:"condition/guardForm",message:{de:`[condition/guardForm] eine gespiegelte Absicherung z\xE4hlt nicht \u2014 schreibe sie genau als '${r}'`,en:`[condition/guardForm] a mirrored guard does not count \u2014 write it exactly as '${r}'`}}]})}s(z2,"guardFormHints");function W2(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let t={...e,left:e.right,right:e.left};return Ki(t)===Ki(e)?null:t}s(W2,"mirror");function Fl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Fl,"isBooleanish");function M_(e){let t=Qs(e);return t===null&&F(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),t}s(M_,"contextPath");function q_(e,t){let n=Qs(t);return n!==null&&e.fields[n]?.nullable===!0}s(q_,"isNullableLeaf");function Y2(e,t){let n=bn(Pl(e.types,M_(t)));return n===void 0?{t:"unknown"}:{t:"data",dt:n}}s(Y2,"identType");function Wf(e,t){return e.t==="unknown"||t.t==="unknown"||e.t==="null"||t.t==="null"?!0:e.t==="array"||t.t==="array"?!1:e.t==="str"&&t.t==="str"?!0:e.t==="str"?N_(e.value,t.dt):t.t==="str"?N_(t.value,e.dt):e.dt===t.dt}s(Wf,"fits");function N_(e,t){return t==="text"||t==="option"||t==="edge"?!0:t==="date"?B2.test(e):!1}s(N_,"strFits");function C_(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(C_,"orderedCategory");function Dr(e,t,n){switch(e.kind){case"num":return{t:"data",dt:"number"};case"bool":return{t:"data",dt:"boolean"};case"str":return{t:"str",value:e.value};case"null":return{t:"null"};case"ident":return Y2(t,e.path);case"arr":for(let r of e.items)Dr(r,t,n);return{t:"array"};case"unary":{let r=Dr(e.operand,t,n);return Fl(r)||n.push(Ut("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(zf,e.name)?zf[e.name]:void 0,i=e.args.map(l=>Dr(l,t,n));return r===void 0?(n.push(Ut("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(zf).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(zf).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&Wf(l,{t:"data",dt:r.params[d]}))||n.push(Ut("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Dr(e.cond,t,n);Fl(r)||n.push(Ut("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Dr(e.then,t,n),o=Dr(e.else,t,n);return Wf(i,o)||n.push(Ut("condition/typeMismatch","die beiden Zweige von 'if' haben verschiedene Typen","the two arms of 'if' differ in type")),i.t==="null"?o:i}case"binary":{let r=Dr(e.left,t,n),i=Dr(e.right,t,n);if(e.op==="&&"||e.op==="||")(!Fl(r)||!Fl(i))&&n.push(Ut("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?n.push(Ut("condition/inWithoutArray","'in' braucht rechts eine Liste, z. B. ['a', 'b']","'in' needs a list on its right, e.g. ['a', 'b']")):e.right.items.every(o=>Wf(r,Dr(o,t,[])))||n.push(Ut("condition/typeMismatch","ein Listeneintrag von 'in' passt nicht zum Typ des linken Operanden","a list item of 'in' does not match the left operand's type"));else if(G2.has(e.op)){let o=C_(r),a=C_(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&n.push(Ut("condition/orderedComparison",`'${e.op}' vergleicht nur Zahlen \u2014 f\xFCr Daten years_between(\u2026) verwenden`,`'${e.op}' compares only numbers \u2014 for dates use years_between(\u2026)`))}else Wf(r,i)||n.push(Ut("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Dr,"typeOf");function dw(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(dw,"isLiteral");function K_(e){let t=[],n=s(r=>{if(r.kind==="binary"&&U2.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(dw):dw(r.right)?[r.right]:[];i.length>0&&t.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&dw(r.left)&&t.push({ident:r.right.path,literals:[r.left]})}j_(r,n)},"visit");return n(e),t}s(K_,"comparedLiterals");function H2(e,t,n){for(let{ident:r,literals:i}of K_(e)){let o=J2(r,i,t);o!==null&&n.push(o)}}s(H2,"literalIssues");function cw(e,t){let n;try{n=Rt(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of K_(n)){let a=Qs(i);if(!(a===null||t.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(cw,"liveLiterals");function J2(e,t,n){let r=n.fields[M_(e)]?.valueSet;if(r?.kind==="unstable")return Ut("condition/literalOnUnstable",`'${e}' ist nicht \xFCber Umgebungen stabil \u2014 vergleiche ihn mit keinem festen Wert; verzweige stattdessen \xFCber ein stabiles Merkmal`,`'${e}' is not stable across environments \u2014 compare it to no literal; branch on a stable attribute instead`);if(r?.kind!=="fixed")return null;let i=t.flatMap(a=>a.kind==="str"&&!r.values.includes(a.value)?[`'${a.value}'`]:[]);if(i.length===0)return null;let o=r.values.map(a=>`'${a}'`).join(", ");return Ut("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(J2,"valueSetIssue");function j_(e,t){switch(e.kind){case"binary":t(e.left),t(e.right);return;case"unary":t(e.operand);return;case"call":e.args.forEach(t);return;case"arr":e.items.forEach(t);return;case"if":t(e.cond),t(e.then),t(e.else);return;default:return}}s(j_,"forEachChild");function V_(e){return e.kind==="binary"&&(e.op==="=="||e.op==="!=")&&(e.left.kind==="ident"&&e.right.kind==="null"||e.left.kind==="null"&&e.right.kind==="ident")}s(V_,"isNullTest");function B_(e){return ea(e).flatMap(t=>{let n=U_(t);return n===null?[]:[n]})}s(B_,"guardsOf");function Ll(e,t,n){switch(e.kind){case"ident":return q_(t,e.path)&&!n.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=Ll(r,t,n);if(i!==null)return i}return null;case"if":return Ll(e.then,t,new Set([...n,...B_(e.cond)]))??Ll(e.else,t,n);default:return null}}s(Ll,"unguardedNullSource");function U_(e){return!V_(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(U_,"guardedIdent");function Xs(e,t,n,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(n);for(let o of ea(e)){Xs(o,t,i,r);let a=U_(o);a!==null&&i.add(a)}return}if(e.kind==="if"){Xs(e.cond,t,n,r),Xs(e.then,t,new Set([...n,...B_(e.cond)]),r),Xs(e.else,t,n,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=Ll(e.left,t,n)??Ll(e.right,t,n);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!V_(e.operand)){let i=It(e.operand).filter(o=>q_(t,o)&&!n.has(o));i.length>0&&r(i[0],"!")}j_(e,i=>Xs(i,t,n,r))}s(Xs,"nullableReads");function uw(e,t){Zs(t);let n=[];return Xs(e,t,new Set,(r,i)=>{n.some(o=>o.identifier===r)||n.push({identifier:r,op:i})}),n}s(uw,"unguardedNullableReads");function Ut(e,t,n){return{severity:"error",code:e,message:{de:`[${e}] ${t}`,en:`[${e}] ${n}`}}}s(Ut,"error");function Ml(e){let t=Array.isArray(e.nodes)?e.nodes:[],n=new Set;for(let r of t)for(let i of Rf(r))i.key!==null&&qs[i.leaf].involves&&n.add(i.key);return n}s(Ml,"declaredGroupKeys");var ta=of;var Q2="unit.key",Z2="offer.key";function G_(e,t){return e===Q2?t.unitKeys:e===Z2?t.offerKeys:null}s(G_,"liveKeyUniverse");function Hf(e){return[ht,...[...Ml(e)].sort((t,n)=>t.localeCompare(n)).map(ff)]}s(Hf,"requiredSlots");var ji=`${af("applicant.channel")} == 'staff'`;var pw=["strict","leastLoaded"];var fw=2;function z_(e){return e.some(t=>t.length===0)?{de:"nennt einen leeren Personenschl\xFCssel",en:"names an empty person key"}:new Set(e).size!==e.length?{de:"nennt eine Person zweimal",en:"names a person twice"}:e.length<fw?{de:`braucht mindestens ${fw} Personen`,en:`needs at least ${fw} people`}:null}s(z_,"rotationPoolProblem");function X2(e,t){let n=t===null?-1:e.indexOf(t);return[...e.slice(n+1),...e.slice(0,n+1)]}s(X2,"strictOrder");function W_(e){let t=X2(e.pool,e.previous).filter(i=>e.eligible.has(i));if(t.length===0)return null;if(e.mode==="strict")return t[0];let n=e.openCounts;n===void 0&&F("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=n.get(i);return o===void 0&&F(`[assignment/rotation] no open count for '${i}'`),o},"load");return t.reduce((i,o)=>r(o)<r(i)?o:i)}s(W_,"pickFromPool");function H_(e){return e.map(t=>({slot:pI(t.slot),rules:[...t.rules]}))}s(H_,"rulesOfStored");function J_(e){return e.map(t=>({slot:eY(t.slot),rules:[...t.rules]}))}s(J_,"storedOfRules");function eY(e){let t=mf(e);return t===null&&F(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),t}s(eY,"slotOf");function Q_(e,t){let n=e?.assignmentRules;n===void 0&&F(`[assignment/noRules] ${t}: the workflow has no assignment rule`);let r=tN(n);return r.length>0&&F(`${r.join("; ")} (${t})`),H_(n)}s(Q_,"rulesOfGraph");function tY(e){return e===ht?{slot:e,rules:[{when:ji,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(tY,"defaultSlotRules");function Z_(e,t){let n=new Set(e.map(o=>o.slot)),r=t.filter(o=>!n.has(o)).map(tY);return[...r.filter(o=>o.slot===ht),...e,...r.filter(o=>o.slot!==ht)]}s(Z_,"withRequiredSlots");function _t(e,t){return t===void 0?`slot '${e}'`:`slot '${e}' row #${t+1}`}s(_t,"where");function Cn(e,t){return t===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${t+1}`}s(Cn,"whereDe");function vn(e,t,n={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${t.de}`,en:`[${e}] ${t.en}`},...n}}s(vn,"issue");function Y_(e){if(e===ht)return!0;let t=pf(e);return t!==null&&t.length>0}s(Y_,"isKnownSlot");function nY(e,t){Zs(ta);let n=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;Y_(l)||n.push(vn("assignment/unknownSlot",{de:`'${l}' ist keine Liste \u2014 'responsible' oder 'team:<teamKey>'`,en:`'${l}' is no slot \u2014 'responsible' or 'team:<teamKey>'`},{slot:l})),r.has(l)&&n.push(vn("assignment/duplicateSlot",{de:`${Cn(l)} steht zweimal da`,en:`${_t(l)} is listed twice`},{slot:l})),r.add(l),l===ht&&a!==0&&n.push(vn("assignment/responsibleFirst",{de:`'${ht}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${ht}' must be the first slot \u2014 team rows copy it`},{slot:l})),n.push(...rY(o))});for(let o of t)r.has(o)||n.push(vn("assignment/slotMissing",{de:`${Cn(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${_t(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(t);for(let{slot:o}of e)o!==ht&&!i.has(o)&&Y_(o)&&n.push(vn("assignment/unusedSlot",{de:`${Cn(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${_t(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return n}s(nY,"validateRules");function rY({slot:e,rules:t}){let n=[];return(t.length===0||t[t.length-1].when!==null)&&n.push(vn("assignment/defaultRowMissing",{de:`${Cn(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${_t(e)} must end with a row without condition ("otherwise")`},{slot:e})),t.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<t.length-1&&n.push(vn("assignment/ruleAfterDefault",{de:`${Cn(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${_t(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=Yf(a,ta,[ji]);for(let c of d)n.push({...c,message:{de:`${c.message.de} (${Cn(e,i)})`,en:`${c.message.en} (${_t(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){L_(a)||n.push(vn("assignment/shadowedRule",{de:`${Cn(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${_t(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=t.slice(0,i).findIndex(u=>u.when!==null&&D_(u.when,a));c!==-1&&n.push(vn("assignment/shadowedRule",{de:`${Cn(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${_t(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===ht&&l.kind==="slot"&&n.push(vn("assignment/slotForwardRef",{de:`${Cn(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${ht}'`,en:`${_t(e,i)} copies '${l.slot}' \u2014 only a team slot after '${ht}' may`},o)),e===ht&&l.kind==="queue"&&n.push(vn("assignment/queueOnProcessSlot",{de:`${Cn(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${_t(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&n.push(vn("assignment/targetMissing",{de:`${Cn(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${_t(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=z_(l.configKeys);d!==null&&n.push(vn("assignment/rotationPool",{de:`${Cn(e,i)}: die Reihum-Liste ${d.de}`,en:`${_t(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!P_(a,ji))&&n.push(vn("assignment/unguardedTarget",{de:`${Cn(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${ji}' ist (oder enth\xE4lt)`,en:`${_t(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${ji}'`},o))}),n}s(rY,"rowIssues");function X_(e,t){for(let r of t)e.some(i=>i.slot===r)||F(`[assignment/slotMissing] ${_t(r)} has no rule list`);let n=new Set(t);return e.filter(r=>n.has(r.slot))}s(X_,"selectSlots");function iY(e,t){return F_(X_(e,t).flatMap(n=>n.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(iY,"contextKeysOfRules");function eN(e,t,n,r){Zs(ta);let i=X_(e,n),o=iY(e,n),a=Gf(ta.types,t,o);__(ta,a,o);let l=[];for(let{slot:d,rules:c}of i){let u=c.findIndex((h,w)=>{if(h.when===null)return!0;for(let k of It(ei(h.when)))Object.hasOwn(a,k)||F(`[condition/unknownIdentifier] ${_t(d,w)} reads '${k}', which the context does not carry`);return VI(h.when,{values:a})});u===-1&&F(`[assignment/defaultRowMissing] ${_t(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:oY(d,u,p,l,r)})}return l}s(eN,"evaluateRules");function oY(e,t,n,r,i){switch(n.kind){case"person":return{kind:"value",value:i.person(n.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(n,{slot:e,row:t})};case"unassigned":return F(`[assignment/targetMissing] ${_t(e,t)} names no one`);case"queue":return e===ht&&F(`[assignment/queueOnProcessSlot] ${_t(e,t)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===ht?void 0:r.find(a=>a.slot===n.slot);return o===void 0&&F(`[assignment/slotForwardRef] ${_t(e,t)} copies '${n.slot}', which is not decided before it`),o.value}}}s(oY,"resolveTarget");var mw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function sY(e){if(typeof e!="object"||e===null)return!1;let{kind:t,groupKey:n,...r}=e;return Object.keys(r).length>0?!1:t==="responsible"?n===void 0:t==="team"&&typeof n=="string"&&n.length>0}s(sY,"isStoredSlot");function tN(e){let t=[],n=s((r,i)=>t.push(`[assignment/shape] ${r}: ${i}`),"bad");return Array.isArray(e)?(e.forEach((r,i)=>{let o=`slots[${i}]`;if(typeof r!="object"||r===null)return n(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&n(o,`unknown field(s) ${Object.keys(d).join(", ")}`),sY(a)||n(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return n(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return n(p,"must be { when, assign }");let{when:h,assign:w,...k}=c;Object.keys(k).length>0&&n(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&n(p,"when must be a condition string or null (\u201Esonst\u201C)");let y=w?.kind;if(typeof w!="object"||w===null||typeof y!="string"||!Object.hasOwn(mw,y))return n(p,`assign must be one of ${Object.keys(mw).map(I=>`{kind:'${I}'}`).join(", ")}`);let v=mw[y],A=Object.keys(w);(A.some(I=>!v.includes(I))||v.some(I=>!A.includes(I)))&&n(p,`a '${y}' target has exactly the field(s) ${v.join(", ")}`);let E=w;if(y==="person"&&(typeof E.configKey!="string"||E.configKey.length===0)&&n(p,"a 'person' target needs a non-empty configKey"),y==="rotation"){let I=E.configKeys;(!Array.isArray(I)||I.some(C=>typeof C!="string"))&&n(p,"a 'rotation' target needs configKeys, a list of person keys"),pw.includes(E.mode)||n(p,`a 'rotation' target's mode is one of ${pw.map(C=>`'${C}'`).join(", ")}`)}y==="slot"&&E.slot!==ht&&n(p,`a 'slot' target copies '${ht}' and nothing else`)})}),t):(n("slots","must be a list of { slot, rules }"),t)}s(tN,"ruleShapeIssues");function nN(e){let t=e??{},n=[];if(t.teamOwnerBindings!==void 0&&n.push({de:"[assignment/legacyBindings] der Workflow tr\xE4gt noch teamOwnerBindings \u2014 die Zust\xE4ndigkeitsregel ersetzt sie; das Feld entfernen",en:"[assignment/legacyBindings] the workflow still carries teamOwnerBindings \u2014 the assignment rule replaces them; remove the field"}),t.assignmentRules===void 0)return n.push({de:"[assignment/noRules] der Workflow hat keine Zust\xE4ndigkeitsregel (graph.assignmentRules) \u2014 jeder Workflow muss sagen, wer zust\xE4ndig wird",en:"[assignment/noRules] the workflow has no assignment rule (graph.assignmentRules) \u2014 every workflow must say who becomes responsible"}),n;let r=tN(t.assignmentRules);if(r.length>0)return[...n,...r.map(o=>({de:o,en:o}))];let i=Hf({nodes:Array.isArray(t.nodes)?t.nodes:[]});for(let o of nY(H_(t.assignmentRules),i))o.severity==="error"&&n.push(o.message);return n}s(nN,"workflowAssignmentIssues");function Jf(e,t){let o=new Map;for(let d of e)o.set(d,0);let a=new Map,l=[];for(let d of e){if((o.get(d)??0)!==0)continue;let c=[{id:d,edges:t(d),idx:0}];for(o.set(d,1),a.set(d,null);c.length>0;){let u=c[c.length-1];if(u.idx>=u.edges.length){o.set(u.id,2),c.pop();continue}let{target:p,edge:h}=u.edges[u.idx];u.idx++;let w=o.get(p)??0;if(w===1){let k=[p],y=u.id;for(;y&&y!==p;)k.push(y),y=a.get(y)??null;k.reverse(),l.push({edge:h,source:u.id,target:p,cycle:k})}else w===0&&(o.set(p,1),a.set(p,u.id),c.push({id:p,edges:t(p),idx:0}))}}return l}s(Jf,"detectBackEdges");var hw="team:",aY=/^[a-z0-9][a-z0-9-]*$/;function lY(e){if(!e.startsWith(hw))return null;let t=e.slice(hw.length);return t.length>0?t:null}s(lY,"teamKeyOfMember");function Qf(e){return`${hw}${e}`}s(Qf,"teamMember");function na(e){let t=e.channels;return t===void 0?[]:(Array.isArray(t)||F("graph.channels must be an array"),t)}s(na,"readAuthoredChannels");function rN(e){return[...Ml(e)].sort()}s(rN,"derivedChannelTeamKeys");function iN(e,t){let n=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!t.has(n))return n;for(let r=2;;r++){let i=`${n}-${r}`;if(!t.has(i))return i}}s(iN,"mintChannelKey");function oN(e,t){let n=e.channels;if(n===void 0)return[];if(!Array.isArray(n))return[{path:"channels",reason:{de:"[channels/shape] graph.channels muss eine Liste sein.",en:"[channels/shape] graph.channels must be a list."}}];let r=[],i=Ml(e),o=new Set,a=new Map;return n.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||$t(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(A=>typeof A=="string")){r.push({path:c,reason:{de:"[channels/shape] Ein Kanal braucht key, label ({ de, en }) und members (Liste von Texten).",en:"[channels/shape] A channel needs key, label ({ de, en }) and members (a list of texts)."}});return}let p={de:`Kanal "${u.key}"`,en:`Channel "${u.key}"`};aY.test(u.key)||r.push({path:`${c}.key`,reason:{de:`[channels/invalidKey] ${p.de}: Schl\xFCssel nur aus Kleinbuchstaben, Ziffern und Bindestrich.`,en:`[channels/invalidKey] ${p.en}: key only from lowercase letters, digits and hyphens.`}}),o.has(u.key)&&r.push({path:`${c}.key`,reason:{de:`[channels/duplicateKey] ${p.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[channels/duplicateKey] ${p.en}: key is used twice.`}}),o.add(u.key);let h=$t(u.label);if(h!=="not-localized"&&h.length===2?r.push({path:`${c}.label`,reason:{de:`[channels/emptyLabel] ${p.de}: Bezeichnung fehlt.`,en:`[channels/emptyLabel] ${p.en}: name is missing.`}}):h!=="not-localized"&&h.length>0&&r.push({path:`${c}.label`,reason:{de:`[i18n/missingTranslation] ${p.de}: Bezeichnung fehlt in: ${h.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${p.en}: name is missing in: ${h.join(", ")} \u2014 every displayed text needs German and English.`}}),u.members.length===0){r.push({path:`${c}.members`,reason:{de:`[channels/emptyMembers] ${p.de}: mindestens ein Team.`,en:`[channels/emptyMembers] ${p.en}: at least one team.`}});return}let w=[];for(let A of u.members){let E=lY(A);if(E===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${A}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${A}" is not a "team:<key>".`}});continue}if(w.includes(E)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${E}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${E}" is named twice.`}});continue}t!==void 0&&!t.has(E)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${E}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${E}" does not exist at this school (or it is the applicant group).`}}),w.push(E)}if(w.length===0)return;let k=[...w].sort().join("+"),[y]=w;w.length===1&&y!==void 0&&i.has(y)&&r.push({path:`${c}.members`,reason:{de:`[channels/duplicatesDerived] ${p.de}: Team "${y}" ist am Prozess beteiligt und hat seinen Kanal schon automatisch.`,en:`[channels/duplicatesDerived] ${p.en}: team "${y}" takes part in the process and already has its channel automatically.`}});let v=a.get(k);v!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${v}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${v}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(oN,"channelIssues");var rme=Object.freeze({});function dY(e,t){return Object.freeze(Gf(Yr,e,t))}s(dY,"formContextEntries");function sN(e){return e.env??[]}s(sN,"declaredContextKeys");function aN(e,t){return sN(e).every(n=>lN(n,t?.[n]))}s(aN,"scenarioContextComplete");function lN(e,t){return O_(Yr,e,t)}s(lN,"contextValueComplete");function dN(e,t){return dY(t??{},sN(e))}s(dN,"scenarioContextEntries");function yw(e){return Dl(e)}s(yw,"isContextIdentifier");function cY(e,t,n){let r=Uf(Yr,e);if(r!==null)return{severity:"error",path:n,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return t.has(i)?null:{severity:"error",path:n,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(cY,"contextIdentifierIssue");var gw=af("stage.key");function uY(e){let t=[],n=s(i=>i.kind==="ident"&&i.path===gw,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(n(i.left)&&i.right.kind==="str"&&t.push(i.right.value),n(i.right)&&i.left.kind==="str"&&t.push(i.left.value)),i.op==="in"&&n(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&t.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),t}s(uY,"stageKeyLiterals");function Zf(e,t,n){return t===void 0?[]:uY(e).filter(r=>!t.has(r)).map(r=>uN(r,t,n))}s(Zf,"stageKeyAstIssues");function cN(e,t){if(t===void 0)return[];let n=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!t.has(i.key)&&n.push(uN(i.key,t,`scenario:${r.id}/env`))}return n}s(cN,"scenarioStageKeyIssues");function uN(e,t,n){let r=[...t].sort();return{severity:"error",path:n,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${gw}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${gw}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(uN,"unknownStageKeyIssue");function fN(e,t,n){let r=[];for(let i of It(e)){if(!yw(i))continue;let o=cY(i,t,n);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of uw(e,of))r.push({severity:"error",path:n,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(fN,"contextAstIssues");function pN(e,t){let n=[...fY(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Es(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${As.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${As.join(", ")}).`}});continue}t!==void 0&&!t.has(i)&&n.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>Es(a)&&!lN(a,i.env?.[a]));o.length>0&&n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))Es(a)?r.has(a)||n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return n}s(pN,"formContextIssues");function fY(e){let t=[];Object.hasOwn(e,"context")&&t.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let n=e.testScenarios;for(let r of Array.isArray(n)?n:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&t.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return t}s(fY,"retiredContextFields");function Xf(e,t,n){let r=Yf(e,t).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(n?.liveEnvKeys!==void 0)for(let o of cw(e,t)){let a=G_(o.path,n.liveEnvKeys);a===null&&F(`[condition] no live-key universe for '${o.path}' \u2014 extend liveKeyUniverse`),a.has(o.value)||i.push({de:`$env.${o.path} == '${o.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${o.path} == '${o.value}' names no key of this school.`})}for(let o of Zf(Rt(e),n?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(Xf,"envConditionFindings");function ep(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(ep,"isReviewField");function ra(e){let t=[],n=[];function r(y,v){try{return Rt(y)}catch(A){t.push({path:v,src:y,reason:A instanceof Error?A.message:String(A)});return}}s(r,"tryParse");function i(y,v){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,requiredIf:y.requiredIf?r(y.requiredIf,`${v}.requiredIf`):void 0,disabledIf:y.disabledIf?r(y.disabledIf,`${v}.disabledIf`):void 0,defaultValue:y.defaultValue?r(y.defaultValue,`${v}.defaultValue`):void 0}}s(i,"compileField");function o(y,v){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,fields:y.fields.map((A,E)=>i(A,`${v}.fields[${E}]`))}}s(o,"compileGroup");function a(y,v){return{...y,itemTemplate:y.itemTemplate.map((A,E)=>i(A,`${v}.itemTemplate[${E}]`)),effects:y.effects?.map((A,E)=>d(A,`${v}.effects[${E}]`)),itemVisibleIf:y.itemVisibleIf?r(y.itemVisibleIf,`${v}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(y,v){let A=[];return y.fields.forEach((E,I)=>{if(E.externalFlag){n.push({key:E.key,label:E.label,defaultValue:E.defaultValue?r(E.defaultValue,`${v}.fields[${I}].defaultValue`):void 0});return}A.push(i(E,`${v}.fields[${I}]`))}),{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${v}.visibleIf`):void 0,fields:A,groups:y.groups?.map((E,I)=>o(E,`${v}.groups[${I}]`)),computed:y.computed?.map((E,I)=>{let C=r(E.expression,`${v}.computed[${I}].expression`);return{key:E.key,expression:C??{kind:"null"}}}),subsections:y.subsections?.map((E,I)=>l(E,`${v}.subsections[${I}]`)),repeated:y.repeated?.map((E,I)=>a(E,`${v}.repeated[${I}]`)),validators:y.validators}}s(l,"compileSection");function d(y,v){return{...y,when:y.when?r(y.when,`${v}.when`):void 0}}s(d,"compileEffect");function c(y,v){let A=r(y.when,`${v}.when`);return A?{...y,when:A}:null}s(c,"compileOutcome");let u=e.sections.map((y,v)=>l(y,`sections[${v}]`)),p=(e.effects??[]).map((y,v)=>d(y,`effects[${v}]`)),h=[],w=e.outcomes??[];for(let y=0;y<w.length;y++){let v=w[y],A=c(v,`outcomes[${y}]`);A&&h.push(A)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:n},errors:t}}s(ra,"compileForm");var pY=new Set(["decision","review","governedDocument"]);function hN(e){return pY.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(hN,"isReadinessGatedNode");function mY(e){let t=new Map,n=gY(e),r=s((i,o)=>{let a=ww(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&t.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:hY(d.bucket,n,a),section:a,type:d.type,enumSource:mN(d),repeated:!1,reviewRequired:d.reviewRequired===!0});for(let d of i.repeated??[])for(let c of d.itemTemplate){let u=`${d.key}.${c.key}`;t.set(u,{kind:"entered",key:u,label:c.label,qualifier:ww(d),section:a,type:c.type,enumSource:mN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=It(Rt(d.expression));t.set(d.key,{kind:"computed",key:d.key,label:d.label??{de:d.key,en:d.key},qualifier:a,deps:c})}for(let d of i.subsections??[])r(d,o)},"visit");for(let i of e.sections)r(i,i);return t}s(mY,"formFieldCatalog");function mN(e){return e.type==="enum"?e:null}s(mN,"enumSourceOf");function hY(e,t,n){return e===void 0?n:t.get(e)??n}s(hY,"fieldQualifier");function gY(e){let t=new Map,n=s((r,i)=>{i===void 0||t.has(r)||t.set(r,ww(i))},"add");for(let r of yN(e))r.kind==="person"?n(r.bucket,r.display):r.kind==="organization"&&n(r.id.replace(/^o\./,""),r.display);return t}s(gY,"bucketWordings");function gN(e){return e.flatMap(t=>[t,...gN(t.subsections??[])])}s(gN,"allSections");function yN(e){return[...e.effects,...gN(e.sections).flatMap(t=>(t.repeated??[]).flatMap(n=>n.effects??[]))]}s(yN,"allEffects");function ww(e){return{label:e.label}}s(ww,"wordingOf");function wN(e){return Sl(e).flatMap(({slot:t,address:n})=>{let r=YI(n);return r===null||xl.includes(r.path)?[]:[{slotId:t,owner:r.owner,fieldKey:r.path}]})}s(wN,"admissionBindingLeaves");function yY(e,t){let n=e.get(t);if(n===void 0)return null;let r=[],i=new Set,o=s(a=>{if(!i.has(a.key)&&(i.add(a.key),r.push({fieldKey:a.key,kind:a.kind}),a.kind==="computed"))for(let l of a.deps){let d=e.get(l);d!==void 0&&o(d)}},"walk");return o(n),r}s(yY,"expandKey");function wY(e){let t=new Set;for(let n of yN(e))if(!(n.kind!=="person"||n.contractParty===void 0)&&n.when!==void 0)for(let r of It(Rt(n.when)))t.add(r);return[...t]}s(wY,"contractPartyConditionKeys");function kY(e){return ra(e).compiled.flags.map(t=>({key:t.key,name:t.label}))}s(kY,"formExternalFlags");function kN(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([t,n])=>[t,mY(n)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set(wY(n))])),formFlagKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set(kY(n).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([t,n])=>[t,new Set((n.views??[]).map(r=>r.key))]))}}s(kN,"readinessUniverse");function kw(e,t){let n=new Set;for(let r of t)for(let i of yY(e,r)??[])i.kind==="entered"&&n.add(i.fieldKey);return n}s(kw,"enteredFieldsBehind");var bY=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function vY(e){return bY.has(e)?!0:bN(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(vY,"isTextKey");function bN(e){return/^localized[A-Z]/.test(e)}s(bN,"isLegacyTwinKey");var xY=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),SY=new Set(["inputs","resolver","library"]);function np(e,t){let n=[];return bw(e,t,n),n}s(np,"findUnlocalizedTexts");function bw(e,t,n){if(Array.isArray(e)){e.forEach((i,o)=>bw(i,`${t}[${EY(i,o)}]`,n));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${t}.${i}`;if(!SY.has(i)){if(bN(i)){n.push({path:a,missing:"legacy-twin"});continue}if(vY(i)){AY(o,a,n);continue}if(xY.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&vN(d,`${a}.${l}`,n);continue}bw(o,a,n)}}}s(bw,"walk");function AY(e,t,n){e!=null&&vN(e,t,n)}s(AY,"checkText");function vN(e,t,n){let r=$t(e);(r==="not-localized"||r.length>0)&&n.push({path:t,missing:r})}s(vN,"report");function EY(e,t){if(e!==null&&typeof e=="object"){let n=e;if(typeof n.id=="string")return n.id;if(typeof n.key=="string")return n.key}return String(t)}s(EY,"keyOf");function tp(e,t){return e==="not-localized"?t==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?t==="de"?'ist ein Zwilling der alten Form \u2014 der Text geh\xF6rt in das Feld ohne \u201Elocalized"':'is a twin of the old shape \u2014 the text belongs in the field without "localized"':t==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(tp,"describe");function vw({path:e,missing:t}){return t==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${tp(t,"de")}.`,en:`[i18n/legacyTwin] ${e} ${tp(t,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${tp(t,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${tp(t,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(vw,"unlocalizedTextReason");var TY={engagePush:["engage"]};function $Y(e){let t=TY[e.type];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([n])=>!t.includes(n)))}s($Y,"withoutMachineData");function xN(e,t){return[...np(e.nodes.map($Y),"nodes"),...t===void 0?[]:np(t,`layout.${t.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:vw(r),severity:"error"}))}s(xN,"checkLocalizedTexts");var Io=5,Oo=480;function ii(e){return typeof e=="string"&&e.trim().length>0}s(ii,"isNonEmptyString");function AN(e,t,n){return Object.keys(e).filter(r=>!t.includes(r)).map(r=>({field:`result.${r}`,code:tt.unknownField,message:{de:`Unbekanntes Feld '${r}' im ${n.de}; erlaubt sind: ${t.join(", ")}.`,en:`Unknown field '${r}' in the ${n.en}; allowed: ${t.join(", ")}.`}}))}s(AN,"unknownFieldIssues");function RY(e){let t=[],n=e.title;(n===void 0||typeof n!="object"||n===null||!ii(n.de)||!ii(n.en))&&t.push({field:"result.title",code:tt.appointmentMissingTitle,message:{de:"Ein Termin-Ergebnis braucht einen neutralen Titel in beiden Sprachen ({ de, en }) \u2014 er steht in der Mail und in der Kalenderdatei der Familie, deshalb nie ein Familienname.",en:"An appointment result needs a neutral title in both languages ({ de, en }) \u2014 it appears in the email and in the family's calendar file, so never a family name."}});let r=e.durationMinutes;return(typeof r!="number"||!Number.isInteger(r)||r<Io||r>Oo)&&t.push({field:"result.durationMinutes",code:tt.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Io} bis ${Oo} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Io} to ${Oo}, got ${JSON.stringify(r)}.`}}),t.push(...AN(e,["kind","title","durationMinutes"],{de:"Termin-Ergebnis",en:"appointment result"})),t}s(RY,"appointmentIssues");function SN(e){if(typeof e!="object"||e===null)return!1;let t=e;return ii(t.de)&&ii(t.en)}s(SN,"isBilingual");var xw=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom"];function IY(e){let t=s((i,o)=>({field:i,code:tt.recordFields,message:o}),"issue");if(!Array.isArray(e)||e.length===0)return[t("result.fields",{de:"Eine Erfassung braucht mindestens ein Feld ('result.fields').",en:"A record needs at least one field ('result.fields')."})];let n=[],r=new Set;for(let[i,o]of e.entries()){let a=`result.fields[${i}]`;if(typeof o!="object"||o===null||Array.isArray(o)){n.push(t(a,{de:"Ein Feld der Erfassung muss ein Objekt sein.",en:"A field of the record must be an object."}));continue}let l=o,d=l.key;typeof d!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(d)?n.push(t(`${a}.key`,{de:`Feld-Schl\xFCssel ${JSON.stringify(d)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,en:`Field key ${JSON.stringify(d)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`})):r.has(d)?n.push(t(`${a}.key`,{de:`Feld-Schl\xFCssel "${d}" ist doppelt.`,en:`Field key "${d}" is duplicated.`})):r.add(d);let c=typeof d=="string"?`"${d}"`:`Nr. ${i+1}`,u=typeof d=="string"?`"${d}"`:`no. ${i+1}`;if(gy(l.type)||n.push(t(`${a}.type`,{de:`Feld ${c}: Typ ${JSON.stringify(l.type)} \u2014 erlaubt: ${gf.join(", ")}.`,en:`Field ${u}: type ${JSON.stringify(l.type)} \u2014 allowed: ${gf.join(", ")}.`})),SN(l.label)||n.push(t(`${a}.label`,{de:`Feld ${c} braucht ein Label in beiden Sprachen ({ de, en }).`,en:`Field ${u} needs a label in both languages ({ de, en }).`})),ii(l.writes)||n.push(t(`${a}.writes`,{de:`Feld ${c} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`,en:`Field ${u} writes to no process key ('writes') \u2014 a value nobody can read does not belong in a record.`})),l.type==="enum"){let h=Array.isArray(l.options)?l.options:[],w=h.map(k=>k.key);(h.length<2||w.some(k=>typeof k!="string"||k.length===0)||new Set(w).size!==w.length||h.some(k=>!SN(k.label)))&&n.push(t(`${a}.options`,{de:`Feld ${c} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`,en:`Field ${u} (choice) needs at least 2 options with unique keys and labels in both languages.`}))}else l.options!==void 0&&n.push(t(`${a}.options`,{de:`Feld ${c}: 'options' gibt es nur bei Typ 'enum'.`,en:`Field ${u}: 'options' exists only for type 'enum'.`}));if(l.min!==void 0&&(l.type!=="number"||typeof l.min!="number"||!Number.isInteger(l.min))&&n.push(t(`${a}.min`,{de:`Feld ${c}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`,en:`Field ${u}: 'min' exists only for type 'number', as a whole number.`})),l.evidence!==void 0&&typeof l.evidence!="boolean"&&n.push(t(`${a}.evidence`,{de:`Feld ${c}: 'evidence' ist true oder false.`,en:`Field ${u}: 'evidence' is true or false.`})),l.evidenceFrom!==void 0){let h=typeof l.min=="number"?l.min:0;(l.type!=="number"||l.evidence!==!0||typeof l.evidenceFrom!="number"||!Number.isInteger(l.evidenceFrom)||l.evidenceFrom<=h)&&n.push(t(`${a}.evidenceFrom`,{de:`Feld ${c}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${h}) \u2014 sonst g\xE4lte der Nachweis immer.`,en:`Field ${u}: 'evidenceFrom' exists only for type 'number' with 'evidence', as a whole number above the minimum (${h}) \u2014 otherwise the proof would always apply.`}))}if(l.suggest!==void 0){let h=l.suggest,w=typeof h=="object"&&h!==null?h.kind:void 0;w==="form"&&"address"in h&&Object.keys(h).length===2&&(!xe(h.address)||ct(h.address))||w==="siblingRank"&&Object.keys(h).length===1&&l.type==="number"||n.push({field:`${a}.suggest`,code:tt.recordSuggest,message:{de:`Feld ${c}: Vorschlag ${JSON.stringify(l.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${yy.join(", ")}.`,en:`Field ${u}: suggestion ${JSON.stringify(l.suggest)} \u2014 allowed: { kind: 'form', address: '$node.<form>.admission.<export>' } or { kind: 'siblingRank' } (only for type 'number'); known kinds: ${yy.join(", ")}.`}})}let p=Object.keys(l).filter(h=>!xw.includes(h));p.length>0&&n.push(t(a,{de:`Feld ${c}: unbekannte Angabe ${p.map(h=>`'${h}'`).join(", ")}; erlaubt: ${xw.join(", ")}.`,en:`Field ${u}: unknown entry ${p.map(h=>`'${h}'`).join(", ")}; allowed: ${xw.join(", ")}.`}))}return n}s(IY,"recordFieldIssues");function OY(e,t,n){let r=[],i=t.options;if(e==="choice"){let o=Array.isArray(i)?i:[],a=o.map(l=>l.key);(o.length<2||a.some(l=>typeof l!="string"||l.length===0)||new Set(a).size!==a.length)&&r.push({field:"result.options",code:tt.choiceOptions,message:{de:`Ein Auswahl-Ergebnis braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln, erhalten ${JSON.stringify(a)}.`,en:`A choice result needs at least 2 options with unique keys, got ${JSON.stringify(a)}.`}})}else i!==void 0&&r.push({field:"result.options",code:tt.choiceOptions,message:{de:`'result.options' gibt es nur bei 'choice' \u2014 ${e==="recommendation"?"eine Empfehlung hat die festen Tendenzen Positiv/Neutral/Negativ":"ein Freitext hat keine Auswahl"}.`,en:`'result.options' exists only for 'choice' \u2014 ${e==="recommendation"?"a recommendation has the fixed leanings Positive/Neutral/Negative":"a free text has no choice"}.`}});if(e==="pricedItem"){let o=t.item;if(!ii(o))r.push({field:"result.item",code:tt.pricedItemMissingItem,message:{de:"Ein Preispositions-Ergebnis nennt den Artikel, den es bepreist \u2014 'result.item' (der Schl\xFCssel des Artikels, z. B. 'tuition') fehlt.",en:"A priced-item result names the article it prices \u2014 'result.item' (the article's key, e.g. 'tuition') is missing."}});else if(n.billingItemKeys!==void 0&&!n.billingItemKeys.has(o))r.push({field:"result.item",code:tt.pricedItemUnknownItem,message:{de:`'result.item' "${o}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...n.billingItemKeys].join(", ")||"keine"}).`,en:`'result.item' "${o}" \u2014 no article of this school has this key (known: ${[...n.billingItemKeys].join(", ")||"none"}).`}});else if(n.offerProgram===null)r.push({field:"result.item",code:tt.pricedItemOfferWithoutProgram,message:{de:`'result.item' "${o}" \u2014 das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.`,en:`'result.item' "${o}" \u2014 the offer is not assigned to a program, so no article belongs to it; give the offer a program.`}});else if(n.offerProgram!==void 0&&!n.offerProgram.billingItemKeys.has(o)){let l=n.offerProgram;r.push({field:"result.item",code:tt.pricedItemNotInProgram,message:{de:`'result.item' "${o}" \u2014 der Artikel ist dem Programm \u201E${l.nameDe}\u201C des Angebots nicht zugeordnet (zugeordnet: ${[...l.billingItemKeys].join(", ")||"keine"}); unter Finanzen \u2192 Artikel zuordnen, direkt oder \xFCber ein Paket.`,en:`'result.item' "${o}" \u2014 the article is not assigned to the offer's program "${l.nameDe}" (assigned: ${[...l.billingItemKeys].join(", ")||"none"}); assign it under Finance \u2192 articles, directly or through a package.`}})}let a=t.label;(typeof a!="object"||a===null||!ii(a.de)||!ii(a.en))&&r.push({field:"result.label",code:tt.labelMissing,message:{de:"Ein Preispositions-Ergebnis braucht einen Namen f\xFCr seinen Wert in beiden Sprachen ('result.label', z. B. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 so hei\xDFt er im Workflow und in der Verdrahtung.",en:"A priced-item result needs a name for its value in both languages ('result.label', e.g. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 that is what it is called in the workflow and in the wiring."}})}else t.item!==void 0&&r.push({field:"result.item",code:tt.itemOnNonPricedItem,message:{de:`'result.item' gibt es nur bei 'pricedItem' \u2014 ein ${e}-Ergebnis bepreist keinen Artikel.`,en:`'result.item' exists only for 'pricedItem' \u2014 a ${e} result prices no article.`}});if(e==="record"?(r.push(...IY(t.fields)),t.writes!==void 0&&r.push({field:"result.writes",code:tt.writesOnProse,message:{de:"Eine Erfassung schreibt je Feld ('fields[].writes'), nie als Ganzes ('result.writes').",en:"A record writes per field ('fields[].writes'), never as a whole ('result.writes')."}}),t.label!==void 0&&r.push({field:"result.label",code:tt.unknownField,message:{de:"Eine Erfassung benennt ihre Werte je Feld ('fields[].label'), nicht als Ganzes ('result.label').",en:"A record names its values per field ('fields[].label'), not as a whole ('result.label')."}})):t.fields!==void 0&&r.push({field:"result.fields",code:tt.fieldsOnNonRecord,message:{de:`'result.fields' gibt es nur bei 'record' \u2014 ein ${e}-Ergebnis hat keine Felder.`,en:`'result.fields' exists only for 'record' \u2014 a ${e} result has no fields.`}}),e==="reduction"&&(ii(t.writes)||r.push({field:"result.writes",code:tt.reductionPrices,message:{de:"Eine Reduktion schreibt ihren Betrag in einen Vorgangs-Schl\xFCssel vom Typ reduction ('result.writes') \u2014 sonst l\xE4se ihn kein Preis.",en:"A reduction writes its amount to a process key of type reduction ('result.writes') \u2014 otherwise no price would read it."}})),t.writes!==void 0&&(e==="freetext"||e==="recommendation")&&r.push({field:"result.writes",code:tt.writesOnProse,message:{de:`'result.writes' gibt es nur bei Ergebnissen mit Wert (Auswahl, Preisposition) \u2014 ein ${e}-Ergebnis bleibt im Chat und schreibt nichts in den Vorgang.`,en:`'result.writes' exists only for results with a value (choice, priced item) \u2014 a ${e} result stays in the chat and writes nothing to the process.`}}),e==="freetext"&&t.textRequired!==void 0&&r.push({field:"result.textRequired",code:tt.textRequiredOnFreetext,message:{de:"'textRequired' auf einem Freitext-Ergebnis \u2014 der Text eines Freitexts ist immer Pflicht; die Angabe entfernen.",en:"'textRequired' on a free-text result \u2014 the text of a free text is always required; remove the entry."}}),t.chat===void 0)r.push({field:"result.chat",code:tt.chatMissing,message:{de:"Ein Aufgaben-Ergebnis steht nur im Chat \u2014 'result.chat' fehlt: 'all', 'team:<Gruppe>' oder einen Kanal des Workflows angeben.",en:"A task result appears only in the chat \u2014 'result.chat' is missing: give 'all', 'team:<group>' or a channel of the workflow."}});else{let o=t.chat,a=typeof o=="string"?_s(o):null;o==="external"||a===null?r.push({field:"result.chat",code:tt.chatExternal,message:{de:`'result.chat' ${JSON.stringify(o)} \u2014 ein Aufgaben-Ergebnis bleibt intern: erlaubt sind 'all', 'team:<Gruppe>' oder ein Kanal des Workflows, nie 'external'.`,en:`'result.chat' ${JSON.stringify(o)} \u2014 a task result stays internal: 'all', 'team:<group>' or a channel of the workflow are allowed, never 'external'.`}}):a.kind==="channel"&&!n.channelKeys.has(a.channelKey)&&r.push({field:"result.chat",code:tt.chatUnknownChannel,message:{de:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...n.channelKeys].join(", ")||"keine"}).`,en:`'result.chat' "${a.channelKey}" is neither 'all' nor 'team:<group>' nor a channel of the workflow (known: ${[...n.channelKeys].join(", ")||"none"}).`}})}return r.push(...AN(t,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(OY,"recordedIssues");function EN(e,t,n={channelKeys:new Set}){if(t===void 0)return[];if(e!=="task")return[{field:"result",code:tt.onApproval,message:{de:`'result' gilt nur f\xFCr die Art 'task' \u2014 eine '${e}' wird durch ihr Votum abgeschlossen, nicht durch ein Ergebnis.`,en:`'result' applies only to the kind 'task' \u2014 an '${e}' is completed by its vote, not by a result.`}}];if(typeof t!="object"||t===null||Array.isArray(t))return[{field:"result",code:tt.unknownKind,message:{de:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${Is.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Is.join(", ")}.`}}];let r=t;return NI(r.kind)?r.kind==="appointment"?RY(r):OY(r.kind,r,n):[{field:"result.kind",code:tt.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Is.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Is.join(", ")}.`}}]}s(EN,"taskResultIssues");var Sw=60;function oi(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(oi,"error");function _Y(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"warning"}}s(_Y,"warning");function TN(e){return Array.isArray(e.tasks)?e.tasks:[]}s(TN,"tasksOf");function RN(e,t){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(r=>r.action==="spawnTasks"&&Array.isArray(r.tasks)&&r.tasks.includes(t))}s(RN,"spawnActionsOf");function $N(e,t){return RN(e,t).map(n=>String(n.key)).sort()}s($N,"bindingsOf");function IN(e,t){let n=[],r=TN(e),i=new Map;for(let o of r){if(o.appointment===void 0)continue;let a=typeof o.key=="string"?o.key:"?",l=`nodes.${e.id}.tasks.${a}`,d={de:`Terminaufgabe "${a}" (Knoten "${e.id}")`,en:`Appointment task "${a}" (node "${e.id}")`},c=o.appointment,p=typeof c=="object"&&c!==null&&Object.keys(c).every($=>$==="of"||$==="dueDaysAfterEnd")&&typeof c.of=="string"?c.of:void 0,h=p===void 0?void 0:r.find($=>$.key===p),w=h?.result;if(p===void 0||h===void 0||w?.kind!=="appointment")n.push(oi(`${l}.appointment.of`,{de:`[workItems/appointmentOfUnknown] ${d.de} braucht 'appointment: { of, dueDaysAfterEnd }', und 'of' nennt eine Aufgabe desselben Knotens, die mit einem Termin abschlie\xDFt (result.kind 'appointment'); erhalten ${JSON.stringify(o.appointment)}.`,en:`[workItems/appointmentOfUnknown] ${d.en} needs 'appointment: { of, dueDaysAfterEnd }', and 'of' names a task of the same node that ends with an appointment (result.kind 'appointment'); got ${JSON.stringify(o.appointment)}.`}));else{i.set(p,(i.get(p)??0)+1);let $=h.blocks,b=[...["when","optional"].filter(R=>h[R]!==void 0),...typeof $?.node=="string"&&$.node!==e.id?["blocks"]:[]];b.length>0&&n.push(oi(`nodes.${e.id}.tasks.${p}.${b[0]}`,{de:`[workItems/appointmentTaskShape] "${p}" bucht den Termin f\xFCr ${d.de} und tr\xE4gt ${b.map(R=>R==="blocks"?"ein knoten\xFCbergreifendes 'blocks'":`'${R}'`).join(", ")} \u2014 fiele sie ohne Buchung weg oder \xFCberlebte sie ihren Knoten, wartete die Terminaufgabe f\xFCr immer bzw. f\xE4nde die Buchung keine Terminaufgabe mehr.`,en:`[workItems/appointmentTaskShape] "${p}" books the appointment for ${d.en} and carries ${b.map(R=>R==="blocks"?"a cross-node 'blocks'":`'${R}'`).join(", ")} \u2014 if it dropped out without a booking or outlived its node, the appointment task would wait forever or the booking would find no appointment task any more.`}));for(let R of RN(e,p))R.repeatable!==!0&&n.push(oi(`nodes.${e.id}.optionalActions.${String(R.key)}.repeatable`,{de:`[workItems/appointmentActionRepeatable] Die optionale Aktion "${String(R.key)}" legt "${p}" an, die den Termin f\xFCr ${d.de} bucht, und ist nicht 'repeatable: true'. Eine Absage beendet die Runde; ohne zweite Runde lie\xDFe sich die Aktion nie wieder ausl\xF6sen, und eine Entscheidung, die auf sie wartet (requiresOneOf), bliebe h\xE4ngen.`,en:`[workItems/appointmentActionRepeatable] The optional action "${String(R.key)}" creates "${p}", which books the appointment for ${d.en}, and is not 'repeatable: true'. A cancellation ends the round; without a second round the action could never be triggered again, and a decision waiting for it (requiresOneOf) would hang.`}));$N(e,a).join(",")!==$N(e,p).join(",")&&n.push(oi(`${l}.appointment.of`,{de:`[workItems/appointmentTaskBinding] ${d.de} geh\xF6rt zu anderen optionalen Aktionen als "${p}", die ihren Termin bucht \u2014 beide Zeilen sind eine Runde: entweder beide in derselben Aktion (spawnTasks) oder beide in keiner.`,en:`[workItems/appointmentTaskBinding] ${d.en} belongs to different optional actions than "${p}", which books its appointment \u2014 both rows are one round: either both in the same action (spawnTasks) or both in none.`}))}let k=c?.dueDaysAfterEnd;(typeof k!="number"||!Number.isInteger(k)||k<0||k>Sw)&&n.push(oi(`${l}.appointment.dueDaysAfterEnd`,{de:`[workItems/appointmentTaskDue] ${d.de}: 'dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${Sw} \u2014 die Tage nach dem Terminende, bis die Aufgabe f\xE4llig ist; erhalten ${JSON.stringify(k)}.`,en:`[workItems/appointmentTaskDue] ${d.en}: 'dueDaysAfterEnd' is a whole number from 0 to ${Sw} \u2014 the days after the appointment ends until the task is due; got ${JSON.stringify(k)}.`})),o.params?.dueInDays!==void 0&&n.push(oi(`${l}.params.dueInDays`,{de:`[workItems/appointmentTaskDue] ${d.de} tr\xE4gt 'params.dueInDays' neben 'appointment.dueDaysAfterEnd' \u2014 eine Terminaufgabe ist ab dem Terminende f\xE4llig, nie ab ihrer Anlage.`,en:`[workItems/appointmentTaskDue] ${d.en} carries 'params.dueInDays' next to 'appointment.dueDaysAfterEnd' \u2014 an appointment task is due from the end of the appointment, never from its creation.`}));let y=o.result,v=["when","optional","familyRequest","reads","locksEvidence"].filter($=>o[$]!==void 0).map($=>`'${$}'`),A=typeof o.blocks?.node=="string"&&o.blocks.node!==e.id,E=s($=>[...o.kind!=="task"?["'kind: approval'"]:[],...y===void 0||!_i(y.kind)?[$==="de"?"kein erfasstes Ergebnis (Feedback)":"no recorded result (feedback)"]:[],...v,...A?[$==="de"?"ein knoten\xFCbergreifendes 'blocks'":"a cross-node 'blocks'"]:[]],"shapeFaults");E("de").length>0&&n.push(oi(`${l}.appointment`,{de:`[workItems/appointmentTaskShape] ${d.de}: ${E("de").join(", ")} \u2014 eine Terminaufgabe ist eine Aufgabe, die mit ihrem Feedback (Freitext, Empfehlung, Auswahl) abschlie\xDFt, und sie entsteht, weil der Termin entsteht: ohne Bedingung, nicht optional, keine Nachforderung, ohne Belege (nichts l\xE4sst sie ungebunden neu entstehen) und an ihrem Knoten.`,en:`[workItems/appointmentTaskShape] ${d.en}: ${E("en").join(", ")} \u2014 an appointment task is a task that ends with its feedback (free text, recommendation, choice), and it exists because the appointment exists: no condition, not optional, no follow-up request, no evidence (nothing lets it be created again unbound) and on its own node.`}));let I=o.result?.chat,C=o.assign?.group;typeof I=="string"&&I.startsWith("team:")&&typeof C=="string"&&I!==`team:${C}`&&n.push(_Y(`${l}.result.chat`,{de:`[workItems/appointmentChatUnreadable] ${d.de} schreibt ihr Feedback in "${I}", geh\xF6rt aber dem Team "${C}" \u2014 die Gastgeberin bzw. der Gastgeber (ein Mitglied von "${C}") kann das eigene Feedback dort wom\xF6glich nicht lesen. 'team:${C}' oder 'all' w\xE4hlen, oder das Team als Mitglied des Chats sicherstellen.`,en:`[workItems/appointmentChatUnreadable] ${d.en} writes its feedback to "${I}", but belongs to the team "${C}" \u2014 the host (a member of "${C}") may not be able to read their own feedback there. Choose 'team:${C}' or 'all', or make sure the team is a member of the chat.`}));for(let $ of t)for(let b of TN($)){let R=b.blocks;R?.templateKey!==a||(typeof R.node=="string"?R.node:$.id)!==e.id||n.push(oi(`nodes.${$.id}.tasks.${String(b.key)}.blocks.templateKey`,{de:`[workItems/appointmentTaskBlocked] Task "${String(b.key)}" (Knoten "${$.id}") h\xE4lt ${d.de} zur\xFCck \u2014 eine Terminaufgabe wartet nur auf ihren Termin (abgeleitet aus 'appointment.of'); ein 'blocks' auf sie entf\xE4llt.`,en:`[workItems/appointmentTaskBlocked] Task "${String(b.key)}" (node "${$.id}") holds back ${d.en} \u2014 an appointment task only waits for its appointment (derived from 'appointment.of'); a 'blocks' on it is dropped.`}))}}for(let[o,a]of i)a<2||n.push(oi(`nodes.${e.id}.tasks.${o}`,{de:`[workItems/appointmentOfTwice] ${a} Terminaufgaben auf Knoten "${e.id}" geh\xF6ren zum Termin von "${o}" \u2014 ein Termin hat eine Terminaufgabe.`,en:`[workItems/appointmentOfTwice] ${a} appointment tasks on node "${e.id}" belong to the appointment of "${o}" \u2014 an appointment has one appointment task.`}));return n}s(IN,"appointmentTaskIssues");var NY="optionalAction:";function ON(e){return`${NY}${e}:trigger`}s(ON,"optionalActionTriggerActionId");var CY="processDecide";function _N(e){let t=e.optionalActions;return t==null?[]:(Array.isArray(t)||F(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof t}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),t)}s(_N,"optionalActionBindings");function NN(e){return _N(e).map(t=>({id:ON(t.key),kind:"internal",label:t.label,surface:CY,placement:"overflow",superUserOnly:!0}))}s(NN,"optionalActionTriggers");function CN(e){let t=new Set;for(let n of _N(e))if(n.action==="spawnTasks")for(let r of n.tasks??[])t.add(r);return t}s(CN,"referencedTaskTemplateKeys");var xn={notOptionalAction:"[workItems/familyRequestNotOptionalAction]",notTask:"[workItems/familyRequestNotTask]",closedOtherwise:"[workItems/familyRequestClosedOtherwise]",blocks:"[workItems/familyRequestBlocks]",noDeadline:"[workItems/familyRequestNoDeadline]",fields:"[workItems/familyRequestFields]",unknownField:"[workItems/familyRequestUnknownField]",shape:"[workItems/familyRequestShape]",twicePerAction:"[workItems/familyRequestTwicePerAction]",deadlock:"[workItems/familyRequestOnlyWayButAsked]"};function Sn(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${t} ${n.de}`,en:`${t} ${n.en}`},severity:"error"}}s(Sn,"issue");function PY(e,t,n){return e.flatMap(r=>(Array.isArray(r.tasks)?r.tasks:[]).filter(i=>{let o=i.blocks,a=typeof o?.node=="string"?o.node:r.id;return o?.templateKey===n&&a===t}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(PY,"blockersOf");function PN(e){let{graph:t,node:n,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${n.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(t,n.id,"de")}\u201C (${n.id})`,en:`Task "${o}" on node "${_e(t,n.id,"en")}" (${n.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[Sn(`${a}.familyRequest`,xn.shape,{de:`${l.de}: 'familyRequest' muss ein Objekt { fields } oder { from } sein.`,en:`${l.en}: 'familyRequest' must be an object { fields } or { from }.`})];let c=Object.keys(i).filter(k=>k!=="fields"&&k!=="from");c.length>0&&d.push(Sn(`${a}.familyRequest.${c[0]}`,xn.shape,{de:`${l.de}: 'familyRequest' kennt nur 'fields' oder 'from', nicht ${c.map(k=>`'${k}'`).join(", ")} \u2014 was angefordert wird und der Text an die Familie werden beim Ausl\xF6sen gew\xE4hlt.`,en:`${l.en}: 'familyRequest' only knows 'fields' or 'from', not ${c.map(k=>`'${k}'`).join(", ")} \u2014 what is requested and the text to the family are chosen when the action is triggered.`}));let{fields:u,from:p}=i;u===void 0==(p===void 0)&&d.push(Sn(`${a}.familyRequest`,xn.shape,{de:`${l.de}: 'familyRequest' nennt genau eines \u2014 'fields' (die anforderbaren Felder) oder 'from' (das Formular, dessen Dateifelder alle zur Wahl stehen).`,en:`${l.en}: 'familyRequest' names exactly one \u2014 'fields' (the fields that can be requested) or 'from' (the form whose file fields are all available).`})),e.onTrigger.has(o)||d.push(Sn(`${a}.familyRequest`,xn.notOptionalAction,{de:`${l.de} fordert bei der Familie an, geh\xF6rt aber zu keiner optionalen Aktion (spawnTasks) \u2014 nur deren Ausl\xF6sen \xF6ffnet die Anfrage an die Familie.`,en:`${l.en} requests from the family but belongs to no optional action (spawnTasks) \u2014 only triggering one opens the request to the family.`})),r.kind!=="task"&&d.push(Sn(`${a}.kind`,xn.notTask,{de:`${l.de} fordert bei der Familie an und muss die Art 'task' haben, nicht ${JSON.stringify(r.kind)}.`,en:`${l.en} requests from the family and must have the kind 'task', not ${JSON.stringify(r.kind)}.`}));for(let k of["result","when","locksEvidence","gatesNode"])r[k]!==void 0&&d.push(Sn(`${a}.${k}`,xn.closedOtherwise,{de:`${l.de} wartet auf die Familie und erledigt sich mit ihrer Antwort \u2014 '${k}' passt nicht dazu.`,en:`${l.en} waits for the family and completes with their answer \u2014 '${k}' does not fit that.`}));r.blocks!==void 0&&d.push(Sn(`${a}.blocks`,xn.blocks,{de:`${l.de} wartet auf die Familie und darf nichts zur\xFCckhalten ('blocks') \u2014 sie h\xE4lt ihren Knoten schon als Aufgabe einer optionalen Aktion.`,en:`${l.en} waits for the family and must not hold anything back ('blocks') \u2014 as the task of an optional action it already holds its node.`}));for(let k of PY(t.nodes,n.id,o))d.push(Sn(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,xn.blocks,{de:`Task "${k.key}" auf Knoten "${k.nodeId}" h\xE4lt ${l.de} zur\xFCck \u2014 eine Nachforderung darf nie zur\xFCckgehalten werden: zur\xFCckgehalten h\xE4tte sie keine Frist und k\xF6nnte mit der Antwort der Familie nicht erledigt werden.`,en:`Task "${k.key}" on node "${k.nodeId}" holds back ${l.en} \u2014 a follow-up request must never be held back: held back, it would have no deadline and could not be completed by the family's answer.`}));let h=r.params?.dueInDays;if((typeof h!="number"||!Number.isInteger(h)||h<1)&&d.push(Sn(`${a}.params.dueInDays`,xn.noDeadline,{de:`${l.de} fordert bei der Familie an und braucht eine Frist in ganzen Tagen ('params.dueInDays' \u2265 1) \u2014 sie ist die Frist der Familie und Anlass der Erinnerung.`,en:`${l.en} requests from the family and needs a deadline in whole days ('params.dueInDays' \u2265 1) \u2014 it is the family's deadline and the reason for the reminder.`})),u===void 0)return d;if(!Array.isArray(u)||u.length===0)return d.push(Sn(`${a}.familyRequest.fields`,xn.fields,{de:`${l.de}: 'familyRequest.fields' muss mindestens ein Feld eines Formulars nennen \u2014 oder statt dessen 'from' das Formular, dann stehen alle seine Dateifelder zur Wahl.`,en:`${l.en}: 'familyRequest.fields' must name at least one field of a form \u2014 or 'from' the form instead, then all its file fields are available.`})),d;let w=new Set;for(let k of u){if(!xe(k))continue;let y=pe(k);if(w.has(y)){d.push(Sn(`${a}.familyRequest.fields`,xn.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(t,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(t,k,"en")} more than once.`}));continue}w.add(y),ct(k)||d.push(Sn(`${a}.familyRequest.fields`,xn.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(t,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(t,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(PN,"familyRequestIssues");function DN(e){let t=new Set((Array.isArray(e.tasks)?e.tasks:[]).flatMap(r=>r.familyRequest!==void 0&&typeof r.key=="string"?[r.key]:[]));return(Array.isArray(e.optionalActions)?e.optionalActions:[]).flatMap((r,i)=>{if(r.action!=="spawnTasks"||!Array.isArray(r.tasks))return[];let o=r.tasks.filter(a=>typeof a=="string"&&t.has(a));return o.length<=1?[]:[Sn(`nodes.${e.id}.optionalActions.${i}.tasks`,xn.twicePerAction,{de:`Optionale Aktion \u201E${String(r.key)}\u201C auf Knoten "${e.id}" startet ${o.length} Nachforderungen (${o.join(", ")}) \u2014 ein Ausl\xF6sen fragt die Familie nach EINER Sache; h\xF6chstens eine Nachforderung je Aktion.`,en:`Optional action "${String(r.key)}" on node "${e.id}" starts ${o.length} follow-up requests (${o.join(", ")}) \u2014 one trigger asks the family for ONE thing; at most one follow-up request per action.`})]})}s(DN,"familyRequestActionIssues");function FN(e,t){let n=e.nodes,r=new Map;for(let a of n)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)ct(l)&&r.set(pe(l),l);if(r.size===0)return[];let i=s(a=>{let l=ni(t,a);return l===void 0||l!==null&&l.kind==="entered"&&l.type==="docRef"},"isFileField"),o=s(a=>{let{fields:l,from:d}=a??{};return Array.isArray(l)?l.filter(ct):!xe(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return n.flatMap(a=>{let l=Array.isArray(a.requiresOneOf)?a.requiresOneOf:[],c=(Array.isArray(a.optionalActions)?a.optionalActions:[]).filter(h=>l.includes(h.key)),u=Array.isArray(a.tasks)?a.tasks:[];return c.filter(h=>Array.isArray(h.tasks)&&c.every(w=>w===h||w.when!==void 0)).flatMap(h=>u.flatMap(w=>{if(w.familyRequest===void 0||!h.tasks.includes(w.key))return[];let k=o(w.familyRequest).filter(y=>r.has(pe(y)));return k.length===0?[]:[{...Sn(`nodes.${a.id}.requiresOneOf`,xn.deadlock,{de:`Auf Knoten \u201E${_e(e,a.id,"de")}\u201C (${a.id}) ist die Nachforderung \u201E${String(h.key)}\u201C der einzige Weg durch 'requiresOneOf', und eine Vollst\xE4ndigkeitspr\xFCfung fragt dieselben Felder an (${k.map(y=>je(e,y,"de")).join(", ")}). Ist deren Anfrage offen, lassen sich diese Felder nicht nachfordern \u2014 die Entscheidung bliebe gesperrt. Eine zweite Aktion in 'requiresOneOf' oder andere Felder l\xF6sen das.`,en:`On node "${_e(e,a.id,"en")}" (${a.id}) the follow-up request "${String(h.key)}" is the only way through 'requiresOneOf', and a completeness check asks for the same fields (${k.map(y=>je(e,y,"en")).join(", ")}). While its request is open, these fields cannot be requested \u2014 the decision would stay locked. A second action in 'requiresOneOf' or other fields solve this.`}),severity:"warning"}]}))})}s(FN,"familyRequestDeadlockWarnings");var Aw={key:!0,kind:!0,title:!0,assign:!0,gatesNode:!0,blocks:!0,completableIf:!0,result:!0,when:!0,onConditionReturn:!0,reads:!0,locksEvidence:!0,feedback:!0,description:!0,documents:!0,formView:!0,familyRequest:!0,optional:!0,appointment:!0,params:!0};function DY(e){let t=Ye(e);return new Map((typeof t.workItemTemplates=="function"?t.workItemTemplates(e):[]).map(n=>[n.key,n]))}s(DY,"intrinsicTemplatesOf");function LN(e,t,n){if(n!==void 0&&typeof n!="string")return null;let r=n??t,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=Ye(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:DY(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(LN,"resolveBlocksTargetNode");function FY(e){let t=new Map;for(let r of Zn(e.nodes)){let i=t.get(r.source)??[];i.push(r.target),t.set(r.source,i)}let n=new Map;return r=>{let i=n.get(r);if(i!==void 0)return i;let o=new Set,a=[...t.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...t.get(l)??[]))}return n.set(r,o),o}}s(FY,"reachability");function MN(e){let t=[],n=new Map;for(let o of e.nodes){let a=o;for(let l of Array.isArray(a.tasks)?a.tasks:[]){let d=typeof l.key=="string"?l.key:void 0,c=l.blocks;if(d===void 0||typeof c?.templateKey!="string")continue;let u=typeof c.node=="string"?c.node:o.id;n.set(`${o.id}::${d}`,`${u}::${c.templateKey}`)}}let r=new Map,i=s((o,a)=>{if(r.get(o)==="done")return;if(r.get(o)==="visiting"){let d=[...a.slice(a.indexOf(o)),o],[c,u]=o.split("::");t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${c}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksCycle] Zyklus im 'blocks'-Graphen: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 jedes Mitglied w\xFCrde auf ein anderes warten, keines w\xFCrde je frei.`,en:`[workItems/blocksCycle] Cycle in the 'blocks' graph: ${d.map(p=>`"${p.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 every member would wait for another, none would ever be released.`},severity:"error"});return}r.set(o,"visiting");let l=n.get(o);l!==void 0&&n.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of n.keys())i(o,[]);return t}s(MN,"checkBlocksCycles");function LY(e){let{requiresOneOf:t,optionalActions:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return new Set;let r=new Set(t.filter(o=>typeof o=="string")),i=new Set;for(let o of n)if(!(typeof o.key!="string"||!r.has(o.key)||!Array.isArray(o.tasks)))for(let a of o.tasks)typeof a=="string"&&i.add(a);return i}s(LY,"tasksOfRequiresOneOf");function qN(e){if(typeof e!="object"||e===null)return!1;let{de:t,en:n}=e;return typeof t=="string"&&t.trim().length>0&&typeof n=="string"&&n.trim().length>0}s(qN,"isFilledBilingual");var MY=["blocks","gatesNode","locksEvidence","completableIf"];function qY(e,t){let n={de:`Task "${t.key}" (Knoten "${t.nodeId}")`,en:`Task "${t.key}" (node "${t.nodeId}")`},r=[];e.feedback!==!0&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${n.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${n.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;(e.kind!=="task"||i?.kind!=="freetext")&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackNeedsFreetext] ${n.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext ('result: { kind: "freetext" }'); erhalten ${e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}`}.`,en:`[workItems/feedbackNeedsFreetext] ${n.en} is a feedback task, so it closes with free text ('result: { kind: "freetext" }'); got ${e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}`}.`}));let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest","appointment"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(St(`${t.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${n.de} ist eine Feedback-Aufgabe; die Antwort kommt von einer Seite ohne weitere Daten und darf deshalb nicht von ${o.join(", ")} abh\xE4ngen.`,en:`[workItems/feedbackSteersProcess] ${n.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(qY,"feedbackTaskIssues");function KY(e,t){let n=[],r={de:`Task "${t.key}" (Knoten "${t.nodeId}")`,en:`Task "${t.key}" (node "${t.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!qN(i.skipLabel))&&n.push(St(`${t.base}.optional.skipLabel`,{de:`[workItems/optionalSkipLabel] ${r.de} ist optional, braucht daf\xFCr '{ skipLabel: { de, en } }' \u2014 die Worte des Knopfs, mit dem die zust\xE4ndige Person ohne Ergebnis abschlie\xDFt (\u201EKeine Einsch\xE4tzung abgeben"); erhalten ${JSON.stringify(i)}.`,en:`[workItems/optionalSkipLabel] ${r.en} is optional and needs '{ skipLabel: { de, en } }' for that \u2014 the words of the button the responsible person uses to finish without a result ("Give no assessment"); got ${JSON.stringify(i)}.`})),e.kind!=="task"&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalOnApproval] ${r.de} ist eine Freigabe \u2014 optional ist nur eine Aufgabe; eine Freigabe schlie\xDFt mit ihrem Urteil.`,en:`[workItems/optionalOnApproval] ${r.en} is an approval \u2014 only a task can be optional; an approval ends with its verdict.`}));let a=e.result;(a===void 0||typeof a.kind!="string"||!CI({kind:a.kind,writes:a.writes}))&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalNeedsProseResult] ${r.de} ist optional, schlie\xDFt aber ${a===void 0?"ohne Ergebnis":`mit einem ${String(a.kind)}-Ergebnis${a.writes!==void 0?" mit Wert":""}`} \u2014 optional ist nur eine Aufgabe mit Freitext, Empfehlung oder einer Auswahl ohne 'writes': einen Wert, den ein sp\xE4terer Schritt liest, g\xE4be es dann nie.`,en:`[workItems/optionalNeedsProseResult] ${r.en} is optional but ends ${a===void 0?"without a result":`with a ${String(a.kind)} result${a.writes!==void 0?" with a value":""}`} \u2014 only a task with free text, a recommendation or a choice without 'writes' can be optional: a value a later step reads would then never arrive.`}));let l=MY.filter(d=>e[d]!==void 0);return l.length>0&&n.push(St(`${t.base}.${l[0]}`,{de:`[workItems/optionalHolds] ${r.de} ist optional und tr\xE4gt ${l.map(d=>`'${d}'`).join(", ")} \u2014 auf eine optionale Aufgabe wartet nichts: sie h\xE4lt keinen Schritt zur\xFCck. Entweder optional oder zur\xFCckhaltend.`,en:`[workItems/optionalHolds] ${r.en} is optional and carries ${l.map(d=>`'${d}'`).join(", ")} \u2014 nothing waits for an optional task: it holds no step back. Either optional or holding back.`})),t.requiredByRule&&n.push(St(`${t.base}.optional`,{de:`[workItems/optionalInRequiresOneOf] ${r.de} ist optional, geh\xF6rt aber zu einer Aktion, die 'requiresOneOf' verlangt \u2014 \u201EKeine Einsch\xE4tzung abgeben" w\xFCrde die Regel erf\xFCllen, ohne dass etwas geschehen ist.`,en:`[workItems/optionalInRequiresOneOf] ${r.en} is optional but belongs to an action that 'requiresOneOf' requires \u2014 "Give no assessment" would satisfy the rule without anything having happened.`})),n}s(KY,"optionalTaskIssues");function St(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(St,"issue");function KN(e,t){let n=[],r=FY(e),i=new Set(na(e).map(o=>o.key));n.push(...FN(e,t));for(let o of e.nodes){let a=o,l=CN(a);n.push(...DN(a));let d=LY(a);n.push(...IN(a,e.nodes));for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=typeof c.key=="string"?c.key:"?",p=`nodes.${o.id}.tasks.${u}`,h=c.kind,w=c.result,k=c.blocks,y=typeof k?.node=="string"&&k.node!==o.id?k.node:void 0;if(typeof k?.templateKey=="string"){let R=typeof k.node=="string"?k.node:o.id,q=e.nodes.find(Y=>Y.id===R),J=(Array.isArray(q?.tasks)?q.tasks:[]).find(Y=>Y.key===k.templateKey)?.blocks;typeof J?.node=="string"&&J.node!==R&&n.push(St(`${p}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${u}" auf Knoten "${o.id}" h\xE4lt "${k.templateKey}" auf Knoten "${R}" zur\xFCck \u2014 das ist selbst eine knoten\xFCbergreifende Aufgabe, die ihren Knoten \xFCberlebt; zur\xFCckgehalten k\xF6nnte sie nach dessen Verlassen weder bearbeitet noch freigegeben werden. Nur Aufgaben, die an ihrem Knoten bleiben, und intrinsische Vorlagen sind Ziele.`,en:`[workItems/blocksCrossNodeTask] Task "${u}" on node "${o.id}" holds back "${k.templateKey}" on node "${R}" \u2014 that is itself a cross-node task that outlives its node; held back, it could be neither worked nor released after the node is left. Only tasks that stay on their node and intrinsic templates are targets.`}))}if(y!==void 0){let R=y;e.nodes.some(q=>q.id===R)&&!r(o.id).has(R)&&n.push(St(`${p}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${u}" auf Knoten "${o.id}" blockiert Knoten "${R}", der von hier aus nicht erreichbar ist \u2014 die Aufgabe entst\xFCnde erst, wenn ihr Ziel schon hinter dem Prozess liegt. Ziel ist derselbe Knoten oder ein sp\xE4terer.`,en:`[workItems/blocksTargetNotAfter] Task "${u}" on node "${o.id}" blocks node "${R}", which cannot be reached from here \u2014 the task would only be created when its target is already behind the process. The target is the same node or a later one.`})),(w===void 0||!_i(w.kind))&&n.push(St(`${p}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${u}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${R}"), hat aber kein 'result' \u2014 eine knoten\xFCbergreifende Aufgabe \xFCberlebt ihren Knoten und wird \xFCber ihr Ergebnis abgeschlossen (Freitext, Empfehlung oder Auswahl).`,en:`[workItems/crossNodeBlocksNeedsResult] Task "${u}" on node "${o.id}" blocks another node ("${R}") but has no 'result' \u2014 a cross-node task outlives its node and is completed through its result (free text, recommendation or choice).`})),l.has(u)&&n.push(St(`${p}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${u}" geh\xF6rt zu einer optionalen Aktion (spawnTasks) auf Knoten "${o.id}" und darf keinen anderen Knoten blockieren \u2014 ihre Zeilen sind die Runde der Aktion.`,en:`[optionalAction/crossNodeBlocks] Task "${u}" belongs to an optional action (spawnTasks) on node "${o.id}" and must not block another node \u2014 its rows are the round of the action.`}))}for(let R of EN(String(h),w,{channelKeys:i,...t?.billingItemKeys!==void 0?{billingItemKeys:t.billingItemKeys}:{},...t?.offerProgram!==void 0?{offerProgram:t.offerProgram}:{}}))n.push(St(`${p}.${R.field}`,{de:`${R.code} ${R.message.de} (Task "${u}" auf Knoten "${o.id}").`,en:`${R.code} ${R.message.en} (task "${u}" on node "${o.id}").`}));let v=c.when,A=s((R,q,_)=>{!xe(q)||ct(q)||n.push(St(R,{de:`[workItems/evidenceNotFormField] ${_} auf Task "${u}" (Knoten "${o.id}") nennt ${je(e,q,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${_} on task "${u}" (node "${o.id}") names ${je(e,q,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");v!==void 0?(A(`${p}.when`,v,"'when'"),c.onConditionReturn!=="respawn"&&c.onConditionReturn!=="stayClosed"&&n.push(St(`${p}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${u}" (Knoten "${o.id}") hat eine Bedingung, aber kein 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 was bei der R\xFCckkehr der Bedingung geschieht, muss entschieden sein.`,en:`[workItems/whenNeedsOnConditionReturn] Task "${u}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):c.onConditionReturn!==void 0&&n.push(St(`${p}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${u}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${u}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let E=c.reads;if(E!==void 0)if(!Array.isArray(E))n.push(St(`${p}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${u}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${u}" (node "${o.id}") must be a list of field addresses.`}));else for(let[R,q]of E.entries())A(`${p}.reads.${R}`,q,"'reads'");let I=c.locksEvidence,C=s((R,q)=>n.push(St(`${p}.locksEvidence`,{de:`[workItems/${R}] Task "${u}" (Knoten "${o.id}") ${q.de}`,en:`[workItems/${R}] Task "${u}" (node "${o.id}") ${q.en}`})),"lockIssue");I!==void 0&&I!==!0&&C("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(I)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(I)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),I===!0&&(E===void 0&&v===void 0&&C("locksEvidenceWithoutEvidence",{de:"sperrt seine Belege, hat aber weder 'reads' noch 'when' \u2014 es gibt nichts, worauf die Entscheidung beruht.",en:"locks its evidence but has neither 'reads' nor 'when' \u2014 there is nothing the decision rests on."}),(w===void 0||!_i(w.kind))&&C("locksEvidenceNeedsRecordedResult",{de:"sperrt seine Belege, schlie\xDFt aber nicht mit einem erfassten Ergebnis (Freitext, Empfehlung, Auswahl) \u2014 nur eine Entscheidung, die das Team wieder\xF6ffnen kann, darf Belege sperren (ein Termin bleibt gebucht).",en:"locks its evidence but does not end with a recorded result (free text, recommendation, choice) \u2014 only a decision the team can reopen may lock evidence (an appointment stays booked)."}),l.has(u)&&C("locksEvidenceOnOptionalAction",{de:"geh\xF6rt zu einer optionalen Aktion (spawnTasks) \u2014 ihre Zeilen sind die Runde der Aktion, wieder\xF6ffnen l\xE4sst sie sich nicht; Belege sperrt nur eine Knotenaufgabe.",en:"belongs to an optional action (spawnTasks) \u2014 its rows are the round of the action and cannot be reopened; only a node task locks evidence."})),n.push(...PN({graph:e,node:a,task:c,onTrigger:l,specCtx:t}));let $=Object.keys(c).filter(R=>!Object.hasOwn(Aw,R));$.length>0&&n.push(St(`${p}.${$[0]}`,{de:`[workItems/unknownKey] Task "${u}" (Knoten "${o.id}") tr\xE4gt ${$.map(R=>`'${R}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(Aw).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${u}" (node "${o.id}") carries ${$.map(R=>`'${R}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(Aw).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let b=c.description;b!==void 0&&!qN(b)&&n.push(St(`${p}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${u}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(b)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${u}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(b)}.`})),c.feedback!==void 0&&n.push(...qY(c,{key:u,nodeId:o.id,base:p})),c.optional!==void 0&&n.push(...KY(c,{key:u,nodeId:o.id,base:p,requiredByRule:d.has(u)}))}}return n}s(KN,"checkNodeTasks");function jN(e){let t=e.indexOf(":"),n=t===-1?"":e.slice(0,t),r=t===-1?"":e.slice(t+1).trim();if(n==="artifact"&&r.length>0)return{kind:n,key:r};let i=mo(r);return(n==="field"||n==="document")&&i!==null?{kind:n,address:i}:ae("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel>, field:$node.<Formular>.admission.<Feld> oder document:$node.<Knoten>.document.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key>, field:$node.<form>.admission.<field> or document:$node.<node>.document.`})}s(jN,"parseTaskDocumentRef");function Ew(e){return e.kind==="artifact"?`artifact:${e.key}`:`${e.kind}:${pe(e.address)}`}s(Ew,"taskDocumentId");function si(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(si,"issue");function VN(e){return Array.isArray(e.tasks)?e.tasks:[]}s(VN,"tasksOf");function jY(e){let t=new Map;for(let n of e){let{id:r,artifacts:i}=n;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&t.set(o.key,[...t.get(o.key)??[],{nodeId:r,slot:o}])}return t}s(jY,"artifactSlotDeclarations");function VY(e){return e.flatMap(t=>{let{id:n,artifacts:r}=t;return(Array.isArray(r)?r:[]).filter(i=>!Ff(i?.type)).map(i=>({nodeId:String(n),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(VY,"unknownArtifactSlotTypes");function BN(e){let t=[];for(let{nodeId:n,slotKey:r,type:i}of VY(e.nodes))t.push(si(`nodes.${n}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${n}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${Ws.join(", ")}.`,en:`[artifact/unknownType] Node "${n}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${Ws.join(", ")}.`}));for(let[n,r]of jY(e.nodes))for(let i of r.slice(1))t.push(si(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${n}", den schon "${r[0].nodeId}" deklariert \u2014 jeder Slot-Schl\xFCssel geh\xF6rt genau einem Knoten.`,en:`[governedDocument/slotKeyTaken] Node "${i.nodeId}" declares the document slot "${n}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return t}s(BN,"checkArtifactSlotKeys");function UN(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let n of e){let r=typeof n=="object"&&n!==null?n:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)t.push({kind:"artifact",key:r.key});else if((r.kind==="field"||r.kind==="document")&&i==="address,kind")t.push({kind:r.kind,address:r.address});else return null}return t}s(UN,"authoredRefs");function BY(e){return e.scope==="node"&&(e.key===bl||e.key===Cs||e.key===Ps)&&e.path===void 0}s(BY,"isDocumentAddress");function GN(e){let t=[];for(let n of e.nodes)for(let r of VN(n)){if(r.documents===void 0)continue;let i=typeof r.key=="string"?r.key:"?",o=`nodes.${n.id}.tasks.${i}.documents`,a={de:`Task "${i}" (Knoten "${n.id}")`,en:`Task "${i}" (node "${n.id}")`},l=UN(r.documents);if(l===null){t.push(si(o,{de:`[workItems/documentsInvalid] 'documents' auf ${a.de} muss eine nicht leere Liste von { kind: 'artifact', key } (eigener Slot), { kind: 'field', address } (Dateifeld eines Formulars) oder { kind: 'document', address } (Dokument eines anderen Knotens) sein, erhalten ${JSON.stringify(r.documents)}.`,en:`[workItems/documentsInvalid] 'documents' on ${a.en} must be a non-empty list of { kind: 'artifact', key } (own slot), { kind: 'field', address } (file field of a form) or { kind: 'document', address } (document of another node), got ${JSON.stringify(r.documents)}.`}));continue}let d=new Set;for(let c of l){if(c.kind!=="artifact"&&!xe(c.address))continue;let u=c.kind==="artifact"?Ew(c):Ew({kind:c.kind,address:c.address});d.has(u)&&t.push(si(o,{de:`[workItems/documentsDuplicate] ${a.de} verweist zweimal auf ${u}.`,en:`[workItems/documentsDuplicate] ${a.en} refers to ${u} twice.`})),d.add(u),c.kind==="artifact"&&!nO(n,c.key)&&t.push(si(o,{de:`[workItems/documentsUnknownArtifact] ${a.de} verweist auf das Dokument "${c.key}", aber der Knoten deklariert keinen solchen Slot \u2014 das Dokument eines anderen Knotens ist { kind: 'document', address: $node.<knoten>.document }.`,en:`[workItems/documentsUnknownArtifact] ${a.en} refers to the document "${c.key}", but the node declares no such slot \u2014 the document of another node is { kind: 'document', address: $node.<node>.document }.`})),c.kind==="field"&&!ct(c.address)&&t.push(si(o,{de:`[workItems/documentsInvalid] ${a.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,c.address,"de")}.`,en:`[workItems/documentsInvalid] ${a.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,c.address,"en")}.`})),c.kind==="document"&&!BY(c.address)&&t.push(si(o,{de:`[workItems/documentsInvalid] ${a.de}: ein Dokument eines anderen Knotens ist dessen ganzes Dokument ($node.<knoten>.document), nicht ${pe(c.address)}.`,en:`[workItems/documentsInvalid] ${a.en}: a document of another node is that node's whole document ($node.<node>.document), not ${pe(c.address)}.`}))}}return t}s(GN,"checkTaskDocuments");function zN(e,t){let n=[];for(let r of e.nodes)for(let i of VN(r)){let o=UN(i.documents);if(o===null)continue;let a=typeof i.key=="string"?i.key:"?",l=`nodes.${r.id}.tasks.${a}.documents`;for(let d of o){if(d.kind!=="field"||!ct(d.address))continue;let c=ni(t,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Vs("taskDocument",js(c));if(p==="repeated"){n.push(si(l,{de:`[workItems/documentsUnknownField] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Dokument der Anmeldung.`,en:`[workItems/documentsUnknownField] Task "${a}" (node "${r.id}") refers to the field ${u.en} \u2014 a field in a repeated group is not a single document of the application.`}));continue}p==="notDocument"&&n.push(si(l,{de:`[workItems/documentsNotDocument] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u.de}, das keine Datei enth\xE4lt \u2014 nur Datei-Felder (docRef) sind Dokumente.`,en:`[workItems/documentsNotDocument] Task "${a}" (node "${r.id}") refers to the field ${u.en}, which holds no file \u2014 only file fields (docRef) are documents.`}))}}return n}s(zN,"checkTaskDocumentFields");var Tw=["form","documents"],UY=/^[a-z][a-zA-Z0-9_-]*$/;function GY(e){let t=new Map,n=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])t.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){t.set(i.key,"other");for(let o of i.itemTemplate)t.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(GY,"fieldPlaces");function WN(e,t,n){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!UY.test(o)){r.push({severity:"error",path:`${n(a)}.key`,code:"view.invalid-key",message:{de:`${t.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${t.en}: '${String(o)}' is no valid key (a lower-case letter first, then letters, digits, - or _).`}});return}i.has(o)&&r.push({severity:"error",path:`${n(a)}.key`,code:"view.duplicate-key",message:{de:`${t.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${t.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(WN,"keyIssues");function zY(e,t,n){return e==="document"?null:e===void 0?{severity:"error",path:n,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${t}'.`,en:`View: the form has no field '${t}'.`}}:e==="row"?{severity:"error",path:n,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${t}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${t}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:n,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${t}' enth\xE4lt keine Datei.`,en:`View: the field '${t}' holds no file.`}}}s(zY,"fieldIssue");function WY(e,t,n){let r=[];Tw.includes(e.key)&&r.push({severity:"error",path:`${t}.key`,code:"view.reserved-key",message:{de:`Der Ansichtsschl\xFCssel '${e.key}' ist f\xFCr die Standardansicht reserviert.`,en:`The view key '${e.key}' is reserved for the standard view.`}});let i=e.groups;i.length===0&&r.push({severity:"error",path:`${t}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...WN(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${t}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${t}.groups[${l}]`,c=a.fields;c.length===0&&r.push({severity:"error",path:`${d}.fields`,code:"view.empty",message:{de:`Gruppe '${a.key}' der Ansicht '${e.key}' hat keine Felder.`,en:`Group '${a.key}' of view '${e.key}' has no fields.`}}),c.forEach((u,p)=>{let h=`${d}.fields[${p}]`,w=zY(n.get(u),u,h);w!==null&&r.push(w),o.has(u)&&r.push({severity:"error",path:h,code:"view.field-twice",message:{de:`Ansicht '${e.key}': Das Feld '${u}' steht mehrfach; eine Datei hat einen Platz.`,en:`View '${e.key}': the field '${u}' is listed more than once; a file has one place.`}}),o.add(u)})}),r}s(WY,"viewIssues");function YY(e){if(!Array.isArray(e))return"views";for(let[t,n]of e.entries()){let r=n?.groups;if(!Array.isArray(r))return`views[${t}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${t}].groups[${i}].fields`}}return null}s(YY,"malformedAt");function YN(e){let t=e.views;if(t===void 0)return[];let n=YY(t);if(n!==null)return[{severity:"error",path:n,code:"view.malformed",message:{de:`${n} hat nicht die Form einer Ansicht: views ist eine Liste von { key, label, groups }, groups eine Liste von { key, label, fields }, fields eine Liste von Feldschl\xFCsseln.`,en:`${n} is not shaped like a view: views is a list of { key, label, groups }, groups a list of { key, label, fields }, fields a list of field keys.`}}];let r=GY(e);return[...WN(t.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...t.flatMap((i,o)=>WY(i,`views[${o}]`,r))]}s(YN,"formViewIssues");function rp(e,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:"error"}}s(rp,"issue");function HN(e,t,n,r){let i=e;if(i===null||typeof i!="object"||typeof i.form!="string"||typeof i.key!="string")return[rp(t,{de:`[workItems/formViewInvalid] 'formView' auf ${n.de} muss { form: <Formularknoten>, key: <Ansicht> } sein.`,en:`[workItems/formViewInvalid] 'formView' on ${n.en} must be { form: <form node>, key: <view> }.`})];let o=r?.formViewKeysByFormNode;if(o===void 0)return[];let a=o.get(i.form);return a===void 0?[rp(t,{de:`[workItems/formViewUnknownForm] ${n.de} nennt das Formular "${i.form}", aber kein Formularknoten hei\xDFt so.`,en:`[workItems/formViewUnknownForm] ${n.en} names the form "${i.form}", but no form node has that id.`})]:a.has(i.key)||Tw.includes(i.key)?[]:[rp(t,{de:`[workItems/formViewUnknown] ${n.de} nennt die Ansicht "${i.key}", aber das Formular "${i.form}" hat keine solche Ansicht.`,en:`[workItems/formViewUnknown] ${n.en} names the view "${i.key}", but the form "${i.form}" has no such view.`})]}s(HN,"viewIssues");function JN(e,t){let n=[];for(let r of e.nodes){if(r.formView!==void 0){let i={de:`Knoten "${r.id}"`,en:`node "${r.id}"`};r.type!=="decision"?n.push(rp(`nodes.${r.id}.formView`,{de:`[workItems/formViewInvalid] ${i.de}: 'formView' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[workItems/formViewInvalid] ${i.en}: 'formView' on a node applies to a decision only; a task carries its own.`})):n.push(...HN(r.formView,`nodes.${r.id}.formView`,i,t))}for(let i of Array.isArray(r.tasks)?r.tasks:[]){if(i.formView===void 0)continue;let o=String(i.key);n.push(...HN(i.formView,`nodes.${r.id}.tasks.${o}.formView`,{de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},t))}}return n}s(JN,"checkTaskFormViews");var Pn="traeger",QN={de:"Tr\xE4ger",en:"Provider"};function ia(e){let t=e.inputs?.[Pn];return t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0?t.value:null}s(ia,"traegerKeyOfNode");var ip={name:"input.traeger.name",address:"input.traeger.anschrift"},Lhe=Object.values(ip);var ZN="governedDocument",_o="prepareDocument",ql="prepareDocument:revision",Fr="releaseApproval",No="documentResponse",oa="coverLetterResponse",op="confirmCoverLetter",sp="requestCoverLetterRevision",sa="coverLetterConfirmation",Lr="responseCheck",ap="returnSigned";var XN="requestApproval";var eC="issueDocument",tC="correctInPlace",nC="rescindAndReissue",lp="requestChange";var aa="releaseArtifact",cn="signingRecovery",dp="resendESignature",Co="switchToPaper";var $w=new Set([_o,ql]),rC=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],cp=["upload","resolver","template","none"],Po=1,Do=366,ai="responseDueInDays";function Fo(e){let t=e.inputs?.[sa];return t?.kind==="literal"&&t.value===!0}s(Fo,"coverLetterConfirmationOf");function Kl(e){let t=e.inputs?.[ai];return t?.kind==="literal"&&jl(t.value)?t.value:void 0}s(Kl,"responseDueInDaysForVocabulary");function jl(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Po&&e<=Do}s(jl,"isValidResponseDueInDays");var up=["generatedAt","responseDueInDays","countersignature"],Lo=["release","none"],fp=["confirm","signedUpload","signedUploadChecked","eSignature"];var HY={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},iC={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},oC={...iC,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},JY={...oC,kind:"eSignature",issuesBy:"provider"},li={confirm:HY,signedUpload:iC,signedUploadChecked:oC,eSignature:JY};function di(e){let t=e.responseStrategy;if(typeof t=="string"&&t in li)return li[t];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(t)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(di,"responseStrategyOf");function pp(e){if(e.type!==ZN||e.production!=="resolver")return!1;let t=e.responseStrategy;return typeof t=="string"&&t in li?li[t].acceptEvent==="contractEvent":!1}s(pp,"isFamilySignedContractNode");function da(e){return e.label}s(da,"governedDocTitle");function Rw(e){return e.approval==="release"?XN:eC}s(Rw,"submitActionId");function sC(e,t,n){return{key:t,recipient:"internal",title:n,unlocks:[Rw(e)],gatesNode:!0,advancesNode:!0}}s(sC,"producerTemplate");function QY(e){return e.titles?.respond??e.label}s(QY,"responseTitle");var la={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Iw(e){let t=di(e),n=[];if(e.production!=="none"&&n.push(sC(e,_o,e.titles?.prepare??la),sC(e,ql,e.titles?.revise??la)),e.approval==="release"&&n.push({key:Fr,recipient:"internal",title:e.titles?.approve??la,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:No,recipient:"external",title:QY(e),unlocks:t.producesResponseArtifact?[t.checksReturn?ap:t.acceptOutcomeId,t.declineOutcomeId,lp]:[t.acceptOutcomeId,t.declineOutcomeId],advancesNode:!0,...Kl(e)!==void 0?{dueInDays:Kl(e)}:{}}),Fo(e)){let r=da(e);n.push({key:oa,recipient:"external",title:{de:`${r.de}: Angebot best\xE4tigen`,en:`${r.en}: confirm offer`},unlocks:[op,sp,t.declineOutcomeId],advancesNode:!0,...Kl(e)!==void 0?{dueInDays:Kl(e)}:{}})}if(t.checksReturn&&n.push({key:Lr,recipient:"internal",title:e.titles?.check??la,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),t.issuesBy==="provider"){let r=da(e);n.push({key:cn,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[dp,Co],gatesNode:!1,advancesNode:!1})}return n}s(Iw,"governedDocIntrinsicTemplates");function ZY(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let t=e.artifacts??[];t.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${t.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let n=t[0];return(typeof n.key!="string"||n.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),n}s(ZY,"governedDocSlot");function mp(e){return ZY(e).key}s(mp,"governedDocSlotKey");var Xn="processFooter";var hp="countersign",Ow="countersign",aC="countersigned",lC="countersigning",dC="countersigned";var cC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},Vl=["scan","eSignature"],gp="service_provider:1",uC=["countersigning","awaitingSignature","signatureStalled","done"],fC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function pC(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(pC,"traegerSignatoryMissingReason");function er(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(er,"issue");function yp(e,t){return e.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&xe(r)&&r.scope==="node"&&r.owner===t})}s(yp,"countersignersOf");function Bl(e){return e.signing==="eSignature"}s(Bl,"isElectronic");function XY(e,t){if(t===void 0||t.sendable||!Bl(e))return[];let n=e.label?.de??e.id,r=e.label?.en||e.id;return[er(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${n}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${t.reason.en}`})]}s(XY,"countersignProviderIssues");function eH(e,t,n){if(n.scope!=="node")return[];let r=e.nodes.find(o=>o.id===n.owner);if(r===void 0)return[];let i=[];return pp(r)||i.push("sourceNotCheckedContract"),yp(e,r.id).some(o=>o.id!==t)&&i.push("twice"),i}s(eH,"countersignContractRefusals");function mC(e){let t=e.inputs?.dueInDays;return t?.kind==="literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&t.value>=1?t.value:void 0}s(mC,"validDueInDays");function tH(e,t,n){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!Vl.includes(o))return[er(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[cn];if(!Bl(e))return a===void 0?[]:[er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(er(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...nH(e,t,n),...rH(e,t,n),...XY(e,n?.signingProvider)),l}s(tH,"signingIssues");function gC(e,t){let n=e.contract;if(!(!xe(n)||n.scope!=="node"))return t.nodes.find(r=>r.id===n.owner)}s(gC,"contractNodeOf");function nH(e,t,n){let r=gC(e,t),i=r===void 0?null:ia(r),o=i===null?void 0:n?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[er(e,"signing",pC(o.name))]}s(nH,"traegerSignatoryIssues");function rH(e,t,n){let r=gC(e,t);if(r===void 0)return[];let i=n?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(gp)||l.push(er(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${gp}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${gp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(rH,"traegerAnchorIssues");var _w=100;async function iH(e,t){let n=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",t.applicationId).eq("context.anchor.nodeId",t.node.id)).take(_w+1);n.length>_w&&F(`countersign node "${t.node.id}" of ${t.applicationId} holds more than ${_w} rows`);let r=n.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===cn)?"signatureStalled":r.some(o=>i(o)===hp)?"countersigning":Bl(t.node)?"awaitingSignature":"done"}s(iH,"countersignCurrentState");var hC={[lC]:{label:ne("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:ne("Gegenzeichnung","Countersignature"),scope:"node"},external:Ze(ne("Vertrag unterschrieben","Contract signed"),"blue",ne("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),ne("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},yC={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:aC,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:hC,progressEvents:Ft(hC),notificationEvents:s(()=>[{id:dC,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:Ow,kind:"internal",label:cC,surface:Xn,availableIn:["countersigning"]},...Bl(e)?[{id:Co,kind:"internal",surface:Xn,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:hp,recipient:"internal",title:e.titles?.countersign??la,unlocks:[Ow],advancesNode:!0,...mC(e)!==void 0?{dueInDays:mC(e)}:{}},...Bl(e)?[{key:cn,recipient:"internal",title:fC,unlocks:[Co],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:uC,currentState:iH,validate:s((e,t,n)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[hp];(typeof a!="string"||a.length===0)&&r.push(er(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Ti(e.titles?.countersign)||r.push(er(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(er(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...tH(e,t,n));let d=e.contract;if(!xe(d))return r;let c=eH(t,e.id,d);if(c.length===0)return r;let u=t.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(er(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let p=yp(t,u.id).filter(h=>h.id!==e.id);r.push(er(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${p.map(h=>`"${h.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${p.map(h=>`"${h.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};function oH(e){return pp(e)?ia(e):null}s(oH,"traegerSignerOf");var sH=s(e=>e.type==="end"&&To(e)==="approved","isApprovedEnd");function wC(e){let t=[];for(let n of e.nodes){let r=oH(n);if(r===null)continue;let i=yp(e,n.id).map(u=>u.id),o=DO(e,n.id,new Set(i),sH);if(o===null)continue;let a=n.label?.de||n.id,l=n.label?.en||n.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${n.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${n.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${n.id}) erzeugt einen Vertrag, den der Tr\xE4ger \u201E${r}\u201C mitunterschreibt, aber keine Gegenzeichnung nennt ihn \u2014 der Vertrag w\xFCrde nie unterschrieben und nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${n.id}) generates a contract the legal entity "${r}" co-signs, but no countersignature names it \u2014 the contract would never be signed and never billed. ${d.en}`}:{de:`[countersign/missingForContract] \u201E${a}\u201C (${n.id}): ein Weg erreicht das Ende \u201E${o}\u201C (Ergebnis approved), ohne durch die Gegenzeichnung ${i.map(u=>`\u201E${u}\u201C`).join(", ")} zu laufen \u2014 dort bliebe der Vertrag ohne Unterschrift des Tr\xE4gers \u201E${r}\u201C und w\xFCrde nie abgerechnet. ${d.de}`,en:`[countersign/missingForContract] "${l}" (${n.id}): a path reaches the end "${o}" (outcome approved) without passing the countersignature ${i.map(u=>`"${u}"`).join(", ")} \u2014 there the contract would lack the signature of the legal entity "${r}" and never be billed. ${d.en}`};t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}`,reason:c,severity:"error"})}return t}s(wC,"checkCountersignCoverage");function aH(e){let t="error",n=new Map;for(let a of Zn(e.nodes)){let l=n.get(a.source)??[];l.push({id:a.id,target:a.target}),n.set(a.source,l)}let r=[],i=new Set,o=Jf(e.nodes.map(a=>a.id),a=>(n.get(a)??[]).map(({id:l,target:d})=>({target:d,edge:l})));for(let a of o)i.has(a.edge)||(i.add(a.edge),r.push({layer:"GRAPH",kind:"cycle",path:`edge.${a.edge}`,reason:{de:`Zyklus \xFCber Kante ${a.source} \u2192 ${a.target}`,en:`Cycle through edge ${a.source} \u2192 ${a.target}`},severity:t}));return r}s(aH,"checkAcyclic");function lH(e){let t=[],n=new Set(e.nodes.map(i=>i.id)),r="error";for(let i of e.nodes){let o=i.next;if(o)for(let[a,l]of Object.entries(o))n.has(l.to)||t.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.next.${a}`,reason:{de:`${i.label.de}: next.${a} verweist auf nicht-existenten Knoten '${l.to}'`,en:`${i.label.en}: next.${a} points to a node that does not exist: '${l.to}'`},severity:"error"});if(i.type!=="end"&&!(!i.outcomes||i.outcomes.length===0))for(let a of i.outcomes)(!o||!(a.id in o))&&t.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.outcome.${a.id}`,reason:{de:`${i.label.de}: Outcome '${a.label.de}' fehlt im next-Mapping`,en:`${i.label.en}: outcome '${a.label.en}' is missing from the next mapping`},severity:r})}return t}s(lH,"checkNextTargets");function dH(e){let t=[];for(let n of e.nodes){let r=n.next;if(!r)continue;let i=zy(n),o=new Set(i?i.map(a=>a.id):[Ys]);for(let a of Object.keys(r))o.has(a)||t.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${n.id}.next.${a}`,reason:{de:`${n.label.de}: next-Schl\xFCssel '${a}' ist kein g\xFCltiges Outcome dieses Knotens (erlaubt: ${[...o].join(", ")}) \u2014 die Kante w\xFCrde im Editor verschwinden`,en:`${n.label.en}: next key '${a}' is not a valid outcome of this node (allowed: ${[...o].join(", ")}) \u2014 the edge would disappear in the editor`},severity:"error"})}return t}s(dH,"checkNextOutcomesKnown");function cH(e){let t=[],n=new Set(Zn(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!n.has(o.id));return r.length===0?t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:`Mehrere Start-Knoten (${r.map(o=>o.label.de).join(", ")})`,en:`Multiple start nodes (${r.map(o=>o.label.en).join(", ")})`},severity:"warning"}),e.nodes.filter(o=>o.type==="end").length===0&&t.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),t}s(cH,"checkStartEnd");function uH(e){let t=new Map;for(let r of Zn(e.nodes))t.set(r.source,(t.get(r.source)??0)+1);let n=[];for(let r of e.nodes)r.type!=="end"&&(t.get(r.id)??0)===0&&n.push({layer:"GRAPH",kind:"startEnd",path:`node.${r.id}`,reason:{de:`${r.label.de}: keine ausgehende Kante`,en:`${r.label.en}: no outgoing edge`},severity:"warning"});return n}s(uH,"checkNoOutgoingEdge");function fH(e){return e.nodes.filter(t=>!Qg(t.id)).map(t=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${t.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${mr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${t.id}": a node id is an identifier without a dot (${mr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(fH,"checkNodeIdFormat");function pH(e){let t=new Set(e.nodes.map(r=>r.id)),n=[];for(let r of Zn(e.nodes))t.has(r.source)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Quelle '${r.source}' nicht gefunden`,en:`Edge ${r.id}: source '${r.source}' not found`},severity:"error"}),t.has(r.target)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:{de:`Kante ${r.id}: Ziel '${r.target}' nicht gefunden`,en:`Edge ${r.id}: target '${r.target}' not found`},severity:"error"});return n}s(pH,"checkEdgeEndpoints");var mH=new Set(["countersignature"]);function hH(e){let t=[],n=s((o,a)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:{de:`[graph/retiredField] ${a.de}`,en:`[graph/retiredField] ${a.en}`},severity:"error"})},"retired"),r={de:"Preise rechnet der Vertragsgenerator (`prices`), nicht der Workflow \u2014 binde Rang und Reduktion an seine Eing\xE4nge.",en:"Prices are computed by the contract generator (`prices`), not the workflow \u2014 bind rank and reduction to its inputs."},i=e;"pricingRules"in i&&n("pricingRules",r);for(let[o,a]of(Array.isArray(i.processStore)?i.processStore:[]).entries())for(let l of["derive","absentValue"])a!==null&&typeof a=="object"&&l in a&&n(`processStore.${o}.${l}`,r);for(let o of e.nodes)for(let a of o.tasks??[]){let l=a.result;l!==null&&typeof l=="object"&&"prices"in l&&n(`nodes.${o.id}.tasks.${a.key}.result.prices`,r)}for(let o of e.nodes){let a=o,l={de:`Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id})`,en:`Node "${_e(e,o.id,"en")}" (${o.id})`};for(let[c,u]of Object.entries(a.next??{}))u!==null&&typeof u=="object"&&"emits"in u&&n(`nodes.${o.id}.next.${c}.emits`,{de:`${l.de}: \`next.${c}.emits\` gibt es nicht mehr \u2014 ein Ausgang routet nur; ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`next.${c}.emits\` no longer exists \u2014 an outcome only routes; a node reads data through addresses in its own fields.`});for(let c of Array.isArray(a.outcomes)?a.outcomes:[])c!==null&&typeof c=="object"&&"emits"in c&&n(`nodes.${o.id}.outcomes.${String(c.id)}.emits`,{de:`${l.de}: \`emits\` am Ausgang "${String(c.id)}" gibt es nicht mehr \u2014 ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`,en:`${l.en}: \`emits\` on the outcome "${String(c.id)}" no longer exists \u2014 a node reads data through addresses in its own fields.`});"targetFormNodeId"in a&&n(`nodes.${o.id}.targetFormNodeId`,{de:`${l.de}: \`targetFormNodeId\` gibt es nicht mehr \u2014 welches Formular freigeschaltet wird, sagt die Adresse, an die der Eingang \`inputs.target\` gebunden ist ($node.<formular>.admission).`,en:`${l.en}: \`targetFormNodeId\` no longer exists \u2014 the address the input \`inputs.target\` is bound to says which form is unlocked ($node.<form>.admission).`}),"wires"in a&&n(`nodes.${o.id}.wires`,{de:`${l.de}: Datenkanten (\`wires\`) gibt es nicht mehr \u2014 jedes Feld, das Daten eines anderen Knotens liest, tr\xE4gt selbst die volle Adresse ($node.\u2026, $task.\u2026, $env.\u2026).`,en:`${l.en}: data edges (\`wires\`) no longer exist \u2014 every field that reads data of another node carries the full address itself ($node.\u2026, $task.\u2026, $env.\u2026).`});for(let[c,u]of Object.entries(a.inputs??{}))u!==null&&typeof u=="object"&&u.kind==="binding"&&"path"in u&&n(`nodes.${o.id}.inputs.${c}.path`,{de:`${l.de}: Der Eingang \u201E${c}\u201C ist \xFCber einen Pfad (\`path\`) gebunden \u2014 eine Bindung tr\xE4gt die volle Adresse (\`address\`) dessen, was sie liest.`,en:`${l.en}: The input "${c}" is bound through a path (\`path\`) \u2014 a binding carries the full address (\`address\`) of what it reads.`});o.type==="governedDocument"&&"resolver"in a&&n(`nodes.${o.id}.resolver`,{de:`${l.de}: \`resolver\` gibt es nicht mehr \u2014 der Generator ist der Eingang \`inputs.contractGenerator\` ({ kind, key }), seine Parameter stempelt die Plattform (\`generatorStamp\`), ein im Cockpit erg\xE4nzter Parameter ist sein Eingang \`{ kind: "cockpit" }\`.`,en:`${l.en}: \`resolver\` no longer exists \u2014 the generator is the input \`inputs.contractGenerator\` ({ kind, key }), the platform stamps its parameters (\`generatorStamp\`), a parameter completed in the cockpit is its input \`{ kind: "cockpit" }\`.`});let d=a.template;if(o.type==="governedDocument"&&d!==null&&typeof d=="object")for(let c of["key","cockpitFields"])c in d&&n(`nodes.${o.id}.template.${c}`,{de:`${l.de}: \`template.${c}\` gibt es nicht mehr \u2014 ${c==="key"?"die Vorlage ist der Eingang `inputs.documentTemplate`":'ein im Cockpit erg\xE4nzter Parameter ist sein Eingang `{ kind: "cockpit" }`'}.`,en:`${l.en}: \`template.${c}\` no longer exists \u2014 ${c==="key"?"the template is the input `inputs.documentTemplate`":'a parameter completed in the cockpit is its input `{ kind: "cockpit" }`'}.`});if(o.type==="setFlag")for(let c of["target","flagKey","value"])c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es am setFlag-Knoten nicht mehr \u2014 Formular, Merkmal und Wert sind die Eing\xE4nge \`inputs.target\` (gebunden an die Adresse $node.<formular>.admission), \`inputs.flagKey\` und \`inputs.value\` (feste Werte).`,en:`${l.en}: \`${c}\` no longer exists on a setFlag node \u2014 form, flag and value are the inputs \`inputs.target\` (bound to the address $node.<form>.admission), \`inputs.flagKey\` and \`inputs.value\` (literals).`});for(let c of Object.keys(Oy[o.type]??{}))c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es als Knoteneigenschaft nicht mehr \u2014 es ist der Eingang \`inputs.${c}\` (ein fester Wert im Parameter-Bereich).`,en:`${l.en}: \`${c}\` no longer exists as a node property \u2014 it is the input \`inputs.${c}\` (a fixed value among the parameters).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.assign;u===null||typeof u!="object"||!("userId"in u)||n(`nodes.${o.id}.tasks.${String(c.key)}.assign.userId`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${String(c.key)}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`})}for(let c of _y[o.type]??[])c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: \`${c}\` gibt es nicht mehr \u2014 dieser Knotentyp liest es nicht.`,en:`${l.en}: \`${c}\` no longer exists \u2014 this node type does not read it.`});for(let[c,u]of Object.entries(vO[o.type]??{}))c in a&&n(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&n(`nodes.${o.id}.adoptForm`,{de:`${l.de}: \`adoptForm: true\` gibt es nicht mehr \u2014 \`adoptForm\` ist die Adresse des \xFCbernommenen Formulars ($node.<anlegender Formularknoten>.admission).`,en:`${l.en}: \`adoptForm: true\` no longer exists \u2014 \`adoptForm\` is the address of the adopted form ($node.<creating form node>.admission).`});for(let c of Array.isArray(a.tasks)?a.tasks:[]){let u=c?.result?.kind;typeof u=="string"&&mH.has(u)&&n(`nodes.${o.id}.tasks.${String(c.key)}.result`,{de:`Aufgabe "${String(c.key)}" an ${l.de}: das Ergebnis \u201E${u}" gibt es nicht mehr \u2014 die Gegenzeichnung ist der Knotentyp \u201EUnterschrift (intern)" (countersign).`,en:`Task "${String(c.key)}" on ${l.en}: the result "${u}" no longer exists \u2014 the countersignature is the node type "Signature (internal)" (countersign).`})}}return t}s(hH,"checkRetiredDataFields");function ca(e,t){return t?.wiring&&t.layout?{wiring:t.wiring,layout:t.layout}:null}s(ca,"resolveLayoutContext");function gH(e,t){let n=ca(e,t);if(!n)return e.nodes.some(o=>(Ye(o)?.progressEvents?.length??0)>0)?[{layer:"GRAPH",kind:"progressState",path:"graph.progressWiring",reason:{de:`Graph emittiert Progress-Events, aber (Layout, Wiring) konnte nicht aufgel\xF6st werden (Wiring ${t?.wiring?"vorhanden":"fehlt"}, Layout ${t?.layout?"vorhanden":"fehlt"}) \u2014 der Engine wirft beim Spiegeln zur Laufzeit. Der Workflow-Entwurf muss progressLayout und progressWiring tragen.`,en:`The graph emits progress events, but (layout, wiring) could not be resolved (wiring ${t?.wiring?"present":"missing"}, layout ${t?.layout?"present":"missing"}) \u2014 the engine throws at runtime when mirroring. The workflow draft must carry progressLayout and progressWiring.`},severity:"error"}]:[];let r=[];for(let i of e.nodes){let a=Ye(i)?.progressEvents;if(a)for(let l of a){let d=Bs(n.wiring,{id:i.id,type:i.type},l);if(!d){r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Progress-Event '${l}' ist im Wiring (Layout '${n.layout.id}') keinem (Bus, State) zugeordnet \u2014 der Engine wirft beim Spiegeln`,en:`${i.type} '${i.id}': progress event '${l}' is not mapped to any (bus, state) in the wiring (layout '${n.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=_f(n.layout,d.bus)}catch{r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf unbekannten Bus '${d.bus}' im Layout '${n.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${n.layout.id}'`},severity:"error"});continue}Tl(c,d.state)||r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:{de:`${i.type} '${i.id}': Event '${l}' verweist auf State '${d.state}', der nicht im Bus '${d.bus}' deklariert ist`,en:`${i.type} '${i.id}': event '${l}' points to state '${d.state}', which is not declared in bus '${d.bus}'`},severity:"error"})}}return r}s(gH,"checkProgressEventMappings");function yH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses){if(!i.boards||i.boards.length===0)continue;let o=new Set(i.unboarded??[]),a=new Set;for(let l of i.boards)for(let d of l.columns)for(let c of d.states)a.add(c),Tl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${l.id}.column.${d.id}.${c}`,reason:{de:`Board '${l.id}', Spalte '${d.id}' referenziert State '${c}', der nicht im Bus '${i.key}' deklariert ist`,en:`Board '${l.id}', column '${d.id}' references state '${c}', which is not declared in bus '${i.key}'`},severity:"error"});for(let l of i.states)a.has(l.id)||o.has(l.id)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${l.id}`,reason:{de:`State '${l.id}' (${l.label.de}) erscheint in keiner Board-Spalte und nicht in 'unboarded' \u2014 nicht darstellbar`,en:`State '${l.id}' (${l.label.en}) appears in no board column and not in 'unboarded' \u2014 it cannot be displayed`},severity:"error"})}return r}s(yH,"checkProgressBoardCoverage");function wH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of ze){let l=new Map;for(let d of o.columns){if(!Ti(d.label))continue;let c=d.label[a],u=c.trim().toLocaleLowerCase(a),p=l.get(u);if(p===void 0){l.set(u,d.id);continue}r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${o.id}.column.${d.id}.label.${a}`,reason:{de:`Board '${o.id}' hat zwei Spalten mit dem Label '${c}' (${a}) ('${p}' und '${d.id}') \u2014 f\xFCr Lesende nicht unterscheidbar. F\xFChre die Spalten zusammen (states beider in EINE Spalte) oder vergib unterschiedliche Labels.`,en:`Board '${o.id}' has two columns with the label '${c}' (${a}) ('${p}' and '${d.id}') \u2014 readers cannot tell them apart. Merge the columns (put the states of both into ONE column) or give them different labels.`},severity:"error"})}}return r}s(wH,"checkProgressBoardDistinctLabels");function kH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses)for(let o of i.states){let a=Nf(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`Terminal-State '${o.id}' hat keine Terminal-Semantik im Bus '${i.key}' \u2014 der Engine wirft beim Versiegeln`,en:`Terminal state '${o.id}' has no terminal semantics in bus '${i.key}' \u2014 the engine throws when sealing`},severity:"error"}),!o.terminal&&a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${o.id}.terminalSemantics`,reason:{de:`State '${o.id}' ist nicht terminal, hat aber Terminal-Semantik im Bus '${i.key}' \u2014 Inkonsistenz`,en:`State '${o.id}' is not terminal but has terminal semantics in bus '${i.key}' \u2014 inconsistent`},severity:"error"})}return r}s(kH,"checkProgressTerminalSemantics");function bH(e,t){let n=ca(e,t);if(!n)return[];let r=[];for(let i of n.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Tl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat.${a}`,reason:{de:`holdsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`holdsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let a of i.commitsSeat??[])Tl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat '${a}' ist nicht in holdsSeat \u2014 ein fest belegter Platz muss auch belegt sein`,en:`commitsSeat '${a}' is not in holdsSeat \u2014 a firmly committed seat must also be held`},severity:"error"}):r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:{de:`commitsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,en:`commitsSeat references '${a}', which is not a state in bus '${i.key}'`},severity:"error"});for(let[a,l]of Object.entries(i.terminalSemantics??{}))l.outcome==="approved"&&(o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat`,reason:{de:`Endzustand '${a}' schlie\xDFt den Prozess positiv ab (outcome 'approved'), steht aber nicht in holdsSeat \u2014 damit z\xE4hlt er als Absage und f\xE4llt aus dem Fortschrittsbalken. Nimm '${a}' in holdsSeat (und in commitsSeat, wenn der Platz damit wirklich belegt ist) auf.`,en:`Final state '${a}' ends the process positively (outcome 'approved'), but is not in holdsSeat \u2014 so it counts as a rejection and drops out of the progress bar. Add '${a}' to holdsSeat (and to commitsSeat, if the seat is really taken by it).`},severity:"error"}))}return r}s(bH,"checkProgressSeatStates");var wp={de:"Abhilfe: nach dem Formularknoten einen review-Knoten einf\xFCgen und dessen 'reviewing' auf diesen Zustand mappen",en:"Remedy: insert a review node after the form node and map its 'reviewing' to this state"};function vH(e){return e==="both"?{de:`${wp.de} \u2014 die Spalte ist auch der Schritt, den die Familie sieht; den Zustand in die Spalte des Nachfolgers zu legen, n\xE4hme ihr diesen Schritt.`,en:`${wp.en} \u2014 the column is also the step the family sees; moving the state into the successor's column would take that step away from them.`}:{de:`${wp.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${wp.en}, or move the state into the successor's column.`}}s(vH,"passThroughRemedy");function xH(e,t){let n=ca(e,t);if(!n)return[];let{layout:r,wiring:i}=n;if(!r.buses.some(v=>v.key==="process"))return[];let o=VO(r);if(!o)return[];let a=new Map(e.nodes.map(v=>[v.id,v])),l=s(v=>Ye(v).progressEvents??[],"eventsOf"),d=s(v=>Object.values(v.next??{}).map(A=>A.to),"routesOf"),c=s((v,A)=>{let E=a.get(v);if(!E||A.has(v))return null;if(l(E).length>0)return[E];if(bC[E.type]!==!1)return null;let I=d(E);if(I.length===0)return null;let C=[];for(let $ of I){let b=c($,new Set([...A,v]));if(!b)return null;C.push(...b)}return C},"firstProgressNodes"),u=s((v,A)=>{let E=[];for(let I of l(v)){let C=Bs(i,v,I);if(!C||C.bus!==A.bus||C.state===A.state)return null;E.push(C.state)}return[...new Set(E)].join("' / '")},"overwrites"),p=s((v,A)=>{let E=d(v);if(E.length===0)return null;let I=[];for(let C of E){let $=c(C,new Set([v.id]));if(!$)return null;for(let b of $){let R=u(b,A);if(R===null)return null;I.push({de:`'${b.id}' (${b.type}) mit '${R}'`,en:`'${b.id}' (${b.type}) with '${R}'`})}}return[...new Map(I.map(C=>[C.de,C])).values()]},"submitOverwrittenBy"),h=new Map;for(let v of e.nodes)for(let A of l(v)){let E=Bs(i,v,A);if(!E||E.bus!=="process")continue;let I=v.type==="form"&&A===ef?p(v,E):null,C=I?{de:`'${v.id}'.${A} erreicht ihn, und ${I.map($=>$.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${v.id}'.${A} reaches it, and ${I.map($=>$.en).join(", ")} overwrites it in the same transaction`}:null;h.set(E.state,[...h.get(E.state)??[],C])}let w=_f(r,"process"),k=new Map;for(let[v,A]of h){if(!A.every(I=>I!==null))continue;let E=[...new Map(A.map(I=>[I.de,I])).values()];k.set(v,{de:E.map(I=>I.de).join("; "),en:E.map(I=>I.en).join("; ")})}let y=[];for(let v of o.columns){if(v.states.length===0||!v.states.every(I=>k.has(I)))continue;let A=v.states.map(I=>{let C=w.holdsSeat?.includes(I)===!0,$=k.get(I);return{de:`Zustand '${I}'${C?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${$.de}`,en:`State '${I}'${C?" (is in holdsSeat, but never takes a seat)":""}: ${$.en}`}}),E=vH(o.audience);y.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${v.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${v.label.de}" ('${v.id}', Board '${o.id}') bleibt immer leer \u2014 ${A.map(I=>I.de).join("; ")}. ${E.de}`,en:`[progress/passThroughState] Column "${v.label.en}" ('${v.id}', board '${o.id}') always stays empty \u2014 ${A.map(I=>I.en).join("; ")}. ${E.en}`},severity:"warning"})}return y}s(xH,"checkProgressPassThroughColumns");function SH(e){let t=["workItems","workitems","work_items","taskTemplates"],n=[];for(let r of e.nodes){let i=r;for(let o of t){let a=i[o];a!=null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.${o}`,reason:{de:`[workItems/misnamedTasksKey] Knoten "${r.id}" deklariert "${o}" \u2014 komponierte Aufgaben werden ausschlie\xDFlich unter "tasks" gelesen. So wie es dasteht, w\xFCrde die Aufgabenkette stillschweigend nie entstehen. Benenne den Schl\xFCssel in "tasks" um.`,en:`[workItems/misnamedTasksKey] Node "${r.id}" declares "${o}" \u2014 composed tasks are read only from "tasks". As it stands, the task chain would silently never be created. Rename the key to "tasks".`},severity:"error"})}}return n}s(SH,"checkMisnamedTasksKey");function AH(e){let t=[];for(let n of e.nodes){let r=n,i=Array.isArray(r.tasks)?r.tasks:[],o=new Set;for(let c of i){let u=typeof c.key=="string"?c.key:void 0;u!==void 0&&(o.has(u)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}`,reason:{de:`[workItems/duplicateTemplateKey] Doppelter Template-Key "${u}" auf Knoten "${r.id}".`,en:`[workItems/duplicateTemplateKey] Duplicate template key "${u}" on node "${r.id}".`},severity:"error"}),o.add(u))}let a=new Set;for(let c of Array.isArray(r.artifacts)?r.artifacts:[])typeof c.key=="string"&&a.add(`${c.key}Uploaded`);let l=Ye(n),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(n):[]).map(c=>[c.key,c]));for(let c of i){let u=typeof c.key=="string"?c.key:"?",p=typeof c.kind=="string"?c.kind:void 0;if(p===void 0||!Cl.has(p)){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.kind`,reason:{de:`[workItems/invalidKind] Task "${u}" auf Knoten "${r.id}" hat Art ${JSON.stringify(c.kind)}; komponierbar sind: ${[...Cl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Cl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.gatesNode`,reason:{de:`[workItems/gatesNodeOnTask] 'gatesNode' ist nur f\xFCr die Art 'approval' zul\xE4ssig \u2014 eine Task gated ihren Knoten nie direkt. Um eine gatende Freigabe zur\xFCckzuhalten, 'blocks' verwenden (Task "${u}" auf Knoten "${r.id}").`,en:`[workItems/gatesNodeOnTask] 'gatesNode' is only allowed for the kind 'approval' \u2014 a task never gates its node directly. To hold back a gating approval, use 'blocks' (task "${u}" on node "${r.id}").`},severity:"error"});let h=c.blocks,w=h===void 0?void 0:LN(e,r.id,h.node);if(h!==void 0&&w===null)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.node`,reason:{de:`[workItems/blocksUnknownNode] 'blocks.node' auf Task "${u}" (Knoten "${r.id}") nennt ${JSON.stringify(h.node)} \u2014 diesen Knoten gibt es im Workflow nicht.`,en:`[workItems/blocksUnknownNode] 'blocks.node' on task "${u}" (node "${r.id}") names ${JSON.stringify(h.node)} \u2014 there is no such node in the workflow.`},severity:"error"});else if(h!==void 0&&w!==void 0&&w!==null){let y=w.node.id===r.id,v=w.node.id,A=y?o:w.composedKeys,E=y?d:w.intrinsicByKey,I=w.node.assign??{};p==="approval"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks`,reason:{de:`[workItems/blocksOnApproval] 'blocks' ist auf der Art 'approval' verboten \u2014 nur Task-Zeilen d\xFCrfen einen Geschwister-Spawn zur\xFCckhalten (Approval "${u}" auf Knoten "${r.id}").`,en:`[workItems/blocksOnApproval] 'blocks' is forbidden on the kind 'approval' \u2014 only task rows may hold back a sibling spawn (approval "${u}" on node "${r.id}").`},severity:"error"});let C=h.templateKey,$=[...new Set([...A,...E.keys()])].filter(R=>!y||R!==u).join(", "),b={de:$||"keine",en:$||"none"};if(typeof C!="string"||y&&C===u||!A.has(C)&&!E.has(C))t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnknownTarget] 'blocks' muss ein Template auf dem Zielknoten benennen \u2014 komponiert ODER intrinsisch (nie sich selbst, nie ohne 'templateKey': die zielfreie Form geh\xF6rt der Maschine, nicht dem Autor). Ziel ${JSON.stringify(C)} auf Knoten "${v}"; zul\xE4ssige Ziele: ${b.de}.`,en:`[workItems/blocksUnknownTarget] 'blocks' must name a template on the target node \u2014 composed OR intrinsic (never itself, never without 'templateKey': the target-less form belongs to the engine, not the author). Target ${JSON.stringify(C)} on node "${v}"; allowed targets: ${b.en}.`},severity:"error"});else if(w.refuse(C)!==null)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:w.refuse(C),severity:"error"});else{let R=E.get(C);h.except!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.except`,reason:{de:`[workItems/blocksExceptRetired] 'blocks.except' auf Task "${u}" (Knoten "${r.id}") gibt es nicht mehr: eine blockierende Aufgabe sperrt die ganze Aktionsgruppe ihres Ziels (bei einer Entscheidung Freigeben, Warteliste, Ablehnen und das Nachr\xFCcken). 'except' entfernen.`,en:`[workItems/blocksExceptRetired] 'blocks.except' on task "${u}" (node "${r.id}") no longer exists: a blocking task locks the whole action group of its target (for a decision: approve, waitlist, reject and promote). Remove 'except'.`},severity:"error"}),R!==void 0&&R.recipient!=="external"&&R.verdictResolved!==!0&&typeof I[C]!="string"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:{de:`[workItems/blocksUnwiredTarget] Task "${u}" auf Knoten "${r.id}" h\xE4lt "${C}" (Knoten "${v}") zur\xFCck, aber der Knoten weist "${C}" keiner Gruppe zu \u2014 ohne 'assign.${C}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${C}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${C}" (node "${v}"), but the node assigns "${C}" to no group \u2014 without 'assign.${C}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${C}' or remove the 'blocks'.`},severity:"error"})}}{let y=c.completableIf;if(typeof y=="string"&&y.trim().length>0){let v=y.trim().replace(/^!/,"").trim();a.has(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${y}" verweist auf unbekannten Node-Export "${v}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${y}" refers to unknown node export "${v}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.commentRequired`,reason:{de:"[workItems/removedParam] 'params.commentRequired' wurde entfernt \u2014 Kommentar-Pflichten werden am Decision-Node ('commentRequired') autorisiert.",en:"[workItems/removedParam] 'params.commentRequired' was removed \u2014 comment requirements are authored on the decision node ('commentRequired')."},severity:"error"}),p!=="approval"){let y=[];k?.onReject!==void 0&&y.push("params.onReject"),k?.revisionGroup!==void 0&&y.push("params.revisionGroup");for(let v of y)t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${v}`,reason:{de:`[workItems/approvalOnlyField] '${v}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${v}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.onReject`,reason:{de:`[workItems/invalidOnReject] Erwartet 'spawnRevision', erhalten ${JSON.stringify(k.onReject)}.`,en:`[workItems/invalidOnReject] Expected 'spawnRevision', got ${JSON.stringify(k.onReject)}.`},severity:"error"}),k?.onReject==="spawnRevision"&&(typeof k.revisionGroup!="string"||k.revisionGroup.length===0)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.params.revisionGroup`,reason:{de:`[workItems/spawnRevisionNoTarget] Approval "${u}" mit 'params.onReject: spawnRevision' ohne 'params.revisionGroup' \u2014 die \xDCberarbeitung h\xE4tte keine Ziel-Gruppe.`,en:`[workItems/spawnRevisionNoTarget] Approval "${u}" with 'params.onReject: spawnRevision' but no 'params.revisionGroup' \u2014 the revision would have no target group.`},severity:"error"})}}return t.push(...MN(e)),t}s(AH,"checkWorkItemTemplates");var EH=new Set(["complete","approve","reject"]),bC={form:!0,decision:!0,review:!0,waitlist:!0,completenessCheck:!0,collectPayment:!0,eventTrigger:!0,join:!1,roleAssign:!1,setFlag:!1,if:!1,end:!1,countersign:!0,engagePush:!1,governedDocument:!0};function TH(e){let t=[];for(let n of e.nodes){let r=n,i=Ye(n),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(n)??[];if(o+a.length>0){let v=bC[r.type];v===void 0?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/unknownParkSemantics] Knotentyp "${r.type}" hat keine bekannte Park-Semantik \u2014 NODE_TYPE_PARKS in validators.ts erg\xE4nzen.`,en:`[workItems/unknownParkSemantics] Node type "${r.type}" has no known parking semantics \u2014 add it to NODE_TYPE_PARKS in validators.ts.`},severity:"error"}):v||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks`,reason:{de:`[workItems/templatesOnNonParkingNode] Knoten "${r.id}" (Typ "${r.type}") parkt nie \u2014 seine Work-Item-Templates w\xFCrden im selben Dispatch gespawnt und storniert (totes Muster).`,en:`[workItems/templatesOnNonParkingNode] Node "${r.id}" (type "${r.type}") never parks \u2014 its work-item templates would be spawned and cancelled in the same dispatch (dead pattern).`},severity:"error"})}let l=i.actions?.(n)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(v=>[v.id,v]));for(let v of l)EH.has(v.id)&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${v.id}" \u2014 reserviert f\xFCr den generischen Complete-/Verdict-Pfad (complete, approve, reject); die Spec muss eine andere Action-Id w\xE4hlen.`,en:`[capability/reservedActionId] Node type "${r.type}" declares the action "${v.id}" \u2014 reserved for the generic complete/verdict path (complete, approve, reject); the spec must choose a different action id.`},severity:"error"});let c=new Set(i.states??[i_]);for(let v of l)if(v.availableIn!==void 0)for(let A of v.availableIn)c.has(A)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${v.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${A}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${v.id}" on node type "${r.type}" is declared for state "${A}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=zy(n),p=new Set(u?u.map(v=>v.id):[Ys]);for(let v of l){if(v.external===void 0)continue;let A=r_(v.external.event),E={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},I=A?v.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${v.external.event}") \u2014 such actions are "internal"`}:v.outcome!==void 0?{de:`nennt das Outcome "${v.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${v.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${v.outcome}", but does not resolve the node (event "${v.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:v.label===void 0?E:null:v.kind!=="advance"?{de:`ist als "${v.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${v.kind}" (external actions resolve the node and must be "advance")`}:v.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(v.outcome)?v.label===void 0?E:null:{de:`verweist auf das unbekannte Outcome "${v.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${v.outcome}" (declared: ${[...p].join(", ")||"none"})`};I!==null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${v.id}" auf Knotentyp "${r.type}" ${I.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${v.id}" on node type "${r.type}" ${I.en}.`},severity:"error"})}for(let v of a){let A=v.unlocks;if(A.length===0&&v.verdictResolved!==!0&&v.informational!==!0){t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${v.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${v.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let E of A)d.get(E)===void 0&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${v.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${v.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${E}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${v.key}" on node "${r.id}" unlocks the unknown action "${E}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(v=>v.key));for(let v of Object.keys(r.assign??{}))h.has(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${v}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${v}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${v}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});let w=l.filter(v=>v.teamAssignable===!0).map(v=>v.id);for(let v of Object.keys(r.actionTeams??{}))w.includes(v)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${v}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${v}", aber diese Aktion l\xE4sst sich hier keinem Team geben; m\xF6glich: ${w.join(", ")||"keine"}.`,en:`[capability/unknownActionTeam] Node "${r.id}" names a team for "${v}", but this action cannot be given to a team here; possible: ${w.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let v of a)if(v.recipient==="external"||typeof(r.assign??{})[v.key]=="string")for(let E of v.unlocks)k.add(E);let y=i.strictActionCoverage===!0;for(let v of l){if(k.has(v.id)||v.superUserOnly===!0)continue;let A=a.find(I=>I.unlocks.includes(v.id)),E=A!==void 0?{de:` Fehlt die Zuweisung assign.${A.key}?`,en:` Is the assignment assign.${A.key} missing?`}:{de:"",en:""};t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${v.id}`,reason:{de:`[capability/superUserOnly] Action "${v.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${E.de}`,en:`[capability/superUserOnly] Action "${v.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${E.en}`},severity:y?"error":"warning"})}}return t}s(TH,"checkNodeCapabilityWiring");function $H(e){let t=new Set(zI()),n=[];for(let r of e.nodes)t.has(r.type)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.type`,reason:{de:`[graph/unknownNodeType] Knoten "${r.id}" hat den unbekannten Typ "${String(r.type)}". Registrierte Typen: ${[...t].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...t].join(", ")}.`},severity:"error"});return n}s($H,"checkKnownNodeTypes");function RH(e,t){let n=[],r=s((a,l)=>{n.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=tI(e),o=s(a=>typeof a=="object"&&a!==null&&Object.values(a).some(l=>typeof l=="string"&&l.trim().length>0),"hasText");for(let a of e.nodes){let l=a,d=Array.isArray(l.optionalActions)?l.optionalActions:[];if(n.push(...VH(l,d)),d.length===0)continue;let c=Ye(a),u=new Set(c.optionalActionKinds??[]),p=Array.isArray(l.tasks)?l.tasks:[],h=new Map;for(let y of p)typeof y.key=="string"&&h.set(y.key,y);let w=new Set,k=new Map;for(let y of d){let v=y.key,A=typeof v=="string"&&v.trim().length>0?v:void 0,E=A??"?",I=`nodes.${l.id}.optionalActions.${E}`,C=typeof y.action=="string"?y.action:void 0;if(y.when!==void 0){let $=s(b=>r(`${I}.when`,{de:`[optionalAction/when] Optionale Aktion "${E}" auf Knoten "${l.id}": ${b.de}`,en:`[optionalAction/when] Optional action "${E}" on node "${l.id}": ${b.en}`}),"conditionFinding");if(typeof y.when!="string"||y.when.trim()==="")$({de:"Die Bedingung ist leer \u2014 ohne Bedingung das Feld weglassen.",en:"The condition is empty \u2014 without a condition, omit the field."});else for(let b of Xf(y.when,i,t))$(b)}if((C===void 0||!u.has(C))&&r(`${I}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${E}" auf Knoten "${l.id}" hat die Art ${JSON.stringify(y.action)} \u2014 `+(u.size===0?`Knotentyp "${l.type}" deklariert keine Familien (spec.optionalActionKinds fehlt).`:`Knotentyp "${l.type}" deklariert nur: ${[...u].join(", ")}.`),en:`[optionalAction/kindNotDeclared] Optional action "${E}" on node "${l.id}" has the kind ${JSON.stringify(y.action)} \u2014 `+(u.size===0?`node type "${l.type}" declares no families (spec.optionalActionKinds is missing).`:`node type "${l.type}" only declares: ${[...u].join(", ")}.`)}),A===void 0?r(`${I}.key`,{de:`[optionalAction/missingKey] Optionale Aktion auf Knoten "${l.id}" ohne (oder mit leerem) 'key' \u2014 Trigger-Action und Template-Keys w\xE4ren namenlos ('optionalAction::\u2026').`,en:`[optionalAction/missingKey] Optional action on node "${l.id}" without (or with an empty) 'key' \u2014 the trigger action and template keys would be nameless ('optionalAction::\u2026').`}):(w.has(A)&&r(`${I}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${A}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${A}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),w.add(A)),o(y.label)||r(`${I}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${E}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${E}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),C==="spawnTasks"){y.except!==void 0&&r(`${I}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${E}" auf Knoten "${l.id}" tr\xE4gt 'except' \u2014 das gibt es nicht mehr: solange die Aufgaben offen sind, ist die ganze Aktionsgruppe des Knotens gesperrt. 'except' entfernen.`,en:`[optionalAction/exceptRetired] Optional action "${E}" on node "${l.id}" carries 'except' \u2014 that no longer exists: while the tasks are open, the node's whole action group is locked. Remove 'except'.`});let $=Array.isArray(y.tasks)?y.tasks:void 0;if($===void 0||$.length===0)r(`${I}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${E}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let b=new Set,R=new Set($.filter(q=>typeof q=="string"));for(let q of $){let _=typeof q=="string"?q:void 0;if(_===void 0||_.length===0){r(`${I}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(b.has(_)){r(`${I}.tasks.${_}`,{de:`[optionalAction/duplicateTaskRef] Template "${_}" ist in der Aktion "${E}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${_}" is referenced twice in the action "${E}" on node "${l.id}".`});continue}b.add(_);let J=h.get(_);if(J===void 0){r(`${I}.tasks.${_}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${E}" auf Knoten "${l.id}" referenziert das Template "${_}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${E}" on node "${l.id}" references the template "${_}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let Y=k.get(_);Y!==void 0&&Y!==E?r(`${I}.tasks.${_}`,{de:`[optionalAction/taskDoublyBound] Template "${_}" auf Knoten "${l.id}" ist bereits von der Aktion "${Y}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${_}" on node "${l.id}" is already referenced by the action "${Y}" \u2014 a template belongs to at most one optional action.`}):k.set(_,E);let ue=J.blocks?.templateKey;typeof ue=="string"&&!R.has(ue)&&r(`${I}.tasks.${_}`,{de:`[optionalAction/taskRefBlocks] Template "${_}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${ue}", das nicht zur selben Aktion "${E}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${_}" on node "${l.id}" carries 'blocks' on "${ue}", which does not belong to the same action "${E}" \u2014 a reference may only hold back a reference of the SAME action (checklist order), never a template outside it.`});for(let Q of p){let re=typeof Q.key=="string"?Q.key:void 0;Q.blocks?.templateKey===_&&(re!==void 0&&R.has(re)||r(`${I}.tasks.${_}`,{de:`[optionalAction/taskRefBlocks] Template "${_}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${E}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${_}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${E}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return n}s(RH,"checkOptionalActions");function IH(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(IH,"literalValueType");function OH(e,t){let n=[],r=t?.notificationTemplates;for(let i of e.nodes){let o=i,a=E_(i,Ye(i)),l=o.notifications??{};if(a.length===0&&Object.keys(l).length===0)continue;let d=new Map(a.map(c=>[c.id,c]));for(let c of Object.keys(l))d.has(c)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c}`,reason:{de:`[notification/unknownEvent] Knoten "${o.id}" bindet einen Brief an das Ereignis "${c}", das der Knotentyp "${o.type}" nicht kennt. Angeboten werden: ${a.map(u=>u.id).join(", ")||"(keine)"}.`,en:`[notification/unknownEvent] Node "${o.id}" binds a letter to the event "${c}", which the node type "${o.type}" does not know. Offered: ${a.map(u=>u.id).join(", ")||"(none)"}.`},severity:"error"});for(let c of a){let u=l[c.id];if(c.required===!0&&(u===void 0||u.disabled===!0)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c.id}`,reason:{de:`[notification/missingBinding] Knoten "${o.id}" muss beim Ereignis "${c.label.de}" (${c.id}) einen Brief verschicken \u2014 es ist ${u===void 0?"keiner gebunden":"einer gebunden, aber abgeschaltet"}.`,en:`[notification/missingBinding] Node "${o.id}" must send a letter on the event "${c.label.en}" (${c.id}) \u2014 ${u===void 0?"none is bound":"one is bound, but switched off"}.`},severity:"error"});continue}if(u===void 0||u.disabled===!0)continue;let p=`nodes.${o.id}.notifications.${c.id}`;if(c.audience!=="external"){n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/internalAudienceUnsupported] Knoten "${o.id}": das Ereignis "${c.id}" richtet sich an die Schule, und Briefe an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 der gebundene Brief "${u.templateId}" w\xFCrde den Vorgang beim Versand abbrechen.`,en:`[notification/internalAudienceUnsupported] Node "${o.id}": the event "${c.id}" is addressed to the school, and letters to the school cannot be delivered yet \u2014 the bound letter "${u.templateId}" would abort the process when it is sent.`},severity:"error"});continue}if(r===void 0)continue;let h=r.get(u.templateId);if(h===void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": der Brief "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the letter "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&n.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/audienceMismatch] Der Brief "${h.id}" ist f\xFCr ${h.audience==="internal"?"die Schule":"die Familie"} geschrieben, das Ereignis "${c.id}" richtet sich aber an die Familie.`,en:`[notification/audienceMismatch] The letter "${h.id}" is written for ${h.audience==="internal"?"the school":"the family"}, but the event "${c.id}" is addressed to the family.`},severity:"warning"});let w=b_(c),k=new Set(h.params.map(y=>y.key));for(let y of Object.keys(u.args??{}))k.has(y)||n.push({layer:"GRAPH",kind:"nodeRule",path:`${p}.args.${y}`,reason:{de:`[notification/unknownArg] Der Brief "${h.id}" hat kein Argument "${y}" \u2014 erwartet werden: ${h.params.map(v=>v.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The letter "${h.id}" has no argument "${y}" \u2014 expected: ${h.params.map(v=>v.key).join(", ")||"(none)"}.`},severity:"error"});for(let y of h.params){let v=u.args?.[y.key],A=`${p}.args.${y.key}`;if(v!==void 0&&"literal"in v){let I=IH(v.literal);y.type!==void 0&&!sw(I,y.type)&&n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/argTypeMismatch] "${y.key}" erwartet ${_l(y.type).de}, festgelegt ist aber ${JSON.stringify(v.literal)} (${I}).`,en:`[notification/argTypeMismatch] "${y.key}" expects ${_l(y.type).en}, but ${JSON.stringify(v.literal)} (${I}) is set.`},severity:"error"});continue}if(v!==void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unsupportedArg] "${y.key}" ist an ${JSON.stringify(v)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${kC(w,"de")} kommen.`,en:`[notification/unsupportedArg] "${y.key}" is bound to ${JSON.stringify(v)} \u2014 a letter argument can only be a fixed value ({ literal }) or come automatically from ${kC(w,"en")}.`},severity:"error"});continue}let E=v_(y,w.get(y.key)??[]);if(!(E.status==="resolved"||E.status==="unused")){if(E.status==="sometimes"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}" immer, ${E.source.source} liefert es aber nur manchmal. In notifications.${c.id}.args.${y.key} einen Festwert benennen \u2014 oder einen Brief w\xE4hlen, der ohne "${y.key}" auskommt.`,en:`[notification/unresolvedArg] The letter "${h.id}" always needs "${y.key}", but ${E.source.source} provides it only sometimes. Name a fixed value in notifications.${c.id}.args.${y.key} \u2014 or choose a letter that works without "${y.key}".`},severity:"error"});continue}if(E.status==="ambiguous"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/ambiguousArg] "${y.key}" hat mehrere passende Quellen \u2014 ${E.matches.map(I=>I.source).join(", ")}. In notifications.${c.id}.args.${y.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${y.key}" has several matching sources \u2014 ${E.matches.map(I=>I.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${y.key}.`},severity:"error"});continue}n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}"${y.type!==void 0?` (${_l(y.type).de})`:""}, und der Knoten hat daf\xFCr ${E.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${E.rejected.map(I=>`${I.source} (${I.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The letter "${h.id}" needs "${y.key}"${y.type!==void 0?` (${_l(y.type).en})`:""}, and the node has ${E.rejected.length===0?"no source for it":`only unsuitable sources for it: ${E.rejected.map(I=>`${I.source} (${I.type})`).join(", ")}`}.`},severity:"error"})}}}}return n}s(OH,"checkNotificationBindings");function _H(e){return nN(e).map(t=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:t,severity:"error"}))}s(_H,"checkAssignmentRules");function kC(e,t){let n=[...e.keys()].sort();return n.length===0?t==="de"?"(nichts)":"(nothing)":n.join(", ")}s(kC,"describeCandidates");function NH(e,t){return oN(e,t?.teamKeys).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(NH,"checkChannels");function CH(e){return rI(e).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(CH,"checkStaffInputs");function PH(e,t){let n=[];for(let r of e.nodes){let i=r.reads;if(i===void 0)continue;let o=`nodes.${r.id}.reads`,a={de:`Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id})`,en:`Node "${_e(e,r.id,"en")}" (${r.id})`},l=s(c=>{n.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!hN(r)){l({de:`[readiness/readsNotGated] ${a.de} (${r.type}) deklariert \`reads\`, aber die Bereitschaftspr\xFCfung h\xE4lt nur Entscheidungs-Knoten und Dokument-Knoten mit Produktion \u2014 hier w\xFCrde \`reads\` nichts bewirken.`,en:`[readiness/readsNotGated] ${a.en} (${r.type}) declares \`reads\`, but the readiness check only holds decision nodes and document nodes with production \u2014 here \`reads\` would have no effect.`});continue}if(!Array.isArray(i)){l({de:`[readiness/readsDuplicate] \`reads\` von ${a.de} muss eine Liste von Feldadressen sein, erhalten ${JSON.stringify(i)}.`,en:`[readiness/readsDuplicate] \`reads\` of ${a.en} must be a list of field addresses, got ${JSON.stringify(i)}.`});continue}let d=new Set;for(let c of i){if(!xe(c))continue;let u=pe(c);if(d.has(u)){l({de:`[readiness/readsDuplicate] ${a.de} liest ${je(e,c,"de")} mehrfach.`,en:`[readiness/readsDuplicate] ${a.en} reads ${je(e,c,"en")} more than once.`});continue}if(d.add(u),!ct(c)){l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 \`reads\` nennt nur Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 \`reads\` only names fields of a form ($node.<form>.admission.<field>).`});continue}let p=ni(t,c);p!=null&&Vs("nodeReads",js(p))==="repeated"&&l({de:`[readiness/readsUnknownField] ${a.de} liest ${je(e,c,"de")} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Feld der Anmeldung und kann nicht gelesen werden.`,en:`[readiness/readsUnknownField] ${a.en} reads ${je(e,c,"en")} \u2014 a field in a repeated group is not a single field of the application and cannot be read.`})}}return n}s(PH,"checkReadinessReads");function DH(e,t){let n=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=oO(r),o=bf(r);if(i===null||o===null)continue;let a=t?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${Ot.flagKey}`,reason:{de:`[setFlag/unknownFlag] Knoten \u201E${_e(e,r.id,"de")}\u201C (${r.id}) setzt \u201E${o}\u201C, aber das Formular von \u201E${_e(e,i,"de")}\u201C hat kein externes Merkmal dieses Namens`+(l.length>0?` (vorhanden: ${l.join(", ")}).`:" \u2014 es deklariert gar keins."),en:`[setFlag/unknownFlag] Node "${_e(e,r.id,"en")}" (${r.id}) sets "${o}", but the form of "${_e(e,i,"en")}" has no external flag of that name`+(l.length>0?` (present: ${l.join(", ")}).`:" \u2014 it declares none at all.")},severity:"error"})}return n}s(DH,"checkSetFlagKeys");function FH(e,t){let n=t?.readinessFormFieldsByFormNode,r=t?.readinessPartyConditionKeysByFormNode;if(n===void 0||r===void 0)return[];let i=[];for(let o of e.nodes){if(o.type!=="governedDocument"||o.production!=="resolver")continue;let a=o.form;if(!xe(a)||!wr(a))continue;let l=n.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=kw(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(y=>ct(y)&&y.owner===a.owner),h=kw(l,[...p.map(y=>y.path),...wN(o).filter(y=>y.owner===a.owner).map(y=>y.fieldKey)]),w=[...c].filter(y=>!h.has(y)).sort();if(w.length===0)continue;let k={de:_e(e,a.owner,"de"),en:_e(e,a.owner,"en")};i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.reads`,reason:{de:`[readiness/readsMissesPartyCondition] Knoten \u201E${_e(e,o.id,"de")}\u201C (${o.id}) erzeugt ein Dokument, dessen Vertragsparteien von Angaben im Formular \u201E${k.de}\u201C abh\xE4ngen, die er weder liest noch bindet: ${w.join(", ")}. Eine Korrektur darauf h\xE4lt den Knoten nicht an und kann nach der Ausstellung eine Vertragspartei entfernen \u2014 die Felder (oder den berechneten Schl\xFCssel) aus \u201E${k.de}\u201C in \`reads\` erg\xE4nzen.`,en:`[readiness/readsMissesPartyCondition] Node "${_e(e,o.id,"en")}" (${o.id}) generates a document whose contract parties depend on answers in the form "${k.en}" that it neither reads nor binds: ${w.join(", ")}. A correction to them does not hold the node and can remove a contract party after issuing \u2014 add the fields (or the computed key) from "${k.en}" to \`reads\`.`},severity:"warning"})}return i}s(FH,"checkReadinessPartyConditions");function Nw(e){let t=Object.keys(e.inputs??{});if(t.length===0)return[];let n=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(n?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(zs(e).map(l=>l.id));return t.filter(l=>!a.has(l))}s(Nw,"undeclaredInputKeys");function LH(e,t){return e.nodes.flatMap(n=>[...qH(e,n,zs(n),t),...MH(e,n,t)])}s(LH,"checkUnknownResources");function MH(e,t,n){let r=[],i=new Set((Ye(t).workItemTemplates?.(t)??[]).map(a=>a.key)),o=new Set((t.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of Rf(t)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=qs[a.leaf],d=`nodes.${t.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,t.id,"en")}" (${t.id}), ${l.what.en} "${a.owner}"`,"where");if(a.missing){if(!l.required){r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/emptyReference] ${c("de")}: der Eintrag ist leer oder kein Schl\xFCssel \u2014 ${l.consequence.de}. Team w\xE4hlen oder den Eintrag entfernen.`,en:`[inputs/emptyReference] ${c("en")}: the entry is empty or no key \u2014 ${l.consequence.en}. Choose a team or remove the entry.`}});continue}r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[workItems/needsTeam] ${c("de")}: kein Team gew\xE4hlt \u2014 ${l.consequence.de}. Jede Aufgabe geh\xF6rt der Warteschlange eines Teams.`,en:`[workItems/needsTeam] ${c("en")}: no team chosen \u2014 ${l.consequence.en}. Every task belongs to a team's queue.`}});continue}if(a.key===null)continue;let u=n?.teamKeys;if(u===void 0||u.has(a.key))continue;let p=[...u].sort().join(", ")||"\u2014";r.push({layer:"GRAPH",kind:"nodeRule",path:d,severity:"error",reason:{de:`[inputs/unknownResource] ${c("de")}: \u201E${a.key}\u201C ist kein Team dieses Mandanten \u2014 ${l.consequence.de}. Teams: ${p}.`,en:`[inputs/unknownResource] ${c("en")}: "${a.key}" is no team of this school \u2014 ${l.consequence.en}. Teams: ${p}.`}})}return r}s(MH,"referenceIssues");function qH(e,t,n,r){let i=[];for(let o of n){if(!vf(o.type))continue;let a=Fs[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=t.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=Fs[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.id}) nennt im Eingang \u201E${o.label.de}\u201C ${c.de} \u201E${d.value}\u201C \u2014 diesen Schl\xFCssel kennt dieser Mandant nicht.`,en:`[inputs/unknownResource] Node "${_e(e,t.id,"en")}" (${t.id}) names the ${c.en.toLowerCase()} "${d.value}" in its input "${o.label.en}", which does not exist in this school.`},severity:"error"})}return i}s(qH,"unknownResourceIssues");function KH(e){let t=[];for(let n of e.nodes)for(let r of Nw(n))t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) hat einen Eingang \u201E${r}\u201C, den sein Typ nicht deklariert \u2014 ein Rest einer fr\xFCheren Einstellung (z. B. eines anderen Generators). Im Parameter-Bereich ist er nicht sichtbar; entfernen.`,en:`[inputs/undeclared] Node "${_e(e,n.id,"en")}" (${n.id}) has an input "${r}" its type does not declare \u2014 a leftover of an earlier setting (e.g. another generator). It is not visible among the parameters; remove it.`},severity:"error"});return t}s(KH,"checkUndeclaredInputs");function jH(e){let t=[];for(let n of e.nodes){let r=new Set;for(let i of zs(n)){if(!r.has(i.id)){r.add(i.id);continue}t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}) hat den Eingang \u201E${i.id}\u201C zweimal \u2014 ein Parameter des Generators oder der Vorlage tr\xE4gt den Namen eines Eingangs des Knotentyps. Den Parameter umbenennen.`,en:`[inputs/duplicateSlot] Node "${_e(e,n.id,"en")}" (${n.id}) has the input "${i.id}" twice \u2014 a parameter of the generator or template carries the name of an input of the node type. Rename the parameter.`},severity:"error"})}}return t}s(jH,"checkDuplicateSlots");function vC(e,t,n){let r=[],i=$H(e);if(i.length>0)return i;r.push(...fH(e)),r.push(...cH(e)),r.push(...pH(e)),r.push(...uH(e)),r.push(...aH(e)),r.push(...lH(e)),r.push(...dH(e)),r.push(...hH(e)),r.push(...WO(e,t)),r.push(...gH(e,t)),r.push(...yH(e,t)),r.push(...wH(e,t)),r.push(...xN(e,t?.layout)),r.push(...kH(e,t)),r.push(...bH(e,t)),r.push(...xH(e,t)),r.push(...MO(e,n)),r.push(...QO(e)),r.push(...n_(e)),r.push(...HO(e)),r.push(...JO(e)),r.push(...KH(e)),r.push(...LH(e,n)),r.push(...jH(e)),r.push(...SH(e)),r.push(...AH(e)),r.push(...KN(e,n)),r.push(...GN(e)),r.push(...BN(e)),r.push(...zN(e,n)),r.push(...JN(e,n)),r.push(...TH(e)),r.push(...OH(e,n)),r.push(...RH(e,n)),r.push(..._H(e)),r.push(...PH(e,n)),r.push(...FH(e,n)),r.push(...DH(e,n)),r.push(...NH(e,n)),r.push(...CH(e)),r.push(...wC(e));for(let o of e.nodes){let a=Ye(o);a.validate&&r.push(...a.validate(o,e,n))}return r}s(vC,"checkGraph");function VH(e,t){let n=e.requiresOneOf;if(n===void 0)return[];let r=`nodes.${e.id}.requiresOneOf`,i=s(d=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:d,severity:"error"}),"issue");if(e.type!=="decision")return[i({de:`[decision/requiresOneOfNotDecision] Knoten "${e.id}" (Typ "${e.type}") tr\xE4gt 'requiresOneOf' \u2014 die Regel gilt nur an Entscheidungsknoten (decision).`,en:`[decision/requiresOneOfNotDecision] Node "${e.id}" (type "${e.type}") carries 'requiresOneOf' \u2014 the rule only applies to decision nodes (decision).`})];if(!Array.isArray(n)||n.length===0||n.some(d=>typeof d!="string"||d.length===0))return[i({de:`[decision/requiresOneOfEmpty] 'requiresOneOf' an Knoten "${e.id}" muss eine nicht-leere Liste von Aktions-Keys sein \u2014 sonst Feld weglassen.`,en:`[decision/requiresOneOfEmpty] 'requiresOneOf' on node "${e.id}" must be a non-empty list of action keys \u2014 otherwise omit the field.`})];let o=t.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of n){if(l.has(d)){a.push(i({de:`[decision/requiresOneOfDuplicate] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}" doppelt.`,en:`[decision/requiresOneOfDuplicate] 'requiresOneOf' on node "${e.id}" names "${d}" twice.`}));continue}l.add(d),o.includes(d)||a.push(i({de:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' an Knoten "${e.id}" nennt "${d}", aber dieser Knoten hat keine optionale Aktion mit diesem Key \u2014 die Regel w\xE4re nie erf\xFCllbar. `+(o.length===0?"Der Knoten hat keine optionalen Aktionen.":`Optionale Aktionen dieses Knotens: ${o.join(", ")}.`),en:`[decision/requiresOneOfUnknownAction] 'requiresOneOf' on node "${e.id}" names "${d}", but this node has no optional action with that key \u2014 the rule could never be met. `+(o.length===0?"The node has no optional actions.":`Optional actions of this node: ${o.join(", ")}.`)}))}return a}s(VH,"checkRequiresOneOf");function BH(e){return e.nodes.flatMap(t=>Nw(t).map(n=>({nodeId:t.id,key:n,binding:t.inputs?.[n]?.kind==="binding"})))}s(BH,"undeclaredInputCells");function xC(e,t){let n=BH(e).filter(o=>t.bindings||!o.binding);if(n.length===0)return{graph:e,dropped:n};let r=new Map;for(let o of n)r.set(o.nodeId,(r.get(o.nodeId)??new Set).add(o.key));let i=e.nodes.map(o=>{let a=r.get(String(o.id));if(a===void 0)return o;let l=Object.fromEntries(Object.entries(o.inputs).filter(([d])=>!a.has(d)));return{...o,inputs:l}});return{graph:{...e,nodes:i},dropped:n}}s(xC,"dropUndeclaredInputs");function Cw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Cw,"isObject");function SC(e){return Cw(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(SC,"oldShape");function AC(e){return(e?.nodes??[]).some(SC)}s(AC,"needsTemplateStampMove");function UH(e){let t=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(t)?t:null;let n=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(n)?n:null}s(UH,"stampedFields");function GH(e){let t=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:t,reason:"templateAndStamp"}};let n={...e},r=[];if("template"in e){let{template:i}=e;if(delete n.template,Cw(i))n.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:t,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete n.cockpitFields;let o=Cw(e.inputs)?{...e.inputs}:{},a=UH(n);if(a===null&&i.length>0)return{unmoved:{nodeId:t,key:i[0],reason:"noStamp"}};for(let l of i){let d=l in o&&o[l]?.kind!=="unset",c=(a??[]).find(u=>u.key===l);if(c===void 0)r.push({nodeId:t,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:t,key:l,reason:"processSource"}):d?r.push({nodeId:t,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}n.inputs=o}return{node:n,reports:r}}s(GH,"moveNode");function EC(e){let t=[],n=[],r=[],i=e.nodes.map(o=>{if(!SC(o))return o;let a=GH(o);return"unmoved"in a?(r.push(a.unmoved),o):(t.push(String(o.id)),n.push(...a.reports),a.node)});return t.length===0?{graph:e,moved:t,reports:n,unmoved:r}:{graph:{...e,nodes:i},moved:t,reports:n,unmoved:r}}s(EC,"moveTemplateStampAndCockpit");var TC=tf,zH="applicant.applicationSubmitted";function kp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(kp,"isObject");function $C(e){return kp(e)&&e.type==="form"&&typeof e.id=="string"&&!kn(e)}s($C,"isCreatingFormNode");function WH(e){return kp(e.notifications)&&TC in e.notifications}s(WH,"hasSubmittedBinding");function Pw(e){let t={toBind:[],alreadyBound:[],malformed:[]};for(let n of e?.nodes??[])$C(n)&&(n.notifications!==void 0&&!kp(n.notifications)?t.malformed.push(n.id):WH(n)?t.alreadyBound.push(n.id):t.toBind.push(n.id));return t}s(Pw,"submitReceiptInventory");function RC(e){let{toBind:t}=Pw(e);if(t.length===0)return{graph:e,bound:[]};let n=new Set(t),r=e.nodes.map(i=>{if(!$C(i)||!n.has(i.id))return i;let o=kp(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[TC]:{templateId:zH}}}});return{graph:{...e,nodes:r},bound:t}}s(RC,"bindSubmitReceipt");var Mo=["park","advance"],tr="whenNothingOwed",IC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function OC(e){let t=e.inputs?.[tr],n=t?.kind==="literal"?t.value:void 0;return Dw(n)?n:null}s(OC,"reviewModeOrNull");function Dw(e){return Mo.includes(e)}s(Dw,"isReviewMode");function Fw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Fw,"isObject");function _C(e){return Fw(e)&&e.type==="review"&&!(Fw(e.inputs)&&tr in e.inputs)}s(_C,"lacksMode");function NC(e){return(e?.nodes??[]).some(_C)}s(NC,"needsReviewMode");function CC(e){let t=[],n=e.nodes.map(r=>{if(!_C(r))return r;t.push(r.id);let i=Fw(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[tr]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:n},set:t}}s(CC,"setReviewModePark");function bp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(bp,"isObject");function PC(e){let{notifications:t,bound:n}=Vf(e.notifications,{tasks:[]},e);return{next:t,bound:n}}s(PC,"bindingsFor");function DC(e){let t={toBind:[],malformed:[]};for(let n of e?.nodes??[])if(!(!bp(n)||typeof n.id!="string"||Js(n).length===0)){if(n.notifications!==void 0&&!bp(n.notifications)){t.malformed.push(n.id);continue}for(let r of PC(n).bound)t.toBind.push(`${n.id}.${r}`)}return t}s(DC,"appointmentLetterInventory");function FC(e){let t=[],n=!1,r=e.nodes.map(i=>{if(!bp(i)||typeof i.id!="string"||Js(i).length===0||i.notifications!==void 0&&!bp(i.notifications))return i;let{next:o,bound:a}=PC(i);return a.length===0?i:(n=!0,t.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return n?{graph:{...e,nodes:r},bound:t}:{graph:e,bound:[]}}s(FC,"bindAppointmentLetters");function ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ua,"isObject");var LC=["id","label","dataFlow"],MC=["audience","populates","stages","expectedOutcomes"];function qC(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(t=>ua(t)&&typeof t.slot=="string")}s(qC,"carriesStringSlots");function KC(e){return(e.nodes??[]).some(t=>ua(t)&&t.type==="form"&&MC.some(n=>n in t))}s(KC,"carriesRetiredFormNodeKey");var YH=[{key:"generatorPin",editor:!0,holds:RI,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:cO,what:{de:"Formular und Merkmal eines \u201EFlag setzen\u201C-Knotens als Eigenschaften",en:'form and flag of a "Set flag" node as properties'}},{key:"scalarProperties",editor:!0,holds:gO,what:{de:"Einstellungen eines Knotens als Eigenschaften statt als Eing\xE4nge",en:"a node's settings as properties instead of inputs"}},{key:"nodeConfigProperties",editor:!0,holds:AO,what:{de:"Hinweis einer Zahlung als Eigenschaft oder ein entferntes Muster-Dokument",en:"a payment's note as a property, or a removed sample document"}},{key:"outcomeWithoutSemantic",editor:!0,holds:wI,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:xI,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:AC,what:{de:"Parameter einer Vorlage am Knoten oder Cockpit-Felder als Liste",en:"a template's parameters on the node, or cockpit fields as a list"}},{key:"reviewWithoutMode",editor:!0,holds:NC,what:{de:"Pr\xFCfknoten ohne \u201EWenn nichts zu pr\xFCfen ist\u201C",en:'review nodes without "When nothing is owed"'}},{key:"taskAssignUser",editor:!1,holds:s(e=>$f(e).length>0,"holds"),what:{de:"eine Aufgabe mit fester Person (`assign.userId`)",en:"a task with a fixed person (`assign.userId`)"}},{key:"retiredGraphKey",editor:!1,holds:s(e=>LC.some(t=>t in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:qC,what:{de:"Zust\xE4ndigkeitsregeln mit Slot als Text (`responsible` / `team:<Schl\xFCssel>`)",en:"assignment rules with a slot as text (`responsible` / `team:<key>`)"}},{key:"retiredFormNodeKey",editor:!1,holds:KC,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function jC(e){if(!ua(e)||!Array.isArray(e.nodes))return[];let t=e;return YH.filter(n=>n.holds(t)).map(({key:n,what:r,editor:i})=>({key:n,what:r,editor:i}))}s(jC,"legacyGraphShapes");function VC(e,t){let n=t.answers??{},r=[],i=[],o=e,a=LC.filter($=>$ in o);if(a.length>0){let $={...o};for(let b of a)delete $[b],r.push({message:`graph.${b}: deleted (read by nothing)`});o=$}if(KC(o)&&(o={...o,nodes:o.nodes.map($=>{if(!ua($)||$.type!=="form")return $;let b=MC.filter(q=>q in $);if(b.length===0)return $;let R={...$};for(let q of b)delete R[q];return r.push({nodeId:String($.id),message:`form node: deleted ${b.map(q=>`\`${q}\``).join(", ")} (read by nothing)`}),R})}),qC(o)){let $=o.assignmentRules.map((b,R)=>{if(!ua(b)||typeof b.slot!="string")return b;let q=mf(b.slot);return q===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${R}].slot "${b.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),b):(r.push({message:`assignmentRules[${R}].slot "${b.slot}" \u2192 ${JSON.stringify(q)}`}),{...b,slot:q})});o={...o,assignmentRules:$}}let l=II(o);o=l.graph;for(let $ of l.moved)r.push({nodeId:$,message:"generator / template pin moved into its input"});for(let $ of l.unmoved)i.push({code:`generatorPin/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${$.reason}) \u2014 edit the node by hand`});let d=uO(o);o=d.graph;for(let $ of d.moved)r.push({nodeId:$,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let $ of d.unmoved)i.push({code:`setFlag/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${$.reason}) \u2014 edit the node by hand`});let c=yO(o);o=c.graph;for(let $ of c.moved)r.push({nodeId:$,message:"scalar settings moved into inputs"});for(let $ of c.unmoved)i.push({code:`scalar/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let u=EO(o);o=u.graph;for(let $ of u.moved)r.push({nodeId:$,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let $ of u.unmoved)i.push({code:`nodeConfig/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`\`${$.key}\` cannot be moved into an input (${$.reason}) \u2014 edit the node by hand`});let p=EC(o);o=p.graph;for(let $ of p.moved){let b=o.nodes.find(_=>ua(_)&&_.id===$),R=b?.inputs?.documentTemplate,q=R?.kind==="literal"&&typeof R.value=="string"?R.value:null;r.push({nodeId:$,message:b!==void 0&&"templateStamp"in b&&q!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${q}\` must declare the same parameters (tenant catalog \`documentTemplates[].parameters\` / \`templates:setParameters\`) before publish, else [governedDocument/templateWithoutParameters]`:"cockpit list moved into `{ kind: 'cockpit' }` cells"})}for(let $ of p.reports)r.push({nodeId:$.nodeId,message:`cockpit field \`${$.key??""}\` deleted (${$.reason}: ${$.reason==="unknownKey"?"the stamp declares no such parameter":$.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let $ of p.unmoved)i.push({code:`templateStamp/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:$.reason==="noStamp"?"the cockpit list cannot be judged: the node carries no parameter stamp \u2014 run `offer workflow restamp-pins` against the environment, then upgrade again":$.reason==="templateAndStamp"?"the node carries both `template` and `templateStamp` \u2014 delete one by hand":"`template` is no object \u2014 edit the node by hand"});let h=SI(o);o=h.graph;for(let $ of h.moved)r.push({nodeId:$,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let $ of h.unmoved)i.push({code:`eventTrigger/${$.reason}`,nodeId:$.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${$.reason}) \u2014 edit the node by hand`});let w=kI(o,n.semantics);o=w.graph;for(let $ of w.written){if($.source==="formerDefault"){r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,value:$.semantic}});continue}r.push({nodeId:$.nodeId,message:`outcome \`${$.outcomeId}\`: semantic "${$.semantic}" (${$.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let $ of w.refused)i.push({code:$.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:$.nodeId,answer:"semantic",answerKey:`${$.nodeId}.${$.outcomeId}`,candidates:$.allowed,message:$.answer===void 0?`${$.nodeType} outcome \`${$.outcomeId}\` ran as "${py($.outcomeId)??""}", which a ${$.nodeType} outcome may no longer carry \u2014 say which one it is`:`${$.nodeType} outcome \`${$.outcomeId}\`: "${$.answer}" is not a meaning a ${$.nodeType} outcome may carry`});for(let $ of w.invalid)i.push({code:"outcome/semanticInvalid",nodeId:$.nodeId,answer:"edit",candidates:wn,message:`outcome \`${$.outcomeId}\` carries the semantic "${$.value}", which is no meaning \u2014 edit it`});let k=TI(o,t.selection,n.waitlistPolicy);o=k.graph;for(let $ of k.moved){let b=$.policy.waitlistOrder;r.push({nodeId:$.nodeId,message:`waitlist policy into inputs: ${HH($.policy)} (${$.source==="answer"?"answered":$.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...$.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:$.nodeId,value:b}}:{}})}for(let $ of k.refused)i.push({code:`waitlist/${$.reason}`,nodeId:$.nodeId,answer:"waitlistPolicy",answerKey:$.nodeId,candidates:Hn,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});if($O(o)){let $=RO(o,n.payee);o=$.graph;for(let b of $.set)r.push({nodeId:b.nodeId,message:`online payment: payee "${b.payee}" (answered)`});for(let b of $.refused)i.push({code:"collectPayment/payeeMissing",nodeId:b,answer:"payee",answerKey:b,message:"an online payment names the Tr\xE4ger its money goes to \u2014 say its key (a `legal_entities.configKey` of the tenant)"})}for(let $ of Pw(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:$,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let y=RC(o);o=y.graph;for(let $ of y.bound)r.push({nodeId:$,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let v=CC(o);o=v.graph;for(let $ of v.set)r.push({nodeId:$,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let $ of DC(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:$,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let A=FC(o);o=A.graph;for(let $ of A.bound){let b=$.indexOf(".");r.push({nodeId:$.slice(0,b),message:`appointment letter bound to \`notifications.${$.slice(b+1)}\` (the standard letter, sent by code before)`})}let E=$f(o).filter($=>!$.hasTeam);for(let $ of E)i.push({code:"task/userWithoutTeam",nodeId:$.nodeId,answer:"edit",message:`task \`${$.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let I=IO(o);o=I.graph;for(let $ of I.dropped.filter(b=>b.hasTeam))r.push({nodeId:$.nodeId,message:`task \`${$.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let C=xC(o,{bindings:!0});o=C.graph;for(let $ of C.dropped){if(!$.binding){r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:$.nodeId,message:`input \`${$.key}\` deleted (DEFAULT \u2014 a binding no slot declares: no slot handed its value to the node, but the readiness gate waited for it; the node no longer waits for that value)`,defaulted:{answer:"undeclaredBinding",answerKey:`${$.nodeId}.${$.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(VC,"upgradeGraph");function HH(e){return`waitlistOrder=${e.waitlistOrder}`}s(HH,"formatPolicy");function ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ci,"isObject");var BC="admission.generic",UC=Object.keys(uf).filter(e=>e!=="label");function GC(e){return ci(e.smartforms)?Object.entries(e.smartforms):[]}s(GC,"smartformEntries");function JH(e){let t=[];GC(e.index).some(([,i])=>ci(i)&&"outcomeFnRef"in i)&&t.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let n=Object.keys(e.manifest).filter(i=>Object.hasOwn(wl,i));if(n.length>0){let i=n.map(o=>`\`${o}\``).join(", ");t.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>UC.some(o=>o in i))&&t.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(ci(r.progressWiring)&&"layoutId"in r.progressWiring&&t.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),t.push(...jC(r.graph).map(i=>i.what))),t}s(JH,"legacyBundleShapes");function xp(e,t){let n=JH(e);n.length!==0&&ae("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${t} stammt aus einem \xE4lteren Bundle-Format (${n.map(r=>r.de).join("; ")}). Zuerst \`plexus-cli offer upgrade --dir <Bundle>\` ausf\xFChren (Probelauf, beantwortet die offenen Fragen), dann mit \`--write\` schreiben und erneut pr\xFCfen.`,en:`offer: ${t} is in an older bundle format (${n.map(r=>r.en).join("; ")}). Run \`plexus-cli offer upgrade --dir <bundle>\` first (a dry run that asks what it cannot decide), then write with \`--write\` and validate again.`})}s(xp,"assertBundleCurrent");function vp(e){let t=s(n=>Array.isArray(n)?n.map(t):ci(n)?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n,"sort");return JSON.stringify(t(e))}s(vp,"canonical");function zC(e,t={}){let n=[],r=[],i=e.index,o=GC(i);if(o.some(([,u])=>ci(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!ci(h)||Object.keys(h).length===0){u[p]=h;continue}let{outcomeFnRef:w,...k}=h;if(Object.keys(k).length>0||w!==void 0&&w!==BC){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(y=>`\`${y}\``).join(", ")} \u2014 only \`outcomeFnRef: ${BC}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}n.push({file:"bundle.yaml",message:`smartforms.${p}.outcomeFnRef deleted (a form routes by its own declared outcomes)`}),u[p]={}}i={...i,smartforms:u}}let a={},l=e.workflow,d;for(let[u,p]of Object.entries(e.manifest)){if(u==="selection"){d=p,n.push({file:"manifest.json",message:"`selection` deleted (its queue policy goes to the waitlist node's inputs; release strategy and deadline were read by nothing)"});continue}if(u==="progressLayout"){l===void 0?n.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},n.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):vp(l.progressLayout)===vp(p)?n.push({file:"manifest.json",message:"`progressLayout` deleted (workflow.json carries the same layout)"}):(r.push({file:"manifest.json",code:"manifest/progressLayoutTwice",answer:"edit",message:"`progressLayout` differs from workflow.json `progressLayout` \u2014 keep one by hand"}),a[u]=p);continue}let h=Object.hasOwn(wl,u)?wl[u]:void 0;if(h===void 0){r.push({file:"manifest.json",code:"manifest/unknownKey",answer:"edit",message:`unknown key \`${u}\` \u2014 manifest.json carries no key; decide by hand where it belongs`}),a[u]=p;continue}n.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(ci(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},n.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(ci(u)&&Array.isArray(u.nodes)){let p=VC(u,{selection:d,answers:t});l={...l,graph:p.graph},n.push(...p.changes.map(h=>({...h,file:"workflow.json"}))),r.push(...p.refusals.map(h=>({...h,file:"workflow.json"})))}else r.push({file:"workflow.json",code:"workflow/graphShape",answer:"edit",message:"`graph` is no object with a node list"})}let c=e.smartforms;if(c!==void 0){let u={};for(let[p,h]of Object.entries(c)){let w={...h},k=`smartforms/${p}.json`;for(let y of UC)if(y in h){if(y==="outcomeIds"){let v=Array.isArray(h.outcomes)?h.outcomes.map(A=>ci(A)?A.id:void 0):[];if(vp([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==vp(v.map(String).sort())){r.push({file:k,code:"smartform/outcomeIdsDiffer",answer:"edit",message:"`outcomeIds` differs from the ids of `outcomes[]` \u2014 reconcile them by hand"});continue}}delete w[y],n.push({file:k,message:`\`${y}\` deleted (${uf[y].en})`})}u[p]=w}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:n,refusals:r}}s(zC,"upgradeOfferBundle");var QH={createManifest:x.workflow.createManifest,publishManifest:x.workflow.publishManifest,publishOfferInternal:x.workflow.publishOfferInternal,publishOfferExternal:x.workflow.publishOfferExternal,getOfferPublishState:x.workflow.getOfferPublishState,upsertCustomField:x.admission.upsertCustomField,upsertDerivedAttributeRule:x.admission.upsertDerivedAttributeRule,createSmartForm:x.forms.createSmartForm,getSmartFormBySlug:x.forms.getSmartFormBySlug,saveSmartFormDraft:x.forms.saveSmartFormDraft,publishSmartForm:x.forms.publishSmartForm,createWorkflow:x.workflow.createWorkflow,getWorkflowGraph:x.workflow.getWorkflowGraph,saveWorkflowDraft:x.workflow.saveWorkflowDraft,publishWorkflow:x.workflow.publishWorkflow},Qye={createManifest:Xt.workflow.createManifestInternal,publishManifest:Xt.workflow.publishManifestInternal,publishOfferInternal:Xt.workflow.publishOfferInternalInternal,publishOfferExternal:Xt.workflow.publishOfferExternalInternal,getOfferPublishState:Xt.workflow.getOfferPublishStateInternal,upsertCustomField:Xt.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:Xt.admission.upsertDerivedAttributeRuleInternal,createSmartForm:Xt.forms.createSmartFormInternal,getSmartFormBySlug:Xt.forms.getSmartFormBySlugInternal,saveSmartFormDraft:Xt.forms.saveSmartFormDraftInternal,publishSmartForm:Xt.forms.publishSmartFormInternal,createWorkflow:Xt.workflow.createWorkflowInternal,getWorkflowGraph:Xt.workflow.getWorkflowGraphInternal,saveWorkflowDraft:Xt.workflow.saveWorkflowDraftInternal,publishWorkflow:Xt.workflow.publishWorkflowInternal};function Lw(e,t){for(let[n,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&ae("INVALID",{de:`offer: ${t}: smartforms.${n} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${t}: smartforms.${n} must be an empty mapping ({}).`});let i=Object.keys(r);if(i.length===0)continue;let o=i.map(l=>`\`${l}\``).join(", "),a=i.includes("outcomeFnRef");ae("INVALID",{de:`offer: ${t}: smartforms.${n} enth\xE4lt unbekannte Schl\xFCssel ${o} \u2014 der Eintrag muss leer sein ({}).${a?" `outcomeFnRef` geh\xF6rt nicht mehr zum Bundle-Format: ein Formular entscheidet \xFCber seine eigenen Ergebnisse. Die Zeile l\xF6schen.":""}`,en:`offer: ${t}: smartforms.${n} carries unknown key(s) ${o} \u2014 the entry must be empty ({}).${a?" `outcomeFnRef` is no longer part of the bundle format: a form routes by its own declared outcomes. Delete the line.":""}`})}}s(Lw,"assertSmartformEntries");function WC(e){let t=s(n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n,"sort");return JSON.stringify(t(e))}s(WC,"canonicalJson");function YC(e,t){return t==null?!0:WC(e)!==WC(t)}s(YC,"changed");async function HC(e,t,n,r={},i=QH){let{index:o}=t;xp({index:o,manifest:t.manifest,...t.smartforms!==void 0?{smartforms:t.smartforms}:{},...t.workflow!==void 0?{workflow:t.workflow}:{}},`bundle of ${o.slugs.manifest}`),Lw(o,`bundle of ${o.slugs.manifest}`);let a=cf(t.manifest);a.length>0&&ae("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
|
|
11207
11207
|
- ${a.join(`
|
|
11208
11208
|
- `)}`,en:`offer: manifest.json of ${o.slugs.manifest} is invalid:
|
|
11209
11209
|
- ${a.join(`
|
|
@@ -11288,7 +11288,7 @@ ${i.map(d=>` ${Ed(d)}
|
|
|
11288
11288
|
`),0}},EF=[Sb,Ab,Eb];var Tb=class extends D{static{s(this,"LeadsListCommand")}static paths=[["leads","list"],["interessenten","list"]];static usage=T.Usage({category:"Admission",description:"List Interessenten (leads) for the active tenant",details:"Lists the tenant's OPEN Interessenten (program interests), newest first. Converted leads are Bewerbungen (listed under applications); withdrawn/declined leads are removed. Use --json for the rich shape.",examples:[["List open Interessenten","plexus-cli leads list"],["As JSON","plexus-cli leads list --json"]]});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.leads.listForManagement,{client:n});return this.print(r,i=>i.map(o=>({name:o.personDisplayName??"\u2014",angebot:o.programName===null?"\u2014":Pe(o.programName),stufe:o.stageName===null?"\u2014":Pe(o.stageName),lauf:o.runName===null?"\u2014":Pe(o.runName)})),["name","angebot","stufe","lauf"]),0}},TF=[Tb];function Db(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(Db,"ts");function RF(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s(RF,"ago");var $F=["queued","running","succeeded","failed","canceled"];function M6(e){let t=$F.find(n=>n===e);if(t===void 0)throw new Error(`jobs list: --status must be one of ${$F.join(" | ")}, got "${e}".`);return t}s(M6,"jobStatus");var $b=class extends D{static{s(this,"JobsListCommand")}static paths=[["jobs","list"]];static usage=T.Usage({category:"Jobs",description:"List jobs newest-first (platform-admin). --status / --kind filter."});status=f.String("--status",{description:"queued | running | succeeded | failed | canceled"});kind=f.String("--kind",{description:"import | dummy | document_template_export"});limit=f.String("--limit",{description:"Max rows (default 100)."});all=f.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let t=await this.caller(),n=this.all?void 0:zu(this.limit,100),r=await this.paginate(t,x.jobs.listPage,this.status?{status:M6(this.status)}:{},{max:n,pageSize:Math.min(n??100,100)}),i=this.kind?r.filter(o=>o.kind===this.kind):r;return this.print(i,o=>o.map(a=>({id:a.id,kind:a.kind,status:a.status,tenant:a.tenantSlug??"",phase:a.phase,progress:a.progress?`${a.progress.current}/${a.progress.total}`:"",tries:`${a.attempts}/${a.maxAttempts}`,worker:a.leasedBy??"",updated:RF(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},Rb=class extends D{static{s(this,"JobsShowCommand")}static paths=[["jobs","show"]];static usage=T.Usage({category:"Jobs",description:"Show one job's full detail + per-attempt run timeline."});jobId=f.String({required:!0});async execute(){let n=await(await this.caller()).query(x.jobs.getDetail,{jobId:this.jobId});if(n===null)throw new Error(`Job ${this.jobId} not found.`);return this.print(n),0}},Ib=class extends D{static{s(this,"JobsLogsCommand")}static paths=[["jobs","logs"]];static usage=T.Usage({category:"Jobs",description:"Tail a job's captured worker output (oldest-first)."});jobId=f.String({required:!0});limit=f.String("--limit",{description:"Max lines (default 500, max 2000)."});async execute(){let n=await(await this.caller()).query(x.jobs.tailLog,{jobId:this.jobId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:Db(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Ob=class extends D{static{s(this,"JobsCancelCommand")}static paths=[["jobs","cancel"]];static usage=T.Usage({category:"Jobs",description:"Cancel a queued/running job (the worker aborts; the domain row is failed) \u2014 irreversible, plan unless --confirm."});jobId=f.String({required:!0});confirm=f.Boolean("--confirm",!1,{description:"Cancel (without it, only the plan is printed)."});async execute(){let t=await this.caller();if(!this.confirm){let n=await t.query(x.jobs.getDetail,{jobId:this.jobId});if(n===null)throw new Error(`Job ${this.jobId} not found.`);return this.print({jobId:this.jobId,kind:n.kind,status:n.status,canceled:!1},r=>[{key:"would cancel",value:`${r.jobId} (${r.kind}, ${r.status})`},{key:"next",value:"re-run with --confirm"}]),0}return await t.mutation(x.jobs.cancel,{jobId:this.jobId}),this.print({canceled:this.jobId}),0}},_b=class extends D{static{s(this,"WorkersLogsCommand")}static paths=[["platform","workers","logs"],["workers","logs"]];static usage=T.Usage({category:"Platform",description:"Tail one worker's captured stdout/stderr."});workerId=f.String({required:!0});limit=f.String("--limit",{description:"Max lines (default 500, max 2000)."});async execute(){let n=await(await this.caller()).query(x.workers.tailLog,{workerId:this.workerId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:Db(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Nb=class extends D{static{s(this,"WorkersReaperStatusCommand")}static paths=[["platform","workers","reaper-status"],["workers","reaper-status"]];static usage=T.Usage({category:"Platform",description:"Show the last worker-reaper tick (confirm the cron is firing)."});async execute(){let n=await(await this.caller()).query(x.workers.reaperStatus,{});return n===null?(this.print({reaper:"no tick recorded yet"}),0):(this.print({...n,ranAt:Db(n.ranAt)}),0)}},Cb=class extends D{static{s(this,"WorkersReapCommand")}static paths=[["platform","workers","reap"],["workers","reap"]];static usage=T.Usage({category:"Platform",description:"Force a reaper pass NOW (free dead leases / fail stalled jobs)."});async execute(){let n=await(await this.caller()).mutation(x.workers.reap,{});return this.print(n),0}},Pb=class extends D{static{s(this,"ImportsCleanupOrphansCommand")}static paths=[["platform","imports","cleanup-orphaned"],["imports","cleanup-orphaned"]];static usage=T.Usage({category:"Imports",description:"Find/fail orphaned import runs (status 'running' with no active job). Dry-run unless --confirm."});allTenants=f.Boolean("--all-tenants",!1,{description:"Scan every tenant (default: the active --tenant only)."});confirm=f.Boolean("--confirm",!1,{description:"Actually mark orphans failed (default: dry-run preview)."});async execute(){let t=await this.caller(),n=this.allTenants?void 0:this.requireTenant(t),r=await t.mutation(x.imports.failOrphanedRuns,{...n?{tenantSlug:n}:{},confirm:this.confirm});return this.print(r,i=>i.orphans.map(o=>({id:o.id,tenant:o.tenantSlug,importRunId:o.importRunId,phase:o.phase??"",updated:RF(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},IF=[$b,Rb,Ib,Ob,_b,Nb,Cb,Pb];var q6=/^(\d+)([mhd])$/,K6={m:6e4,h:36e5,d:864e5};function om(e,t=Date.now()){let n=e.trim(),r=q6.exec(n);if(r!==null)return t-Number(r[1])*K6[r[2]];let i=/^\d{4}-\d{2}-\d{2}/.test(n)?Date.parse(n):Number.NaN;if(Number.isNaN(i))throw new Error(`--since "${e}": expected 90m, 24h, 2d or an ISO date like 2026-10-13T11:40Z`);return i}s(om,"parseSince");function sm(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(sm,"ts");function Wb(e,t){if(e===void 0)throw new Error(`notifications ${t}: --locale is required (${ze.join("|")}) \u2014 every letter exists in each language, and each is worded on its own`);if(!qp(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${ze.join("|")})`);return e}s(Wb,"parseLocale");function j6(e,t){let n={},r=s((i,o,a)=>{let l=o.indexOf("=");if(l<=0)throw new Error(`notifications letters: malformed ${i} "${o}" (expected <blockKey>=<value>)`);let d=o.slice(0,l).trim();if(!d)throw new Error(`notifications letters: malformed ${i} "${o}" (empty block key)`);if(d in n)throw new Error(`notifications letters: block "${d}" given twice \u2014 one value per block.`);n[d]=a(o.slice(l+1))},"put");for(let i of e??[])r("--slot",i,o=>o);for(let i of t??[])r("--slot-file",i,o=>he(o.trim(),"utf8"));return n}s(j6,"parseSlots");var Fb=class extends D{static{s(this,"NotificationsListCommand")}static paths=[["platform","notifications","list"],["notifications","list"]];static usage=T.Usage({category:"Notifications",description:"List mail deliveries newest-first (platform-admin). Filter by --status, --template, --to, --since; the smtp column is the relay's answer (`250 \u2026 queued as <id>` = accepted).",examples:[["Dead-letters only","$0 notifications list --status dead"],["Everything still in flight","$0 notifications list --status queued"],["Did the login-page link to this address go out today?","$0 notifications list --template account.loginLink --to steffi@schule.example --since 24h"]]});status=f.String("--status",{description:"queued | sending | sent | skipped | dead"});template=f.String("--template",{description:"Only this letter, e.g. account.loginLink."});to=f.String("--to",{description:"Only deliveries to this address."});since=f.String("--since",{description:"Created since: 90m, 24h, 2d or an ISO date/time."});limit=f.String("--limit",{description:"Max rows (default 100)."});all=f.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let t=await this.caller(),n=this.all?void 0:zu(this.limit,100),r=await this.paginate(t,x.notifications.listPage,{...this.status?{status:this.status}:{},...this.template?{templateId:this.template}:{},...this.to?{recipientEmail:this.to}:{},...this.since?{since:om(this.since)}:{}},{max:n,pageSize:Math.min(n??100,100)});return this.print(r,i=>i.map(o=>({id:o.id,template:o.templateId,status:o.status,tenant:o.tenantSlug??"",to:o.recipientEmail,files:o.attachmentCount>0?String(o.attachmentCount):"",tries:`${o.attempts}/${o.maxAttempts}`,error:o.errorCode??"",mode:o.transportMode??"",dup:o.possibleDuplicate?"!":"",created:sm(o.createdAt),settled:sm(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function V6(e){if(e.letter===null)return{...e,attachments:[]};let{attachments:t,...n}=e.letter;return{...e,attachments:t.map(({filename:r,contentType:i,size:o})=>({filename:r,contentType:i,size:o})),letter:n}}s(V6,"showView");var Lb=class extends D{static{s(this,"NotificationsShowCommand")}static paths=[["platform","notifications","show"],["notifications","show"]];static usage=T.Usage({category:"Notifications",description:"Show one delivery in full: SMTP evidence, lease, sweeper bookkeeping, template summary."});deliveryId=f.String({required:!0});async execute(){let n=await(await this.caller()).query(x.notifications.getDetail,{deliveryId:this.deliveryId});if(n===null)throw new Error(`Delivery ${this.deliveryId} not found.`);return this.print(V6(n)),0}},Mb=class extends D{static{s(this,"NotificationsRetryCommand")}static paths=[["platform","notifications","retry"],["notifications","retry"]];static usage=T.Usage({category:"Notifications",description:"Retry a DEAD delivery: a fresh attempt through the normal claim path. Check `show` first \u2014 a `possibleDuplicate` row may already have reached the recipient."});deliveryId=f.String({required:!0});async execute(){return await(await this.caller()).mutation(x.notifications.retry,{deliveryId:this.deliveryId}),this.print({deliveryId:this.deliveryId,status:"queued"}),0}},qb=class extends D{static{s(this,"NotificationsSweeperStatusCommand")}static paths=[["platform","notifications","sweeper-status"],["notifications","sweeper-status"]];static usage=T.Usage({category:"Notifications",description:"Last tick of the notification sweeper cron (deadLastHour is the number to watch)."});async execute(){let n=await(await this.caller()).query(x.notifications.sweeperStatus,{});return n===null?(this.print({ranAt:null,note:"sweeper has not run since deploy"}),0):(this.print({...n,ranAt:sm(n.ranAt),lastDeadAt:sm(n.lastDeadAt)}),0)}},Kb=class extends D{static{s(this,"NotificationsSelfTestCommand")}static paths=[["platform","notifications","self-test"],["notifications","self-test"]];static usage=T.Usage({category:"Notifications",description:"Resolve the deployment's mail config, verify the SMTP connection + credentials, and send ONE test mail to --to with the raw SMTP transcript. A redirect deployment redirects the test too; dry sends nothing.",examples:[["Probe staging","$0 --env staging notifications self-test --to you@example.com"]]});to=f.String("--to",{required:!0,description:"Explicit recipient (never defaulted)."});async execute(){let n=await(await this.caller()).action(x.notificationActions.selfTest,{recipient:this.to});return this.print(n),n.ok?0:1}},jb=class extends D{static{s(this,"NotificationsLettersListCommand")}static paths=[["notifications","letters","list"]];static usage=T.Usage({category:"Notifications",description:"The letter catalog for one school: what it can reword, and what it already did.",details:"Only the letters a school may actually write are listed \u2014 addressed to families, and with blocks to rewrite. A staff-internal letter or a retired one is not offered at all. `reworded` names the languages in which this school has already deviated from a letter.",examples:[["The catalog","$0 --tenant test notifications letters list"],["Only the reworded ones","$0 --tenant test notifications letters list --json"]]});async execute(){let t=await this.caller(),n=await t.query(x.notifications.letterWorkspace,{tenantSlug:this.requireTenant(t),locale:"de"});return this.print(n.letters,r=>r.map(i=>({template:i.id,label:i.label,blocks:i.slots.map(o=>o.key).join(", "),reworded:i.rewordedIn.join(", ")})),["template","label","blocks","reworded"]),0}},Vb=class extends D{static{s(this,"NotificationsLettersShowCommand")}static paths=[["notifications","letters","show"]];static usage=T.Usage({category:"Notifications",description:"One letter block by block: the current text, whether it deviates, and the placeholders it may use.",examples:[["The welcome letter","$0 --tenant test notifications letters show applicant.welcome --locale de"],["Its English version","$0 --tenant test notifications letters show applicant.welcome --locale en"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});async execute(){let t=await this.caller(),n=await t.query(x.notifications.letterWorkspace,{tenantSlug:this.requireTenant(t),locale:Wb(this.locale,"letters show")}),r=n.letters.find(i=>i.id===this.templateId);if(r===void 0)throw new Error(`notifications letters show: "${this.templateId}" is not a letter this school may reword \u2014 known: ${n.letters.map(i=>i.id).join(", ")}`);if(!this.json){let i=r.placeholders.map(o=>`{{${o.key}}}${o.required?" (Pflicht)":""}`).join(", ");this.context.stdout.write(`${r.label} \u2014 ${r.occasion.de}
|
|
11289
11289
|
Platzhalter: ${i||"\u2014"}
|
|
11290
11290
|
|
|
11291
|
-
`)}return this.print(r,i=>i.slots.map(o=>{let a=i.override?.[o.key];return{block:o.key,label:o.label,deviates:a===void 0?"":"yes",text:(a??o.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"]),0}},Bb=class extends D{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=f.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=j6(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new Error("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let n=await this.caller(),r=await n.mutation(x.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Wb(this.locale,"letters set"),slots:t});return this.print({templateId:this.templateId,submitted:Object.keys(t),...r},i=>[{key:"letter",value:i.templateId},{key:"submitted",value:i.submitted.join(", ")},{key:"deviating blocks",value:i.overriddenSlotKeys.join(", ")||"\u2014 (back to the platform text)"}]),0}},Ub=class extends D{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"Block key to reset (repeatable)"});all=f.Boolean("--all",!1,{description:"Reset every block of this letter"});async execute(){let t=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&t.length>0)throw new Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new Error("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let n=await this.caller(),r=await n.mutation(x.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Wb(this.locale,"letters reset"),...this.all?{}:{slotKeys:t}});return this.print({templateId:this.templateId,reset:this.all?"all":t.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Rd=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function am(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":Rd(t[r],""),...n===null?{}:{platform:Rd(n[r],"")}}))}s(am,"chromeTextRows");var Gb=class extends D{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let t=await this.caller(),n=await t.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(t)});return this.print(n,r=>[...am("greeting",r.greeting,r.defaults.greeting),...am("closing",r.closing,r.defaults.closing),{field:"senderName",school:Rd(r.senderName,"\u2014 (platform)"),platform:Rd(r.defaults.senderName,"")}],["field","school","platform"]),0}},zb=class extends D{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=f.String("--greeting-de",{description:"Opening line, German"});greetingEn=f.String("--greeting-en",{description:"Opening line, English"});closingDe=f.String("--closing-de",{description:"Sign-off, German"});closingEn=f.String("--closing-en",{description:"Sign-off, English"});senderName=f.String("--sender-name",{description:"Name the school signs with (empty string clears it)"});async execute(){let t=s((l,d,c)=>{if(!(d===void 0&&c===void 0)){if(d===void 0||c===void 0)throw new Error(`notifications chrome set: --${l}-de and --${l}-en go together \u2014 the frame is worded in every language`);return{de:d,en:c}}},"pair"),n=t("greeting",this.greetingDe,this.greetingEn),r=t("closing",this.closingDe,this.closingEn);if(n===void 0&&r===void 0&&this.senderName===void 0)throw new Error("notifications chrome set: nothing to change \u2014 pass --greeting-de/--greeting-en, --closing-de/--closing-en or --sender-name");let i=await this.caller(),o=this.requireTenant(i);await i.mutation(x.notifications.saveTenantChrome,{tenantSlug:o,...n!==void 0?{greeting:n}:{},...r!==void 0?{closing:r}:{},...this.senderName!==void 0?{senderName:this.senderName}:{}});let a=await i.query(x.notifications.getTenantChrome,{tenantSlug:o});return this.print(a,l=>[...am("greeting",l.greeting,null),...am("closing",l.closing,null),{field:"senderName",school:Rd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},OF=[Fb,Lb,Mb,qb,Kb,jb,Vb,Bb,Ub,Gb,zb];var B6="-stufe-",U6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Yb(e){return`${e}${B6}`}s(Yb,"stageKeyPrefix");function Hb(e,t){return`${Yb(e)}${t}`}s(Hb,"stageStorageKey");function NF(e,t){let n=Yb(e);return t.startsWith(n)&&t.length>n.length}s(NF,"isUnderProgram");function Kr(e,t){let n=Yb(e);return NF(e,t)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${t}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C). F\xFChren Sie die Stufe in bundle.yaml unter einem neuen Schl\xFCssel auf; der n\xE4chste Apply archiviert diese Zeile (hinter der Archivsperre) und legt die Stufe mit dem neuen Schl\xFCssel an.`,en:`[stage/foreignKey] The level key "${t}" is not under the program "${e}" (expected: "${n}<key>"). List the level in bundle.yaml under a new key; the next apply archives this row (behind the archive lock) and creates the level with the new key.`}),t.slice(n.length)}s(Kr,"bareStageKey");function lm(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=$t(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.stages[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"stage/nameMissing",index:i,message:{de:`[stage/nameMissing] ${l}: jede Klassenstufe braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[stage/nameMissing] ${l}: every stage needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"stage/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"stage/keyMissing",index:i,message:{de:`[stage/keyMissing] ${l}: jede Klassenstufe braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[stage/keyMissing] ${l}: every stage needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!U6.test(d)){t.push({code:"stage/keyInvalid",index:i,message:{de:`[stage/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[stage/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"stage/duplicateKey",index:i,message:{de:`[stage/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.stages[${c}] verwendet`,en:`[stage/duplicateKey] ${l}: key "${d}" is already used by program.stages[${c}]`}});return}n.set(d,i)}),t}s(lm,"stageSpecIssues");function _F(e){return{de:e.de.trim(),en:e.en.trim()}}s(_F,"trimmedText");function G6(e,t){let n=[];return e.de!==t.de&&n.push(`"${e.de}" \u2192 "${t.de}"`),e.en!==t.en&&n.push(`en "${e.en}" \u2192 "${t.en}"`),n.join(", ")}s(G6,"describeNameChange");function dm(e,t,n){if(e===null)return t.length>0&&F("planStageReconcile: stages exist but the offer has no program key"),n.map((a,l)=>({op:"insert",key:a.key,name:_F(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(t.map(a=>[a.key,a])),i=new Set,o=[];n.forEach(({name:a,...l},d)=>{let c={...l,name:_F(a)},u=Hb(e,c.key);i.add(u);let p=d+1,h=r.get(u);if(h===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:p});return}let w={};xs(h.name,c.name)||(w.name=[h.name,c.name]);let k=h.gradeLevel??null,y=c.gradeLevel??null;k!==y&&(w.gradeLevel=[k,y]),h.sequence!==p&&(w.sequence=[h.sequence,p]),(Object.keys(w).length>0||h.archived)&&o.push({op:"update",key:c.key,stageId:h.stageId,name:c.name,changes:w,unarchive:h.archived})});for(let a of[...t].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:NF(e,a.key)?Kr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(dm,"planStageReconcile");function cm(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let t=e.occupancy,n=[...t&&t.activeApplications>0?[`REFUSED: ${t.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...t&&t.openLeads>0?[`${t.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${n.length>0?` \u2014 ${n.join("; ")}`:""}`}case"update":{let t=[];if(e.unarchive&&t.push("restored"),e.changes.name&&t.push(G6(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[n,r]=e.changes.gradeLevel;t.push(`grade ${n??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&t.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${t.join(", ")})`}}}s(cm,"describeStageStep");var z6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function fi(e,t){return`${e}-${t}`}s(fi,"runStorageKey");function CF(e,t){typeof t!="string"&&ae("CONFLICT",{de:`[run/keyNotServed] Das Deployment liefert f\xFCr ein Schuljahr von \u201E${e}\u201C keinen Schl\xFCssel \u2014 es l\xE4uft ein \xE4lteres Release als die CLI. Nach dem n\xE4chsten Release erneut versuchen.`,en:`[run/keyNotServed] The deployment provides no key for a school year of "${e}" \u2014 it runs an older release than the CLI. Try again after the next release.`});let n=`${e}-`;return(!t.startsWith(n)||t.length===n.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${t}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C).`,en:`[run/foreignKey] The key "${t}" of the school year is not under the program "${e}" (expected: "${n}<key>").`}),t.slice(n.length)}s(CF,"bareRunKey");function um(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=$t(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.runs[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"run/nameMissing",index:i,message:{de:`[run/nameMissing] ${l}: jedes Schuljahr braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[run/nameMissing] ${l}: every run needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"run/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"run/keyMissing",index:i,message:{de:`[run/keyMissing] ${l}: jedes Schuljahr braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[run/keyMissing] ${l}: every run needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!z6.test(d)){t.push({code:"run/keyInvalid",index:i,message:{de:`[run/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[run/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"run/duplicateKey",index:i,message:{de:`[run/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.runs[${c}] verwendet`,en:`[run/duplicateKey] ${l}: key "${d}" is already used by program.runs[${c}]`}});return}n.set(d,i)}),t}s(um,"runSpecIssues");var W6={capacity:null,isOpen:!1},Y6={capacity:null,isOpen:!0};function H6(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(H6,"isCapacity");function fm(e,t){let n=[],r=t===void 0?void 0:new Set(t);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&n.push(`[capacity/runIsOpenWithCells] ${a}: \`isOpen\` on the run AND \`capacities\` \u2014 the open state lives on each cell; drop the run-level \`isOpen\``),i.capacities===null||typeof i.capacities!="object"||Array.isArray(i.capacities)){n.push(`[capacity/shape] ${a}: \`capacities\` must map stage keys to { isOpen, capacity }`);return}for(let[l,d]of Object.entries(i.capacities)){let c=`${a}.capacities.${l}`;r!==void 0&&!r.has(l)&&n.push(`[capacity/unknownStage] ${c}: no stage with key "${l}" in program.stages (have: ${[...r].join(", ")||"none"})`);let u=d;if(u===null||typeof u!="object"){n.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&n.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!H6(u.capacity))&&n.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),n}s(fm,"capacitySpecIssues");function DF(e,t,n={stageKeys:[],runKeys:[]}){let r=e.programKey,i=new Map;if(r!==null)for(let c of e.stages)c.archived||i.set(Kr(r,c.key),c.stageId);let o=new Set(n.stageKeys),a=new Set(n.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of t){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===fi(r,c.key));if(u===void 0&&!a.has(c.key))throw new Error(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[p,h]of Object.entries(c.capacities)){let w=i.get(p);if(w===void 0&&!o.has(p))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${p}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:h.capacity,isOpen:h.isOpen},y=u!==void 0&&w!==void 0?l.get(`${u.runId}|${w}`):void 0,v=y!==void 0?{capacity:y.capacity,isOpen:y.isOpen}:u===void 0?W6:Y6;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:v,to:k})}}return d}s(DF,"planRunCapacities");function PF(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(PF,"describeCell");function pm(e){return`~cap ${e.run}\xD7${e.stageKey} ${PF(e.from)} \u2192 ${PF(e.to)}`}s(pm,"describeCapacityStep");function FF(e){if(e.programKey===void 0)throw new Error("offer[admission]: the target backend predates stage keys \u2014 deploy it before running offer plan / apply / export with this CLI")}s(FF,"assertBackendHasStageKeys");async function Jb(e,t,n,r){let i=await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),o=i.stages.map(u=>({stageId:u.stageId,key:u.key,name:u.name,...u.gradeLevel!==void 0?{gradeLevel:u.gradeLevel}:{},sequence:u.sequence,archived:u.archived}));FF(i);let a=dm(i.programKey,o,r),l=a.flatMap(u=>u.op==="archive"?[u.stageId]:[]);if(l.length===0)return a;let d=await e.query(x.programAdmin.getStageOccupancy,{client:t,offerKey:n,stageIds:l}),c=new Map(d.map(u=>[u.stageId,u]));return a.map(u=>{if(u.op!=="archive")return u;let p=c.get(u.stageId);if(p===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:p.activeApplications,openLeads:p.openLeads}}})}s(Jb,"planStages");async function mm(e,t,n,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=n===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n});FF(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Kr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return DF(o,i,{stageKeys:l.filter(c=>!a.has(c)),runKeys:i.map(c=>c.key).filter(c=>d===null||!o.runs.some(u=>u.key===fi(d,c)))})}s(mm,"planCapacities");async function J6(e,t,n,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===fi(a,d)&&c.status==="archived"));if(l.length>0)throw new Error(`offer[admission]: run(s) ${l.map(d=>`"${d}"`).join(", ")} exist only ARCHIVED \u2014 restore with \`offer run restore --run <key>\` or drop the bundle entry`)}s(J6,"assertNoArchivedRunKey");var Qb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...lm(o??[]),...um(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(y=>y.message.de).join("; ")}`);let l=fm(n.program?.runs??[],o?.map(y=>y.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await J6(e,i,t,n);let d=await mm(e,i,t,n),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=Q6(n);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let p=c.units.find(y=>y.key===u);if(!p)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(y=>y.key===null?[]:[y.key]).join(", ")||"(none)"}`);let h=[];if(r.dryRun||(await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:i,unitId:p.unitId}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:p.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let y=await Jb(e,i,t,o);h.push(...y.map(cm))}else{let y=await e.mutation(x.programAdmin.reconcileProgramStages,{client:i,offerKey:t,stages:o.map(v=>({key:v.key,name:v.name,...v.gradeLevel!==void 0?{gradeLevel:v.gradeLevel}:{}}))});h.push(...y.steps,...y.warnings.map(v=>`warning ${v}`))}let w=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let y of n.program?.runs??[]){let v=w.programKey===null?void 0:w.runs.find(A=>A.key===fi(w.programKey,y.key));if(v!==void 0){xs(v.name,y.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:y.name}),h.push(`~run ${y.key} ("${Pe(v.name)}" \u2192 "${Pe(y.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:t,key:y.key,name:y.name,isOpen:y.capacities!==void 0?!1:y.isOpen??!0,...y.startDate?{startDate:y.startDate}:{},...y.endDate?{endDate:y.endDate}:{}}),h.push(`+run ${y.key} (${Pe(y.name)})`)}let k=r.dryRun?d:await mm(e,i,t,n);if(!r.dryRun&&k.length>0){let y=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=y.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of k){let E=y.runs.find(C=>C.key===fi(v,A.run))?.runId,I=y.stages.find(C=>Kr(v,C.key)===A.stageKey)?.stageId;if(E===void 0||I===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:E,stageId:I,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return h.push(...k.map(pm)),h.join(", ")}};function Q6(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(Q6,"bundleUnitKey");var LF={role:"control",effect:"pure",cardinality:"N-to-1"};var hm=["add","remove","replace"];function MF(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(MF,"roleAssignLiteral");var qF={role:"method",effect:"context-mutation",inputs:s(()=>[{id:"person",label:{de:"Person",en:"Person"},type:"personRef",required:!0},{id:"roleKey",label:{de:"Rolle",en:"Role"},type:"roleKey",required:!0,optionSource:"tenantRoles"},{id:"mode",label:{de:"Modus",en:"Mode"},type:"enum",defaultValue:"add",optionSource:"declared",enumOptions:[{value:"add",label:{de:"Rolle hinzuf\xFCgen",en:"Add role"}},{value:"remove",label:{de:"Rolle entziehen",en:"Remove role"}},{value:"replace",label:{de:"Alle Rollen ersetzen",en:"Replace all roles"}}]}],"inputs"),validate:s((e,t,n)=>{let r=[],i=MF(e,"roleKey")?.trim()??"",o=MF(e,"mode")??"add";return i===""?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/missingRoleKey] roleAssign-Knoten "${e.id}" nennt keine Rolle \u2014 welche Rolle vergeben wird, muss der Autor aus dem Rollenkatalog des Mandanten w\xE4hlen.`,en:`[roleAssign/missingRoleKey] roleAssign node "${e.id}" names no role \u2014 the author must choose which role is assigned from the school's role catalog.`},severity:"error"}):n?.roleKeys!==void 0&&!n.roleKeys.has(i)?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/unknownRoleKey] Rolle "${i}" existiert nicht im Rollenkatalog des Mandanten \u2014 der Knoten w\xFCrde bei jeder Ausf\xFChrung abbrechen. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[roleAssign/unknownRoleKey] Role "${i}" does not exist in the school's role catalog \u2014 the node would abort on every run. Known roles: ${[...n.roleKeys].sort().join(", ")}.`},severity:"error"}):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(i)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/nonLeafRoleKey] Rolle "${i}" hat untergeordnete Rollen und ist deshalb nicht vergebbar \u2014 eine Partei bekommt ein Blatt, keine Oberkategorie. Vergebbare Rollen: ${[...n.assignableRoleKeys].sort().join(", ")}.`,en:`[roleAssign/nonLeafRoleKey] Role "${i}" has sub-roles and therefore cannot be assigned \u2014 a party gets a leaf role, not a parent category. Assignable roles: ${[...n.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),hm.includes(o)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.mode`,reason:{de:`[roleAssign/unknownMode] roleAssign-Knoten "${e.id}" deklariert Modus "${o}" \u2014 erlaubt sind ${hm.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${hm.join(" | ")}.`},severity:"error"}),r},"validate")};var Z6=["event","effect","outcomes"],Zb=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),KF={outcomes:[{id:gr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of Z6)i in r&&n.push(Zb(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${gr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${gr}" itself.`));return Zn(t.nodes).some(i=>i.target===e.id)&&n.push(Zb(`nodes.${e.id}`,`[eventTrigger/notStart] Knoten "${e.id}" ist ein Start-Knoten, hat aber eine eingehende Kante \u2014 nur der Start l\xF6st ihn aus, jeder Vorgang bliebe hier stehen.`,`[eventTrigger/notStart] Node "${e.id}" is a start node but has an incoming edge \u2014 only the start triggers it, every process would stop here.`)),e.next?.[gr]===void 0&&n.push(Zb(`nodes.${e.id}.next.${gr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${gr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${gr}" nowhere.`)),n},"validate")};var X6="submit",jF=[{id:X6,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function VF(e){return e==="draft"}s(VF,"isWritableSmartFormState");var Xb=["draft","committed"],ARe=Xb.filter(e=>VF(e));async function BF(e,t,n){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",t).eq("formNodeId",n)).take(2);return r.length>1&&F(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(BF,"getSmartFormInstance");var UF="form:fill",ev="request:collectPayment",GF="request:collectPaymentSeparate",tv="confirmPayment";var e3={key:UF,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},zF={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},WF={[qR]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:zF,external:Ze(ne("Entwurf","Draft"),"neutral",ne("Bewerbung fortsetzen","Continue application"),ne("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),ne("Bewerbung fortsetzen","Continue application"),"continue-form")},[ef]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:zF,external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ne("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},YF={role:"user-action",effect:"side-effect",progressDefaults:WF,progressEvents:Ft(WF),actions:s(()=>jF,"actions"),workItemTemplates:s(()=>[e3],"workItemTemplates"),states:Xb,currentState:s(async(e,t)=>{let n=await BF(e,t.applicationId,t.node.id);return n===null?"draft":n.state},"currentState"),inputs:s(e=>[{id:"smartForm",label:{de:"Formular",en:"Form"},type:"smartForm",optionSource:"offerSmartForms",required:e.adoptForm===void 0,inspector:"literal-only"}],"inputs"),outputs:s(e=>[{name:"admission",type:"admission",label:{de:"Anmeldung",en:"Application"},schema:[{key:"beneficiary",type:"personRef",label:{de:"Beschulte Person",en:"Student"}},{key:"signers",type:"personList",label:{de:"Unterzeichner",en:"Signers"}},...e.formExports??[]]}],"outputs"),notificationEvents:s(e=>kn(e)?[]:[{id:tf,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[],n=e.inputs?.smartForm,r=n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0,i=e.adoptForm!==void 0;return r&&i?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.adoptForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" hat sowohl ein smartForm als auch adoptForm \u2014 genau eines ist erlaubt.`,en:`[form.adopt-xor-create] Form node "${e.id}" has both a smartForm and adoptForm \u2014 exactly one is allowed.`},severity:"error"}):!r&&!i&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.smartForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" braucht entweder ein smartForm (neu erzeugen) oder adoptForm (bestehende Instanz \xFCbernehmen).`,en:`[form.adopt-xor-create] Form node "${e.id}" needs either a smartForm (create new) or adoptForm (adopt an existing instance).`},severity:"error"}),t},"validate")};var HF={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Ot.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Ot.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Ot.value,label:{de:"Setzen oder zur\xFCcknehmen",en:"Raise or lower"},type:"boolean",defaultValue:!0,inspector:"literal-only",enumOptions:[{value:"true",label:{de:"Setzen",en:"Raise"}},{value:"false",label:{de:"Zur\xFCcknehmen",en:"Lower"}}]}],"inputs"),notificationEvents:s(e=>[{id:"unlocked",label:{de:"Abschnitt freigeschaltet",en:"Section unlocked"},audience:"external",required:sO(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Ot.flagKey]?.kind==="literal"&&bf(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ot.flagKey}`,reason:{de:`[setFlag/missingFlagKey] setFlag-Knoten "${e.id}" nennt kein Merkmal (Parameter \u201EMerkmal im Formular\u201C).`,en:`[setFlag/missingFlagKey] setFlag node "${e.id}" names no flag (parameter "Flag in the form").`},severity:"error"});let r=e.inputs?.[Ot.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ot.value}`,reason:{de:`[setFlag/valueType] setFlag-Knoten "${e.id}": \u201ESetzen oder zur\xFCcknehmen\u201C ist ein Ja/Nein-Wert (true/false), kein Text.`,en:`[setFlag/valueType] setFlag node "${e.id}": "Raise or lower" is a yes/no value (true/false), not text.`},severity:"error"}),t},"validate")};var t3="true",n3="false",nv=[{id:t3,label:{de:"Ja",en:"Yes"}},{id:n3,label:{de:"Nein",en:"No"}}];var JF={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:nv,validate:s((e,t,n)=>r3(e,t,n),"validate")};function r3(e,t,n){let r=s(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${o.de}`,en:`[if/condition] Node "${e.id}": ${o.en}`},severity:"error"}),"issue"),i=nv.filter(o=>e.next?.[o.id]===void 0).map(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${o.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${o.label.de}\u201C (${o.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${o.label.en}" (${o.id}) leads nowhere.`},severity:"error"}));return typeof e.condition!="string"||e.condition.trim()===""?[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})]:[...i,...Xf(e.condition,eI(t),n).map(r)]}s(r3,"ifNodeIssues");var Sa="decision",i3=new Set(["decision","review"]),YRe=new Set([...i3,"governedDocument"]);var ZF=[{id:"approved",label:{de:"Freigeben",en:"Approve"},semantic:"granted"},{id:"rejected",label:{de:"Ablehnen",en:"Reject"},semantic:"rejected"},{id:"waitlisted",label:{de:"Auf Warteliste",en:"Waitlist"},semantic:"waitlisted"}],QF={released:{label:ne("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ne("Freigabe","Release"),scope:"node"},external:Ze(ne("Freigegeben","Released"),"green",ne("Ihre Bewerbung wurde freigegeben","Your application has been released"),ne("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Yo={role:"user-action",effect:"side-effect",outcomes:ZF,progressDefaults:QF,progressEvents:Ft(QF),notificationEvents:s(e=>(e.outcomes??[]).map(t=>({id:t.id,label:t.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(t=>({id:t.id,kind:"advance",outcome:t.id,label:t.label,...Ii(t.semantic)?{semantic:t.semantic}:{}})),...NN(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:Sa,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(t=>t.id).filter(t=>typeof t=="string"&&t.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,t)=>t===Sa&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),taskFormView:s((e,t)=>t===Sa?e.formView:void 0,"taskFormView"),validate:rv};function rv(e,t,n){let r=[],i=e.outcomes??[];i.length===0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[decision/missingOutcomes] Entscheidungs-Knoten "${e.id}" hat keine Outcomes \u2014 die Entscheidung w\xE4re niemals aufl\xF6sbar.`,en:`[decision/missingOutcomes] Decision node "${e.id}" has no outcomes \u2014 the decision could never be resolved.`},severity:"error"});let o=new Set(i.map(l=>l.id));for(let l of i){let d=l.label;(typeof d=="string"?d.trim().length>0:d!=null&&typeof d=="object"&&Object.values(d).some(p=>typeof p=="string"&&p.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}`,reason:{de:`[decision/outcomeMissingLabel] Outcome "${l.id}" von "${e.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,en:`[decision/outcomeMissingLabel] Outcome "${l.id}" of "${e.id}" has no label \u2014 it is the text of the button in the cockpit.`},severity:"error"});let u=l.semantic;u===void 0?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticMissing] Outcome "${l.id}" von "${e.id}" sagt nicht, was es bedeutet \u2014 eines von ${wn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${wn.join(", ")}.`},severity:"error"}):Ii(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" von "${e.id}" hat die Bedeutung "${String(u)}" \u2014 erlaubt: ${wn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${wn.join(", ")}.`},severity:"error"})}for(let l of Object.keys(e.commentRequired??{}))o.has(l)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.commentRequired.${l}`,reason:{de:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${l}" in commentRequired; erlaubt: ${[...o].join(", ")}`,en:`[decision/commentRequiredUnknownOutcome] Unknown outcome "${l}" in commentRequired; allowed: ${[...o].join(", ")}`},severity:"error"});let a=e.decisionAsTask?.title;return a!==void 0&&(a!==null&&typeof a=="object"&&Object.values(a).some(d=>typeof d=="string"&&d.length>0)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.decisionAsTask.title`,reason:{de:"[decision/decisionTaskMissingTitle] decisionAsTask.title ist gesetzt, aber leer \u2014 entweder einen nicht-leeren lokalisierten Text angeben oder das Feld weglassen (dann greift der Standardtitel).",en:"[decision/decisionTaskMissingTitle] decisionAsTask.title is set but empty \u2014 either give a non-empty localized text or omit the field (the default title then applies)."},severity:"error"})),r}s(rv,"validateDecisionNode");var iv=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],XF=[{id:"complete",label:{de:"Vollst\xE4ndig",en:"Complete"}},{id:"acceptedIncomplete",label:{de:"Ohne Nachreichung abgeschlossen",en:"Closed without the missing documents"}},{id:"rejected",label:{de:"Abgelehnt",en:"Rejected"}},{id:"absage",label:{de:"Zur\xFCckgezogen",en:"Withdrawn"}}];var ov="promoted";var eL="promote",tL="Nachr\xFCcken";var sv={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},nL={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:sv,external:Ze(ne("Warteliste","Waiting list"),"amber",ne("Sie stehen auf der Warteliste","You are on the waiting list"),ne("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:ne("Nachger\xFCckt","Promoted"),tone:"green",phase:sv,external:Ze(ne("Nachger\xFCckt","Moved up"),"green",ne("Sie sind nachger\xFCckt","You have moved up"),ne("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ne("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:sv,external:Ze(ne("Warteliste geschlossen","Waiting list closed"),"red",ne("Die Warteliste wurde geschlossen","The waiting list has been closed"),ne("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},rL={outcomes:iv,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Hn.map(e=>({value:e,label:fI[e]}))}],"inputs"),validate:s((e,t)=>{let n=ly(e);if(n===null)return[];let r=t.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=t.nodes.indexOf(e);for(let o of r){if(t.nodes.indexOf(o)>i)continue;let a=ly(o);if(a!==null&&a.waitlistOrder!==n.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different orders \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:nL,progressEvents:Ft(nL),notificationEvents:s(()=>[{id:"placed",label:{de:"Auf die Warteliste gesetzt",en:"Placed on the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]},{id:"promoted",label:{de:"Nachger\xFCckt",en:"Promoted from the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]}],"notificationEvents"),actions:s(e=>(e.outcomes!==void 0&&e.outcomes.length>0?e.outcomes:iv).some(n=>n.id===ov)?[{id:eL,kind:"advance",outcome:ov,semantic:"other",label:{de:tL,en:"Promote from waitlist"},surface:Xn,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var av="complete",Id="acceptedIncomplete",gm="rejected",o3="absage",iL="closeWithoutDocuments",oL="rejectAtCompleteness",sL="Ohne Nachreichung abschlie\xDFen",aL="Ablehnen",lL="awaitingDocuments",lv="documentsComplete",dv="closedWithoutDocuments",cv="rejected",uv="withdrawn",dL="requested",hIe={[av]:{event:lv,status:"complete",endsRole:!0},[Id]:{event:dv,status:"acceptedIncomplete",endsRole:!1},[gm]:{event:cv,status:"rejected",endsRole:!0},[o3]:{event:uv,status:"withdrawn",endsRole:!0}};var Od=s(()=>xl[0],"beneficiary"),fv=366;function s3(e){let t=e.reads,n=Sl(e).flatMap(({address:r})=>ct(r)&&!xl.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(ct):[],...n]}s(s3,"printedFields");function a3(e,t){let n=pe(t);return e.nodes.filter(r=>r.type==="governedDocument"&&s3(r).some(i=>pe(i)===n))}s(a3,"documentsPrinting");function l3(e,t){if(!ct(t)||t.path!==Od())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!kn(n)}s(l3,"isCreatedFormBeneficiary");function Lt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Lt,"issue");function d3(e,t,n){let r=new Map(e.nodes.map(l=>[l.id,l])),i=t.next??{},o=new Set,a=[av,Id].flatMap(l=>{let d=i[l]?.to;return d===void 0?[]:[d]});for(;a.length>0;){let l=a.pop();if(o.has(l))continue;o.add(l);let d=r.get(l);if(d!==void 0&&!(d.type==="review"&&xe(d.form)&&wr(d.form)&&d.form.owner===n)){if(d.type==="end"){if(To(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(d3,"reachesApprovedEndUnreviewed");var pv={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},cL={[lL]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:pv,external:Ze(ne("Unterlagen fehlen","Documents missing"),"amber",ne("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ne("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[lv]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:pv,external:Ze(ne("Unterlagen vollst\xE4ndig","Documents complete"),"green",ne("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ne("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[dv]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:pv,external:Ze(ne("Abgeschlossen","Closed"),"neutral",ne("Die Nachreichung ist abgeschlossen","The document request is closed"),ne("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[cv]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:UO,external:Ze(ne("Abgelehnt","Rejected"),"red",ne("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ne("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[uv]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:Pf,external:Ze(ne("Zur\xFCckgezogen","Withdrawn"),"red",ne("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ne("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},uL={outcomes:XF,progressDefaults:cL,progressEvents:Ft(cL),notificationEvents:s(()=>[{id:dL,label:{de:"Unterlagen angefordert",en:"Documents requested"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"fieldLabels",type:"localizedText",required:!0},{key:"dueAt",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=s(r=>e.next?.[r]!==void 0,"wired"),n=[];return t(Id)&&n.push({id:iL,kind:"advance",outcome:Id,semantic:"other",label:{de:sL,en:"Close without documents"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Es geht ohne die fehlenden Unterlagen weiter. Die Anfrage an die Familie wird geschlossen.",en:"The application continues without the missing documents. The request to the family is closed."},confirmLabel:{de:"Abschlie\xDFen",en:"Close"}}}),t(gm)&&n.push({id:oL,kind:"advance",outcome:gm,semantic:"rejected",label:{de:aL,en:"Reject application"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Der Platz wird abgesagt und die Anfrage an die Familie geschlossen. Das l\xE4sst sich nicht r\xFCckg\xE4ngig machen.",en:"The application is rejected and the request to the family is closed. This cannot be undone."},confirmLabel:{de:"Ablehnen",en:"Reject"}}}),n},"actions"),inputs:s(()=>[{id:"person",label:{de:"Person (Gasth\xF6rer-Rolle)",en:"Person (guest role)"},type:"personRef",required:!1},{id:"guestRole",label:{de:"Gastrolle bis zur Nachreichung",en:"Guest role until submitted"},type:"roleKey",required:!1,inspector:"literal-only",optionSource:"tenantRoles"}],"inputs"),validate:s((e,t,n)=>{let r=[],i=`Vollst\xE4ndigkeitspr\xFCfung \u201E${e.label?.de??e.id}\u201C (${e.id})`,o=`Completeness check "${e.label?.en||e.id}" (${e.id})`,a=s(A=>je(t,A,"de"),"shown"),l=s(A=>je(t,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Lt(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let E of d){if(!xe(E))continue;let I=pe(E);if(A.has(I)){r.push(Lt(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(E)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(E)} appears twice in \`requires\`.`}));continue}if(A.add(I),!ct(E)){r.push(Lt(e,"requires",{de:`[completenessCheck/unknownField] ${a(E)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(E)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let C=ni(n,E);if(C==null)continue;let $=Vs("requires",js(C));$==="computed"||$==="repeated"?r.push(Lt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(E)} ist ${C.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(E)} is ${C.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):$==="untranslated"&&r.push(Lt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(E)} (\u201E${Fi(C,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(E)} ("${Fi(C,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},p="inDays"in u,h="until"in u;if(p===h)r.push(Lt(e,"deadline",{de:`[completenessCheck/deadlineShape] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" braucht genau eine Frist: \`{ inDays: n }\` (Tage ab Eintritt) oder \`{ until: "JJJJ-MM-TT" }\`.`,en:`[completenessCheck/deadlineShape] Completeness check "${e.id}" needs exactly one deadline: \`{ inDays: n }\` (days after entry) or \`{ until: "YYYY-MM-DD" }\`.`}));else if(p){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>fv)&&r.push(Lt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${fv} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${fv} days.`}))}else typeof u.until!="string"||Yy(u.until)===null?r.push(Lt(e,"deadline.until",{de:`[completenessCheck/deadlineDate] Frist "${String(u.until)}" ist kein g\xFCltiges Datum (JJJJ-MM-TT).`,en:`[completenessCheck/deadlineDate] Deadline "${String(u.until)}" is not a valid date (YYYY-MM-DD).`})):u.until<l_(Date.now())&&r.push({...Lt(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(ct).map(E=>[pe(E),E]));for(let E of A.values())for(let I of a3(t,E))r.push(Lt(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(E)} flie\xDFt in das Dokument \u201E${I.label?.de??I.id}" (${I.id}) ein \u2014 nach dessen Ausstellung kann die Familie es nicht mehr nachreichen. Feld aus \`requires\` oder aus dem Dokument nehmen.`,en:`[completenessCheck/requiresConsumedUpstream] Field ${l(E)} flows into the document "${I.label?.en||I.id}" (${I.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}if(Array.isArray(d)&&n!==void 0){let A=d.filter(ct).filter(C=>{let $=ni(n,C);return $!=null&&ep($)}),I=[...new Set(A.map(C=>C.owner))].filter(C=>d3(t,e,C));if(I.length>0){let C=A.filter($=>I.includes($.owner));r.push({...Lt(e,"next",{de:`[review/unreviewedAfterSupply] ${C.map(a).join(", ")} ist pr\xFCfpflichtig und wird hier nachgereicht, aber nach \u201Evollst\xE4ndig\u201C oder \u201Eohne Nachreichung\u201C f\xFChrt ein Weg ohne Pr\xFCfknoten dieses Formulars zur Aufnahme \u2014 niemand pr\xFCft das Nachgereichte. Dort einen Pr\xFCfknoten einf\xFCgen (z. B. \u201EWenn nichts zu pr\xFCfen ist: Durchreichen\u201C).`,en:`[review/unreviewedAfterSupply] ${C.map(l).join(", ")} requires review and is supplied here, but after "complete" or "accepted incomplete" a path without a review node of this form leads to admission \u2014 nobody reviews what was supplied. Insert a review node there (e.g. "When nothing is owed: pass through").`}),severity:"warning"})}}let w=e.inputs?.guestRole,k=w?.kind==="literal"?w.value:void 0,y=e.inputs?.person,v=y?.kind==="binding"?y.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Lt(e,"inputs.guestRole",{de:"[completenessCheck/guestRoleEmpty] `guestRole` ist leer \u2014 Rollenschl\xFCssel angeben oder das Feld weglassen.",en:"[completenessCheck/guestRoleEmpty] `guestRole` is empty \u2014 give a role key or omit the field."})):n?.roleKeys!==void 0&&!n.roleKeys.has(k)?r.push(Lt(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(k)&&r.push(Lt(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${k}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${k}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Lt(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${en}.${Od()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${en}.${Od()}).`}))),xe(v)&&!l3(t,v)&&r.push(Lt(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(v)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${en}.${Od()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(v)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${en}.${Od()}).`})),v!==null&&k===void 0&&r.push(Lt(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Lt(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var c3=[{id:mI,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],ym=s(e=>e,"asDecision"),fL={[hI]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ne("In Pr\xFCfung","In review"),scope:"node"},external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ne("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},pL={role:"user-action",effect:"side-effect",outcomes:c3,progressDefaults:fL,progressEvents:Ft(fL),notificationEvents:s(e=>Yo.notificationEvents(ym(e)),"notificationEvents"),inputs:s(()=>[{id:tr,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Mo.map(e=>({value:e,label:IC[e]}))}],"inputs"),actions:s(e=>[...Yo.actions(ym(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:uy,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Yo.optionalActionKinds,workItemTemplates:s(e=>Yo.workItemTemplates(ym(e)).map(t=>t.key===Sa?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,uy]}:t),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,t,n)=>{let r=rv(ym(e),t,n);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!hf.includes(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${c.id}" mit der Bedeutung "${String(u)}" \u2014 eine Pr\xFCfung lehnt nicht ab und setzt nicht auf die Warteliste; das ist die Entscheidung der Freigabe bzw. \u201EBewerbung ablehnen".`,en:`[review/rejectingOutcome] Review node "${e.id}" declares the outcome "${c.id}" meaning "${String(u)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}let i={de:`\u201E${e.label?.de??e.id}\u201C (${e.id})`,en:`"${e.label?.en||e.id}" (${e.id})`},o=e.inputs?.[tr],a=OC(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${tr}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Mo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Mo.join(" or ")}.`},severity:"error"});let l=a==="advance",d=e.form;if(l&&d===void 0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:{de:`[review/advanceNeedsForm] Pr\xFCf-Knoten ${i.de} reicht durch, wenn nichts zu pr\xFCfen ist, nennt aber kein Formular \u2014 er w\xFCrde immer durchreichen. Nenne das Formular, dessen pr\xFCfpflichtige Felder er pr\xFCft.`,en:`[review/advanceNeedsForm] Review node ${i.en} passes through when nothing is owed but names no form \u2014 it would always pass through. Name the form whose review-required fields it checks.`},severity:"error"}),l&&(e.outcomes??[]).length!==1&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/advanceOneOutcome] Pr\xFCf-Knoten ${i.de} reicht durch, hat aber ${(e.outcomes??[]).length} Outcomes \u2014 durchgereicht wird \xFCber genau eines.`,en:`[review/advanceOneOutcome] Review node ${i.en} passes through but has ${(e.outcomes??[]).length} outcomes \u2014 it passes through over exactly one.`},severity:"error"}),xe(d)&&wr(d)){let c=n?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(ep)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${pe(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt w\xFCrde jedes Mal durchreichen. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${pe(d)}, but that form declares no field review-required \u2014 the step would pass through every time. Mark the fields "Review required" in the form.`}:{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${pe(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt wartet, ohne dass etwas abzuhaken ist. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${pe(d)}, but that form declares no field review-required \u2014 the step waits with nothing to tick. Mark the fields "Review required" in the form.`},severity:l?"error":"warning"})}return r},"validate")};var mL=["awaitingAnswer","answered"];async function hL(e,t){return(await Nl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(hL,"externalRequestState");var wL=[{id:Ao,label:{de:"Bezahlt",en:"Paid"}}],XIe=new Set(wL.map(e=>e.id));var u3=Ao,gL=[{id:u3,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],f3={id:My,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:Xn,confirm:{title:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},body:{de:"Die Geb\xFChr ist au\xDFerhalb von Plexus eingegangen. Der Schritt wird als separat bezahlt abgeschlossen, die Aufgabe der Familie schlie\xDFt mit.",en:"The fee was received outside Plexus. The step is completed as paid separately; the family's task closes with it."},confirmLabel:{de:"Best\xE4tigen",en:"Confirm"}}},p3={id:Ly,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Zahlung \xFCberspringen",en:"Skip payment"},body:{de:"Die Geb\xFChr wird au\xDFerhalb von Plexus abgerechnet. Der Schritt wird ohne Zahlung abgeschlossen; es wird kein Betrag als bezahlt verbucht.",en:"The fee is billed outside Plexus. The step is completed without a payment; no amount is recorded as paid."},confirmLabel:{de:"\xDCberspringen",en:"Skip"}}},m3={id:Ly,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Xn,superUserOnly:!0,availableIn:["awaitingAnswer"],confirm:{title:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},body:{de:"Die Familie hat nicht online \xFCber Plexus bezahlt. Der Schritt wird ohne Online-Zahlung abgeschlossen; eine offene Zahlungsseite wird geschlossen. Bitte den Grund angeben (z. B. bar bezahlt).",en:"The family did not pay online through Plexus. The step is completed without an online payment; an open payment page is closed. Please give the reason (e.g. paid in cash)."},confirmLabel:{de:"Abschlie\xDFen",en:"Complete"}},commentRequired:!0};function mv(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(mv,"literalOf");function Ho(e){let t=mv(e,Jn);return Af(t)?t:null}s(Ho,"settlementOrNull");function h3(e){let t=mv(e,Pi);return typeof t=="string"&&t.length>0?t:null}s(h3,"articleKeyOrNull");function g3(e){let t=mv(e,Qn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(g3,"payeeKeyOrNull");var y3={id:Pi,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},w3={id:Jn,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},k3={id:Di,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},b3={id:Qn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function v3(e){return[y3,w3,...Ho(e)==="online"?[b3]:[],k3]}s(v3,"collectPaymentInputs");var x3=["amount","currency","settlement"],S3={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},A3={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function E3(e,t){if(Ho(e)!=="online")return[];let n=g3(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Qn}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return t?.traeger!==void 0&&!t.traeger.has(n)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${n}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${n}" is not a legal entity of this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})]:t?.stripeReadyTraegerKeys!==void 0&&!t.stripeReadyTraegerKeys.has(n)?[i({de:`[collectPayment/onlineWithoutStripe] Abrechnung \u201Eonline" an \u201E${n}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${n}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "online" to "${n}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${n}") \u2014 otherwise no family can pay. Until then, choose "separate".`})]:[]}s(E3,"payeeIssues");var yL={awaitingPayment:{label:ne("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ne("Zahlung","Payment"),scope:"node"},external:Ze(ne("Zahlung offen","Payment due"),"amber",ne("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ne("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},kL={outputs:s(()=>[{name:HI,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>v3(e),"inputs"),outcomes:wL,progressDefaults:yL,progressEvents:Ft(yL),notificationEvents:s(e=>Ho(e)!=="online"?[]:[{id:"requested",label:{de:"Zahlung angefordert",en:"Payment requested"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"amount",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=Ho(e);return t==="online"?[...gL,m3]:t==="separate"?[f3,p3]:[]},"actions"),states:mL,currentState:s((e,t)=>hL(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:ev}),"currentState"),workItemTemplates:s(e=>{let t=e,n=Ho(t);return n==="separate"?[{key:tv,recipient:"internal",title:S3,unlocks:[My],advancesNode:!0},{key:GF,recipient:"external",title:A3,unlocks:[],informational:!0,advancesNode:!1}]:n!=="online"?[]:[{key:ev,recipient:"external",title:t.label,unlocks:gL.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,t,n)=>{let r=[],i=s((d,c)=>r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${d}`,reason:c,severity:"error"}),"push");for(let d of x3)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});if(r.push(...E3(e,n)),Ho(e)==="separate"){let d=e.assign?.[tv];(typeof d!="string"||d.length===0)&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird separat abgerechnet, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is billed separately, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."})}Ho(e)===null&&i(`inputs.${Jn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Ms.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Jn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Ms.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Jn])}.`});let o=e.inputs?.[Di];if(o?.kind==="literal"){let d=Sf(o.value);d!==null&&i(`inputs.${Di}`,{de:`[collectPayment/reasonText] Der Hinweis f\xFCr die Familie braucht einen Text auf Deutsch und auf Englisch (${d}).`,en:`[collectPayment/reasonText] The note for the family needs a text in German and in English (${d}).`})}let a=h3(e);if(a===null)return i(`inputs.${Pi}`,{de:'[collectPayment/missingArticle] Der Zahlungsknoten nennt keinen Artikel \u2014 unter \u201EParameter" einen einmaligen Artikel des Programms w\xE4hlen (Finanzen \u2192 Artikel).',en:'[collectPayment/missingArticle] The payment node names no article \u2014 under "Parameters" choose a one-time article of the program (Finance \u2192 Articles).'}),r;let l=`inputs.${Pi}`;return n?.billingItemKeys!==void 0&&!n.billingItemKeys.has(a)?(i(l,{de:`[collectPayment/unknownArticle] Artikel \u201E${a}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel.`,en:`[collectPayment/unknownArticle] Article "${a}" \u2014 no article of this school has this key.`}),r):(n?.oneTimeBillingItemKeys!==void 0&&!n.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${qy.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${qy.join(", ")}.`}),n?.offerProgram===null?i(l,{de:"[collectPayment/articleOfferWithoutProgram] Das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.",en:"[collectPayment/articleOfferWithoutProgram] The offer is not assigned to a program, so no article belongs to it; give the offer a program."}):n?.offerProgram?.directBillingItemKeys!==void 0&&!n.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${n.offerProgram.nameDe}" des Angebots nicht direkt zugeordnet \u2014 unter Finanzen \u2192 Artikel zuordnen (ein Paket z\xE4hlt nicht: es kann den Artikel anders bepreisen).`,en:`[collectPayment/articleNotInProgram] Article "${a}" is not directly assigned to the offer's program "${n.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function bL(e){return{de:`[governedDocument/localeFieldMissing] Die Vorlage "${e}" nennt kein Sprachfeld \u2014 ein Schreiben entsteht in genau einer Sprache. Ein Pflicht-Auswahlfeld mit den Optionen de/en unter den Parametern der Vorlage anlegen, es als localeField der Vorlage nennen und im Knoten an die Sprache des Benutzerkontos binden ($env.applicant.language); die Word-Datei h\xE4lt je Sprache einen Abschnitt <<#input.<feld>.de>> \u2026 <</input.<feld>.de>>.`,en:`[governedDocument/localeFieldMissing] The template "${e}" names no language field \u2014 a letter is written in exactly one language. Create a required choice field with the options de/en among the template's parameters, name it as the template's localeField and bind it in the node to the language of the user account ($env.applicant.language); the Word file holds one section per language <<#input.<field>.de>> \u2026 <</input.<field>.de>>.`}}s(bL,"localeFieldMissingText");var hv=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),vL=/^[a-z][a-z0-9_]*$/;function xL(e,t){let n=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${t}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${t}" declares no parameters \u2014 expected { fields } (the placeholders input.<key> a node fills).`}}];let i=r,o=new Set;for(let a of i){if(typeof a?.key!="string"||!vL.test(a.key)||o.has(a.key)){n.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${t}" ist ${o.has(a?.key)?"doppelt":"kein g\xFCltiger Schl\xFCssel"} \u2014 erlaubt sind eindeutige Kleinbuchstaben, Ziffern und _ (gedruckt als input.<schl\xFCssel>).`,en:`[governedDocument/templateFieldKey] Field "${String(a?.key)}" of the template "${t}" is ${o.has(a?.key)?"duplicated":"not a valid key"} \u2014 allowed are unique lower-case letters, digits and _ (printed as input.<key>).`}});continue}o.add(a.key);let l=`fields.${a.key}`;if(!Ci(a.type)){n.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${t}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Ls.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${t}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${Ls.join(", ")}).`}});continue}if(hv.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...hv].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...hv].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!vL.test(String(d.value)))&&n.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${t}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${t}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&n.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${t}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${t}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${t}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${t}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?n.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Brief aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a letter from a template is not countersigned.`}}):a.processSource!==void 0&&!up.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${up.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${up.join(", ")}.`}})}return n.push(...T3(e,t)),n}s(xL,"templateParameterIssues");function T3(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:bL(t)}];let n=e.fields.find(i=>i.key===e.localeField),r=n===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:n.type!=="enum"?{de:`ist ${n.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${n.type}, a select field (enum) is expected`}:n.required!==!0?{de:"ist kein Pflichtfeld \u2014 ohne Sprache gibt es keine Variante",en:"is not a required field \u2014 without a language there is no variant"}:(n.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(n.options??[]).some(i=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${t}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${t}" ${r.en}.`}}]}s(T3,"localeFieldIssues");function SL(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(SL,"applyTemplateStamp");var gv=50;async function wm(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(gv+1);return n.length>gv&&F(`signing_returns: Vorgang ${t} has more than ${gv} returns`),n}s(wm,"returnsOf");var yv=50;async function wv(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(yv+1);return n.length>yv&&F(`signing_returns: return ${t} has more than ${yv} files`),n.length===0&&F(`[signing/noDocument] return ${t} carries no file`),n}s(wv,"returnDocumentsOf");async function AL(e,t){let n=await wv(e,t);return n.length!==1&&F(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(AL,"soleReturnDocumentOf");var km=200,yOe=km*20;async function $3(e,t){let n=await e.db.get(t);return n===null&&F(`[process] application ${t} not found`),n.redactedAt!==void 0}s($3,"processRedacted");async function kv(e,t){await $3(e,t)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(kv,"assertProcessReadable");function R3(e){let t={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...t,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...t,scope:"node",result:e.result}}s(R3,"rowOf");async function EL(e,t,n){await kv(e,t);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",t).eq("scope",n.scope).eq("owner",n.owner).eq("key",n.key)).order("desc").take(km+1);return r.length>km&&F(`[process] application ${t} has more than ${km} results of ${n.scope}.${n.owner}.${n.key}`),r.map(R3)}s(EL,"storeHistory");async function I3(e,t,n){if(n.key===en){await kv(e,t);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",t).eq("formNodeId",n.owner)).unique();return i===null||i.state!=="committed"?{state:"pending",reason:null}:{state:"present",result:{kind:"ref",ref:{kind:"form",formInstanceId:i._id}},row:null}}let[r]=await EL(e,t,{scope:"node",owner:n.owner,key:n.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(I3,"nodeResultAt");async function bm(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return O3(await I3(e,t.applicationId,n),n,t.applicationId)}s(bm,"readOwnResult");function O3(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${pe(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(O3,"refOf");var bv={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},_3=Object.keys(bv),N3=_3.filter(e=>bv[e]==="open"),TOe=N3.filter(e=>e!=="pending");function TL(e){return bv[e]==="terminal"}s(TL,"isTerminalSigningStatus");var Ui=["docusign","insign"];var _d={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var P3=TL;function RL(e){return!P3(e.status)&&e.voidRequestedAt===void 0}s(RL,"holdsContract");async function IL(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(IL,"traegerLegalEntityOfParty");async function D3(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(D3,"isOrganizationParty");async function OL(e,t){return await IL(e,t)!==null?"traeger":await D3(e,t)?"organization":"person"}s(OL,"signerKindOf");async function _L(e,t){t.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await F3(e,n.partyId)==="family")return"family";return"traeger"}s(_L,"signingSideOf");async function F3(e,t){return await OL(e,t)==="traeger"?"traeger":"family"}s(F3,"sideOfParty");var c_e=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),CL=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var vv=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),vm=m.object({period:vv,anchorDate:m.string()});var h_e=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),g_e=m.union(m.literal("line"),m.literal("aggregate")),xm=m.record(m.string(),m.string());var L3=m.union(m.literal("active"),m.literal("ended")),xv=m.union(m.object({mode:m.literal("track")}),m.object({mode:m.literal("pin"),billingItemVersionId:Ve.restrict(m.id("billing_item_versions"),{unindexed:"pinned price version inside the pricing union"})}),m.object({mode:m.literal("override"),amount:m.number()})),M3=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),q3={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:xv,pricingSelections:m.optional(xm),paymentSchedule:m.optional(vm),resolvedSnapshot:m.any(),feeGroup:m.optional(CL),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},K3={...q3,period:M3,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:L3,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},A_e=_n(K3).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var br=m.union(m.string(),m.null()),PL=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),j3=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string(),representative:m.optional(m.object({userId:m.id("users"),nameAtSigning:m.string(),email:m.string()}))}),DL=m.object({sourceAllocationId:m.id("payer_allocations"),scope:m.union(m.object({kind:m.literal("contract")}),m.object({kind:m.literal("contract_line"),contractLineId:m.id("contract_lines")})),payer:m.union(m.object({kind:m.literal("party"),partyId:m.id("parties"),nameAtSigning:m.string()}),m.object({kind:m.literal("payment_method"),paymentMethodId:m.id("payment_methods"),label:m.string(),ownersAtSigning:m.array(PL)})),sharePct:m.union(m.number(),m.null()),flatAmount:m.union(m.number(),m.null()),cap:m.union(m.number(),m.null()),activeFrom:m.string(),activeTo:br}),FL=m.object({sourceAppliedGrantId:m.string(),sourceGrantTemplateId:m.union(m.string(),m.null()),name:m.string(),reason:m.string(),kind:m.string(),value:m.number(),rule:m.optional(m.any()),scope:m.optional(m.union(m.literal("line"),m.literal("aggregate"))),floorTotal:m.optional(m.number()),pricePeriod:m.optional(vv),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:br,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),V3={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:br,pricing:xv,paymentSchedule:m.optional(vm),pricingSelections:m.optional(xm),billingItemDefinition:m.object({sourceBillingItemDefinitionId:m.id("billing_item_definitions"),name:m.string(),itemType:m.string(),configOpaque:m.any()}),resolvedSnapshotOpaque:m.any(),enrolment:m.union(m.object({sourceEnrolmentId:m.id("enrollments"),status:m.string(),startDate:br,endDate:br,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:br,programName:br,runName:br,groupName:br}),m.null()),grants:m.array(FL),payerAllocations:m.array(DL)},B3=m.object({...V3,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:br,sourceValidTo:br})}),U3=m.object({formatVersion:m.literal(2),contract:m.object({scope:m.string(),generator:m.object({sourceGeneratorDefinitionId:m.id("contract_generator_definitions"),sourceCreationTime:m.number(),name:m.string(),bodyOpaque:m.any()})}),parties:m.array(PL),declaredSigners:m.array(j3),payerAllocations:m.array(DL),aggregateGrants:m.optional(m.array(FL)),lines:m.array(B3)}),G3=U3;var z3=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),W3=m.object({pageCount:m.number(),spots:m.array(m.object({signer:m.union(m.object({kind:m.literal("party"),role:m.string(),ordinal:m.union(m.number(),m.null())}),m.object({kind:m.literal("named"),label:Bi})),caption:m.string(),page:m.number(),box:z3}))});var Y3=m.object({storageId:Ve.holds(m.id("_storage")),sourceArtifactId:m.optional(Ve.history(m.id("admission_documents"))),sha256:m.string(),mimeType:m.optional(m.string()),sizeBytes:m.optional(m.number()),filename:m.string(),source:m.union(m.object({kind:m.literal("uploaded")}),m.object({kind:m.literal("machine_rendered"),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),signaturePlacement:m.optional(W3)}))}),H3=m.object({storageId:Ve.holds(m.id("_storage")),sha256:m.string(),filename:m.string(),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),confirmationRequired:m.boolean()}),J3={importedTemplateSource:m.optional(m.object({id:m.string(),creationTime:m.number()})),tenantId:Ve.tenant(m.id("tenants")),contractId:Ve.restrict(m.id("contracts")),snapshotNumber:m.optional(m.number()),revisionNumber:m.optional(m.number()),supersedesSnapshotId:m.optional(Ve.history(m.id("contract_snapshots"))),frozenAt:m.number(),frozenByUserId:m.optional(Ve.history(m.id("users"))),document:Y3,coverLetter:m.optional(H3),snapshot:Ve.historyOf(G3),generation:m.optional(m.object({generatorVersionId:m.optional(Ve.history(m.id("contract_generator_versions"))),generatorRevisionId:m.optional(m.string()),implementationKey:m.string(),implementationChecksum:m.string(),input:m.any(),output:m.any()}))},C_e=_n(J3).index("by_tenantId",["tenantId"]).index("by_document_storageId",["document.storageId"]).index("by_coverLetter_storageId",["coverLetter.storageId"]).index("by_contractId_and_snapshotNumber",["contractId","snapshotNumber"]).index("by_supersedesSnapshotId",["supersedesSnapshotId"]).index("by_generation_generatorVersionId",["generation.generatorVersionId"]);var W_e=16*1024;var Y_e=15*6e4;var H_e=10*6e4;var Sv={contractSnapshotId:Ve.restrict(m.id("contract_snapshots")),storageId:Ve.restrict(m.id("_storage")),sha256:m.string(),filename:m.string(),uploadedAt:m.number(),signers:m.array(m.object({partyId:Ve.history(m.id("parties")),role:m.string()}))},fNe=_n({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...Sv}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var yNe=m.object(Sv);var Av=200;async function Q3(e,t,n,r){t.length>Av&&F(`${r} is carried by more than ${Av} signing requests`);let i=[],o=new Set;for(let l of t){if(o.has(l.signingRequestId))continue;o.add(l.signingRequestId);let d=await e.db.get(l.signingRequestId);d===null&&F(`signing_request_documents ${l._id} names a missing signing request ${l.signingRequestId}`),i.push(d)}let a=n==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(Q3,"requestsOfMembers");async function LL(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Av+1);return await Q3(e,r,n,`revision ${t}`)}s(LL,"requestsOfSnapshot");var ML=100;async function Z3(e,t){let n=await LL(e,t);n.length>ML&&F(`requestsBySideOf: revision ${t} has more than ${ML} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await _L(e,i.signers)].push(i);return r}s(Z3,"requestsBySideOf");async function Ev(e,t){return(await Z3(e,t)).family}s(Ev,"familyRequestsOf");var Tv=100;async function X3(e,t){let n=await e;return n.length>Tv&&F(`contractChain: more than ${Tv} ${t}`),n}s(X3,"bounded");async function e5(e,t,n){let r=await bm(e,{applicationId:t,nodeId:n,key:Cs});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${n}.${Cs} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(e5,"nodeContractRef");async function qL(e,t){return await X3(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",n=>n.eq("contractId",t)).take(Tv+1),`revisions on contract ${t}`)}s(qL,"snapshotsAsc");async function $v(e,t){let n=(await Ev(e,t)).filter(RL);return n.length>1&&F(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s($v,"openFamilyRequest");async function t5(e,t){for(let n of await qL(e,t))if((await Ev(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(t5,"familyRoute");async function KL(e,t){for(let n of t)if(await t5(e,n)==="paper")return"paper";return"provider"}s(KL,"familyRouteOf");async function n5(e,t){let n=await AL(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&F(`contractChain: return ${t._id} holds missing file ${n.storageId}`),{_id:t._id,_creationTime:t._creationTime,storageId:n.storageId,filename:n.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:t._id}}s(n5,"toReturn");function Sm(e){async function t(a,l){return await e5(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await t(a,l);return(p===null||h===null||p.contractId!==h)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${h??"(none yet)"} \u2014 corrupt arc`),p}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await qL(a,d)).at(-1)??null}return s(r,"newestSnapshot"),{reads:{kind:"contract",async returned(a,l,d){if(d.askedAbout===void 0){if(d.onUnpinned==="notReturned")return null;F(`returned(${d.where}): an ask of the contract chain is always pinned to its revision`)}let c=await n(a,l,d.askedAbout,`returned(${d.where})`),u=await $v(a,c._id);if(u===null)return null;let p=(await wm(a,u._id)).filter(h=>h.review.status==="pending"&&h._id!==d.rejected);return p.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${p.length} returns pending \u2014 one is checked at a time`),p[0]===void 0?null:await n5(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:t,snapshotOf:n,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await t(a,l);return d===null?[]:[d]}}.contractsOf}}s(Sm,"contractNodeReads");function Am(e){return e.addedParts??[]}s(Am,"addedPartsOf");var Rv=50;async function r5(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(Rv+1);return n.length>Rv&&F(`groupRunsOf: generation group ${t} has more than ${Rv} runs`),n.length===0&&F(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(r5,"groupRunsOf");async function jL(e,t){let n=await r5(e,t),r=n[0].packageRunId;if(r!==void 0){(n.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(n.map(l=>l.partKey)).size!==n.length)&&F(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageVersionId_and_position",l=>l.eq("packageVersionId",i.packageVersionId)).take(51),a=[...o.map(l=>l.partKey),...Am(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${t} has no package reference.`)}s(jL,"groupRunsInOrder");function VL(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(VL,"isCompleteGroup");var Iv=200;function i5(e){let t=e.generatorStamp?.parts;return t===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(i5,"groupPartKeys");async function o5(e,t,n){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",t).eq("workflowNodeId",n)).take(Iv+1);return r.length>Iv&&F(`groupChain: more than ${Iv} generation runs on node ${n}`),r}s(o5,"nodeRuns");async function s5(e,t,n){let r=i5(n),i=new Set;for(let a of await o5(e,t,n.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${n.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await jL(e,a);if(!VL(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(Am(d).map(p=>p.partKey)),u=[];for(let p of l){!r.includes(p.partKey)&&!c.has(p.partKey)&&F(`groupChain: run ${p._id} renders part "${p.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let h=await e.db.get(p.contractSnapshotId);h===null&&F(`groupChain: run ${p._id} names revision ${p.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:p,snapshot:h})}o.push({packageRunId:a,startedAt:Math.min(...l.map(p=>p._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(s5,"groupRevisionRows");async function Ov(e,t,n){let r=await bm(e,{applicationId:t,nodeId:n,key:Ps});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${n}.${Ps} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Ov,"nodeGroupContracts");async function a5(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await $v(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&F(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(a5,"openGroupRequest");async function l5(e,t){let n=[];for(let i of await wv(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${t._id} holds missing file ${i.storageId}`),n.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=n[0];return{_id:t._id,_creationTime:t._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:t._id,documents:n}}s(l5,"toGroupReturn");function BL(e){async function t(i,o,a,l){let d=(await s5(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&F(`${l}: ${a} is no revision of node "${e.id}"'s generation groups \u2014 corrupt arc`),d}return s(t,"revisionRowOf"),{reads:{kind:"group",async returned(i,o,a){if(a.askedAbout===void 0){if(a.onUnpinned==="notReturned")return null;F(`returned(${a.where}): an ask of the group chain is always pinned to its lead revision`)}let l=await t(i,o,a.askedAbout,`returned(${a.where})`),d=await a5(i,l);if(d===null)return null;let c=(await wm(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&F(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await l5(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await Ov(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(BL,"groupNodeReads");async function d5(e,t){let n=t.lifecycle.kind==="draft"?void 0:t.lifecycle.kind;return{_id:t._id,_creationTime:t._creationTime,versionNumber:t.versionNumber,...n!==void 0?{status:n}:{},origin:t.origin.kind,storageId:t.storageId,...await yk(e,t.storageId),...t.filename!==void 0?{filename:t.filename}:{}}}s(d5,"toRevision");async function c5(e,t){let n=await d5(e,t);return{_id:n._id,_creationTime:n._creationTime,storageId:n.storageId,...n.filename!==void 0?{filename:n.filename}:{},...n.mimeType!==void 0?{mimeType:n.mimeType}:{},round:n.versionNumber}}s(c5,"toReturn");function UL(e){let t=mp(e);async function n(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",t)).collect()}return s(n,"contentRowsAsc"),{reads:{kind:"artifact",async returned(o,a,l){if(l.askedAbout===void 0){if(l.onUnpinned==="notReturned")return null;ae("CONFLICT",{de:"Die offene Antwort-Aufgabe ist an keine Dokumentversion gebunden, daher l\xE4sst sich die unterschriebene Fassung nicht vom versandten Dokument unterscheiden. Stellen Sie das Dokument neu aus (Zur\xFCckziehen & neu ausstellen).",en:"The open response task is not bound to a document version, so the signed copy cannot be told apart from the document that was sent. Issue the document again (withdraw and reissue)."})}let d=await n(o,a),c=d[d.length-1];if(c===void 0||c._id===l.askedAbout||c.origin.kind!=="uploaded")return null;if(l.rejected!==void 0){let u=d.find(p=>p._id===l.rejected);if(u===void 0&&F(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return await c5(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(UL,"artifactNodeReads");function Em(e){return e.production==="none"&&F(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Em,"documentChainKind");function GL(e){switch(Em(e)){case"contract":return Sm(e).reads;case"group":return BL(e).reads;case"artifact":return UL(e).reads}}s(GL,"documentReadsFor");var u5={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Nd(e){let t=e.responseStrategy;return typeof t=="string"&&t in li?li[t].producesResponseArtifact:!1}s(Nd,"returnsSignedCopy");function f5(e){return Nd(e)&&e.confirmContractTerms!==!1}s(f5,"asksContractTerms");function zL(e){return f5(e)?{title:e.contractTermsQuestionText??u5,body:{de:"Die unterschriebene Fassung wird erst nach Ihrer Best\xE4tigung hochgeladen. Die Best\xE4tigung wird mit Zeitpunkt und Person festgehalten.",en:"The signed copy is uploaded only after you confirm. The confirmation is recorded with time and person."},confirmLabel:{de:"OK",en:"OK"}}:null}s(zL,"contractTermsConfirm");async function p5(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:lw(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Lr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Lr} row`),a}s(p5,"rejectedReturnOfAsk");async function WL(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await p5(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(WL,"returnedCopyOfAsk");var _v=new Set([...$w,Fr,No,oa,Lr,cn]),QL={id:jt,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},ZL={id:go,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function m5(e){let t=[],n=[{slot:QL,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:ZL,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of n){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){t.push(Se(e,l,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber ${o.a} ${r.label.de} \u2014 nur production '${i}' verwendet sie.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a ${r.label.en.toLowerCase()} \u2014 only production '${i}' uses it.`}));continue}if(a.kind==="binding"){t.push(Se(e,l,{de:`[governedDocument/referenceNotLiteral] Knoten "${e.id}": ${o.the} ${r.label.de} ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ${o.it} aus.`,en:`[governedDocument/referenceNotLiteral] Node "${e.id}": the ${r.label.en.toLowerCase()} is a fixed value of the node, not a binding \u2014 choose it from the list.`}));continue}if(a.kind!=="literal")continue;let d=Al(a.value,{type:r.type});d!==null&&t.push(Se(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(m5,"referenceInputIssues");var h5={id:ai,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},g5={id:sa,type:"boolean",label:{de:"Coverletter best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},y5={id:Pn,type:"legalEntity",label:QN,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function w5(e,t){let n=`inputs.${Pn}`,r=e.inputs?.[Pn];if(r!==void 0&&r.kind==="binding")return[Se(e,n,{de:`[governedDocument/traegerNotLiteral] Knoten "${e.id}": der Tr\xE4ger ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ihn aus.`,en:`[governedDocument/traegerNotLiteral] Node "${e.id}": the legal entity is a fixed value of the node, not a binding \u2014 choose it from the list.`})];let i=ia(e),o=t?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=t?.traeger?.get(l);t?.traeger!==void 0&&d===void 0?a.push(Se(e,n,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Se(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${ip.address}), aber "${l}" hat keine \u2014 in der Konfiguration des Mandanten nachtragen (foundation.legalEntities[].address).`,en:`[governedDocument/traegerAddressMissing] The generator template on node "${e.id}" prints the legal entity's address (${ip.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(w5,"traegerIssues");function $m(e){if(e.production==="template"){let n=e.templateStamp?.fields;return Array.isArray(n)?n:[]}if(e.production!=="resolver")return[];let t=e.generatorStamp?.inputSchema?.fields;return Array.isArray(t)?t.map(n=>{let{label:r}=n;return r===void 0?{...n,label:{de:n.key,en:n.key}}:(Ti(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${n.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...n,label:r})}):[]}s($m,"generatorFields");function k5(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(k5,"deferredToCockpit");function b5(e){return Ci(e.type)?e.type:void 0}s(b5,"resolverSlotType");function v5(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=da(e);return{confirm:{title:{de:`\u201E${t.de}\u201C jetzt senden?`,en:`Send "${t.en}" now?`},body:{de:"Das Dokument wird danach f\xFCr die Familie sichtbar.",en:"The family will be able to see the document afterwards."},confirmLabel:{de:"Senden",en:"Send"}}}}s(v5,"issueConfirmation");function Se(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Se,"issue");function Tm(e){return cp.includes(e.production)&&Lo.includes(e.approval)&&fp.includes(e.responseStrategy)}s(Tm,"hasValidModes");async function Nv(e,t){let n=await Nl(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&$w.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";if(r.some(l=>l.templateKey===oa))return"awaitingCoverLetter";let o=r.find(l=>l.templateKey===Fr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===cn))return"signatureStalled";let a=r.find(l=>l.templateKey===No);if(a!==void 0){if(di(t.node).issuesBy==="provider"){let d=Em(t.node)==="group"?(await Ov(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await Sm(t.node).contractOrNull(e,t.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&F(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await KL(e,d)==="provider")return"awaitingSignature"}return di(t.node).producesResponseArtifact?await WL(e,{chain:GL(t.node),applicationId:t.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Lr)?"responseInCheck":"done"}s(Nv,"governedDocCurrentState");function YL(e){return e.production!=="none"&&Em(e)!=="artifact"}s(YL,"keepsDocumentInContractDomain");function x5(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!xe(r)||r.scope!=="env"||!Yn(r.key))return[];let i=ho(r.key);if(t.type!==i.type)return[Se(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${pe(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${pe(r)}) supplies ${i.type}.`})];let o=new Set((t.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Se(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" kennt ${a.map(l=>`\u201E${l.label.de}\u201C (${l.value})`).join(", ")} nicht \u2014 die Umgebungsvariable \u201E${i.label.de}\u201C kann diese Werte liefern. Jeder Wert braucht eine Option.`,en:`[governedDocument/envNotCovered] Field "${t.key}" does not know ${a.map(l=>`"${l.label.en}" (${l.value})`).join(", ")} \u2014 the environment variable "${i.label.en}" can supply these values. Every value needs an option.`})]}s(x5,"envCoverageIssues");function XL(e,t){let n=[];for(let r of $m(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...x5(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${xe(a.address)?pe(a.address):JSON.stringify(a.address)}`,en:`a binding to ${xe(a.address)?pe(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:k5(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/processSourceConflict] "${r.label.de}" wird vom Vorgang selbst gef\xFCllt (${r.processSource}), daneben steht ${l.de}. Eine der beiden Quellen bliebe wirkungslos \u2014 entferne die Verdrahtung.`,en:`[governedDocument/processSourceConflict] "${r.label.en}" is filled by the case itself (${r.processSource}), and ${l.en} is set as well. One of the two sources would have no effect \u2014 remove the wiring.`},severity:"error"});continue}if(r.required!==!0)continue;let i=e.inputs?.[r.key];i?.kind==="binding"||i?.kind==="literal"||i?.kind==="cockpit"||r.defaultValue!==void 0||n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${t.de} hat keine Quelle \u2014 binde es an ein Formular-Export-Feld, setze einen festen Wert oder lass es ausdr\xFCcklich im Cockpit erg\xE4nzen.`,en:`[governedDocument/unsourcedRequiredField] Required field "${r.label.en}" of the generator ${t.en} has no source \u2014 bind it to a form export field, set a fixed value or leave it explicitly to the cockpit.`},severity:"error"})}return n}s(XL,"fieldSourceIssues");function S5(e){let t=hr(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=xL(e.templateStamp,t).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...XL(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(S5,"templateIssues");function A5(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${n.pin}" wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the generator template "${n.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=n.signerAnchors.filter(i=>!n.documentAnchors.has(i));return r.length===0?[]:[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${n.pin}" tr\xE4gt keinen Anker f\xFCr ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 der Anbieter f\xE4nde f\xFCr diese Personen kein Unterschriftsfeld.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the template of "${n.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(A5,"eSignatureAnchorIssues");function E5(e,t){return t===void 0||t.sendable?[]:di(e).issuesBy!=="provider"?[]:[Se(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${t.reason.en}`})]}s(E5,"eSignatureProviderIssues");var HL={key:"dokument",label:ne("Dokument","Document"),scope:"node"},JL={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:HL,external:Ze(ne("In Vorbereitung","In preparation"),"blue",ne("Ihr Dokument wird vorbereitet","Your document is being prepared"),ne("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:ne("Dokument bereitgestellt","Document issued"),tone:"blue",phase:HL,external:Ze(ne("Dokument bereit","Document ready"),"amber",ne("Ihr Dokument liegt bereit","Your document is ready"),ne("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),ne("Dokument beantworten","Respond to the document"))}},e0={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>_o,"processHoldTemplate"),progressDefaults:JL,progressEvents:Ft(JL),notificationEvents:s(e=>[{id:"issued",label:{de:"Dokument bereitgestellt",en:"Document issued"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number"}]},{id:"responded",label:{de:"Antwort eingegangen",en:"Response received"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]},{id:"coverLetterAsked",label:{de:"Coverletter zur Best\xE4tigung",en:"Cover letter to confirm"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number",required:!1}]},{id:"responseRejected",label:{de:"R\xFCcklauf zur\xFCckgegeben",en:"Returned copy handed back"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"reason",type:"string",required:!0}]}],"notificationEvents"),strictActionCoverage:!0,actions:s(e=>{if(!Tm(e))return[];let t=di(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...Fo(e)?["awaitingCoverLetter"]:[],...i,...t.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(n.push({id:Rw(e),kind:"internal",surface:aa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...v5(e)??{}}),n.push({id:tC,kind:"internal",surface:aa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:nC,kind:"internal",surface:aa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:ap,kind:"internal",label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:t.acceptOutcomeId,kind:"advance",outcome:t.acceptOutcomeId,semantic:t.outcomeSemantics.accept,label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:t.declineOutcomeId,kind:"advance",outcome:t.declineOutcomeId,semantic:t.outcomeSemantics.decline,label:e.responseLabels?.decline??t.defaultLabels.decline,availableIn:Fo(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),Fo(e)&&(n.push({id:op,kind:"internal",label:{de:"Schreiben best\xE4tigen",en:"Confirm the letter"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),n.push({id:sp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),t.producesResponseArtifact&&n.push({id:lp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:dp,kind:"internal",surface:aa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Co,kind:"internal",surface:aa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:rC,currentState:Nv,workItemTemplates:s(e=>{let t=e;return Tm(t)?Iw(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Tm(n)||n.production==="none")return[];let r=Iw(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:mp(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[QL,y5]:[],...e.production==="template"?[ZL]:[],h5,...e.generatorStamp?.coverLetter===!0?[g5]:[],...$m(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=b5(t);return n===void 0?[]:[{field:t,type:n}]}).map(({field:t,type:n})=>({id:t.key,type:n,label:t.label,required:t.required===!0&&t.processSource===void 0,...t.processSource===void 0?{deferrable:!0}:{},...t.defaultValue!==void 0&&(typeof t.defaultValue=="string"||typeof t.defaultValue=="number"||typeof t.defaultValue=="boolean"||t.defaultValue===null||n==="pricedItem"&&Oi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:bl,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===No||t===oa||t===ql||t===Lr||t===cn){let n=t===No?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Lr?{de:"die Pr\xFCfung des R\xFCcklaufs entsteht erst mit dem R\xFCcklauf der Familie",en:"the check of the returned copy only arises once the family returns it"}:t===cn?{de:"die Kl\xE4rung der elektronischen Unterschrift entsteht erst, wenn sie nicht zustande kommt",en:"resolving the electronic signature only arises when it does not come about"}:{de:"die \xDCberarbeitungs-Aufgabe entsteht nur durch eine Ablehnung",en:"the revision task only arises from a rejection"};return{de:`[governedDocument/blocksTarget] 'blocks' auf "${t}" (Knoten "${e.id}") ist verboten \u2014 ${n.de}; zul\xE4ssige intrinsische Ziele: ${_o}${e.approval==="release"?`, ${Fr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${_o}${e.approval==="release"?`, ${Fr}`:""}.`}}return t===Fr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Fr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Fr}" on node "${e.id}" \u2014 with approval 'none' this template does not exist; the blocker would postpone a phantom.`}:null},"refuseBlocksTarget"),userUploadGate:s(async(e,t)=>{if(YL(t.node))return!1;let n=await Nv(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&di(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=zL(t.node);if(n===null||YL(t.node))return null;let r=await Nv(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Tm(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${cp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Lo.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${fp.join(", ")}} (ist: ${JSON.stringify(e.responseStrategy)}). Eine Betriebsart ist eine erkl\xE4rte Entscheidung, nie aus der Verdrahtung abgeleitet.`,en:`[governedDocument/unknownMode] Node "${e.id}" declares no valid mode \u2014 required: production \u2208 {${cp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Lo.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${fp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=li[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Se(e,"production",{de:`[governedDocument/modeContract] Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben und nichts zu unterschreiben: approval muss 'none' sein (ist: '${e.approval}') und responseStrategy 'confirm' (ist: '${e.responseStrategy}').`,en:`[governedDocument/modeContract] Node "${e.id}" has production 'none' \u2014 with no document there is nothing to release and nothing to sign: approval must be 'none' (is: '${e.approval}') and responseStrategy 'confirm' (is: '${e.responseStrategy}').`}));let o=e.artifacts??[];if(e.production==="none")o.length!==0&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" hat production 'none', deklariert aber ${o.length} Artefakt-Slot(s) \u2014 ein dokumentloser Best\xE4tigungs-Knoten verwaltet keinen Slot.`,en:`[governedDocument/slotContract] Node "${e.id}" has production 'none' but declares ${o.length} artifact slot(s) \u2014 a confirmation node without a document manages no slot.`}));else{o.length!==1&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" deklariert ${o.length} Artefakt-Slots \u2014 genau EINER (das verwaltete Dokument) ist erforderlich.`,en:`[governedDocument/slotContract] Node "${e.id}" declares ${o.length} artifact slots \u2014 exactly ONE (the managed document) is required.`}));for(let A of o)A.visibility!=="external"&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${A.key}" auf Knoten "${e.id}" hat visibility "${A.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${A.key}" on node "${e.id}" has visibility "${A.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(A=>A.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(A=>l.includes(A)))&&r.push(Se(e,"outcomes",{de:`[governedDocument/outcomeContract] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') muss genau ZWEI Outcomes deklarieren \u2014 das Accept-Terminal "${i.acceptOutcomeId}" und das Decline-Terminal "${i.declineOutcomeId}" (deklariert: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"keine"}). Beide sind Pflicht: der Knoten besitzt die Antwort, nicht nur die Freigabe.`,en:`[governedDocument/outcomeContract] Node "${e.id}" (responseStrategy '${e.responseStrategy}') must declare exactly TWO outcomes \u2014 the accept terminal "${i.acceptOutcomeId}" and the decline terminal "${i.declineOutcomeId}" (declared: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(A=>{let E=c?.[A];return E===null||typeof E!="object"||!Object.values(E??{}).some(I=>typeof I=="string"&&I.length>0)},"missingTitle"),p=[];e.production!=="none"&&p.push("prepare","revise"),e.approval==="release"&&p.push("approve"),i.checksReturn&&p.push("check");let h=p.filter(u);h.length>0&&r.push(Se(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${h.join(", ")} \u2014 der Knotentyp ist dokument-agnostisch, die Betitelung ist Pflicht-Konfiguration seiner Betriebsart.`,en:`[governedDocument/missingTitles] Node "${e.id}" is missing the task titles ${h.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let w=e.assign??{};if(e.production!=="none"){let A=w.prepareDocument;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`}))}if(e.approval==="none"&&(w.releaseApproval!==void 0&&r.push(Se(e,"assign.releaseApproval",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', verdrahtet aber assign.releaseApproval \u2014 tote Verdrahtung darf nicht als konfiguriert durchgehen (Betriebsart explizit \xE4ndern statt Gruppen zuweisen).`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but wires assign.releaseApproval \u2014 dead wiring must not pass as configured (change the mode explicitly instead of assigning groups).`})),c?.approve!==void 0&&r.push(Se(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn){let A=w.responseCheck;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.responseCheck",{de:`[governedDocument/checkAssign] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') verdrahtet kein Team f\xFCr die Pr\xFCfung des R\xFCcklaufs (assign.responseCheck) \u2014 ohne Team l\xE4ge jeder R\xFCcklauf bei niemandem.`,en:`[governedDocument/checkAssign] Node "${e.id}" (responseStrategy '${e.responseStrategy}') wires no team for checking the returned copy (assign.responseCheck) \u2014 without a team every returned copy would lie with nobody.`})),e.production!=="resolver"&&i.issuesBy==="provider"?r.push(Se(e,"responseStrategy",{de:`[governedDocument/eSignatureNeedsResolver] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben (eSignature), erzeugt das Dokument aber mit production '${e.production}' \u2014 der Anbieter bekommt eine eingefrorene Vertragsrevision mit Unterschriftsankern und deklarierten Unterzeichnern, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/eSignatureNeedsResolver] Node "${e.id}" is signed electronically (eSignature) but produces the document with production '${e.production}' \u2014 the provider gets a frozen contract revision with signature anchors and declared signatories, and that only exists with production 'resolver'.`})):e.production!=="resolver"&&r.push(Se(e,"responseStrategy",{de:`[governedDocument/checkNeedsContract] Knoten "${e.id}" pr\xFCft den R\xFCcklauf (signedUploadChecked), erzeugt das Dokument aber mit production '${e.production}' \u2014 die Pr\xFCfung hakt die unterzeichnenden Personen einer eingefrorenen Vertragsrevision ab, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/checkNeedsContract] Node "${e.id}" checks the returned copy (signedUploadChecked) but produces the document with production '${e.production}' \u2014 the check ticks off the signatories of a frozen contract revision, and that only exists with production 'resolver'.`}))}else{e.production==="resolver"&&r.push(Se(e,"responseStrategy",{de:`[governedDocument/contractNeedsCheckedReturn] Knoten "${e.id}" erzeugt einen Vertrag (production 'resolver'), beantwortet ihn aber mit '${e.responseStrategy}' \u2014 ein Vertrag gilt erst als unterschrieben, wenn die Schule den R\xFCcklauf gepr\xFCft hat oder ein Anbieter die Unterschrift belegt: responseStrategy muss 'signedUploadChecked' oder 'eSignature' sein (mit assign.responseCheck und titles.check).`,en:`[governedDocument/contractNeedsCheckedReturn] Node "${e.id}" produces a contract (production 'resolver') but answers it with '${e.responseStrategy}' \u2014 a contract only counts as signed once the school has checked the returned copy or a provider proves the signature: responseStrategy must be 'signedUploadChecked' or 'eSignature' (with assign.responseCheck and titles.check).`}));for(let[A,E]of[["assign.responseCheck",w.responseCheck!==void 0],["titles.check",c?.check!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 eine Pr\xFCfung des R\xFCcklaufs gibt es nur mit responseStrategy 'signedUploadChecked' oder 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let A=w.signingRecovery;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`}))}else w.signingRecovery!==void 0&&r.push(Se(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`}));if(i.issuesBy==="provider"&&r.push(...A5(e,n),...E5(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Se(e,"confirmBeforeIssue",{de:`[governedDocument/confirmBeforeIssue] Knoten "${e.id}" setzt confirmBeforeIssue auf ${JSON.stringify(e.confirmBeforeIssue)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmBeforeIssue] Node "${e.id}" sets confirmBeforeIssue to ${JSON.stringify(e.confirmBeforeIssue)} \u2014 only true or false is allowed.`})):e.confirmBeforeIssue===!0&&e.approval==="release"&&r.push(Se(e,"confirmBeforeIssue",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'release', deklariert aber confirmBeforeIssue \u2014 \u201EFreigabe anfordern" schickt noch nichts an die Familie, und die Freigabe selbst ist die bewusste Pr\xFCfung vor dem Versand. Die R\xFCckfrage gibt es nur mit approval 'none'.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'release' but declares confirmBeforeIssue \u2014 "Request release" sends nothing to the family yet, and the release itself is the deliberate check before sending. The confirmation prompt only exists with approval 'none'.`})),e.confirmContractTerms!==void 0&&typeof e.confirmContractTerms!="boolean"&&r.push(Se(e,"confirmContractTerms",{de:`[governedDocument/confirmContractTerms] Knoten "${e.id}" setzt confirmContractTerms auf ${JSON.stringify(e.confirmContractTerms)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmContractTerms] Node "${e.id}" sets confirmContractTerms to ${JSON.stringify(e.confirmContractTerms)} \u2014 only true or false is allowed.`})),Nd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Se(e,"contractTermsQuestionText",{de:`[governedDocument/deadWiring] Knoten "${e.id}" schaltet die Best\xE4tigung der Vertragsbedingungen ab (confirmContractTerms: false), formuliert aber die Frage um \u2014 ohne Best\xE4tigung wird sie nie gestellt.`,en:`[governedDocument/deadWiring] Node "${e.id}" switches off the confirmation of the contract terms (confirmContractTerms: false) but rewords the question \u2014 without the confirmation it is never asked.`}));else for(let[A,E]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 die Best\xE4tigung der Vertragsbedingungen geh\xF6rt zum Hochladen der unterschriebenen Fassung, das es nur mit responseStrategy 'signedUpload' oder 'signedUploadChecked' gibt.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 the confirmation of the contract terms belongs to uploading the signed copy, which only exists with responseStrategy 'signedUpload' or 'signedUploadChecked'.`}));if(e.production==="none")for(let[A,E]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",w.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${A} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${A} \u2014 without a production phase there is nothing to carry it.`}));for(let A of e.tasks??[])_v.has(A.key)&&r.push(Se(e,`tasks.${A.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${A.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[..._v].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${A.key}" on node "${e.id}" collides with an intrinsic template (${[..._v].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...w5(e,n)):e.inputs?.[Pn]!==void 0&&r.push(Se(e,`inputs.${Pn}`,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber einen Tr\xE4ger \u2014 nur ein erzeugter Vertrag hat eine Vertragspartei der Schule.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a legal entity \u2014 only a generated contract has a contracting party on the school's side.`})),r.push(...m5(e)),e.production==="resolver"){let A=Jr(e);if(A!==null){let E=aI(A);for(let I of $m(e)){if(!Ci(I.type)){r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/unknownFieldType] Generator "${E}" typisiert das Feld "${I.key}" als "${String(I.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Ls.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${E}" types the field "${I.key}" as "${String(I.type)}" \u2014 that is not part of the platform's value vocabulary (${Ls.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(I.type==="personList"){r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${E}" deklariert das Feld "${I.key}" als personList \u2014 daf\xFCr gibt es keine Platzhalter-Heimat im Dokument und keine Eingabe. Eine Liste von Personen geh\xF6rt als Rolle mit Kapazit\xE4t deklariert oder als berechneter Textwert.`,en:`[governedDocument/partyListUnsupported] Generator "${E}" declares the field "${I.key}" as personList \u2014 there is no placeholder home for it in the document and no input. A list of people belongs declared as a role with capacity or as a computed text value.`}));continue}I.type==="party"&&(I.key.endsWith("PartyId")||r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${I.key}" endet nicht auf "PartyId" \u2014 aus diesem Suffix wird der Platzhalter-Pr\xE4fix im Dokument abgeleitet (emergencyContactPartyId \u2192 emergency_contact).`,en:`[governedDocument/partyFieldKey] Party field "${I.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...XL(e,{de:`"${E}"`,en:`"${E}"`}))}}else e.generatorStamp!==void 0&&r.push(Se(e,"generatorStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber den Stempel eines Generators \u2014 ohne maschinelle Produktion l\xE4uft keiner.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a generator stamp \u2014 without machine production none runs.`}));e.production==="template"?r.push(...S5(e)):e.templateStamp!==void 0&&r.push(Se(e,"templateStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber die Parameter einer Vorlage \u2014 ohne Vorlagen-Produktion wird sie nie gef\xFCllt.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a template's parameters \u2014 without template production it is never filled.`}));let k=e.inputs?.[sa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${sa}`,{de:`[governedDocument/coverLetterInput] Knoten "${e.id}": Die Best\xE4tigung des Coverletters ist ein fester Wert ja oder nein.`,en:`[governedDocument/coverLetterInput] Node "${e.id}": the cover letter's confirmation is a fixed yes or no.`})),Fo(e)&&(n!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${sa}`,{de:`[governedDocument/coverLetterNotDeclared] Knoten "${e.id}" l\xE4sst ein Coverletter best\xE4tigen, sein Generator erzeugt aber keines.`,en:`[governedDocument/coverLetterNotDeclared] Node "${e.id}" asks to confirm a cover letter, but its generator produces none.`})),e.approval!=="release"&&r.push(Se(e,"approval",{de:`[governedDocument/coverLetterNeedsRelease] Knoten "${e.id}": Ein Coverletter mit Best\xE4tigung braucht die Freigabe, denn Vertrag und Coverletter werden zusammen freigegeben.`,en:`[governedDocument/coverLetterNeedsRelease] Node "${e.id}": a cover letter with confirmation needs the release, because contract and letter are released together.`})),di(e).producesResponseArtifact||r.push(Se(e,"responseStrategy",{de:`[governedDocument/coverLetterNeedsSigning] Knoten "${e.id}": Ein Coverletter steht vor einer Unterschrift; dieser Knoten l\xE4sst nicht unterschreiben.`,en:`[governedDocument/coverLetterNeedsSigning] Node "${e.id}": a cover letter comes before a signature; this node takes none.`})));let y=e.inputs?.[ai],v=y===void 0||y.kind==="unset"?void 0:y.kind==="literal"?y.value:y;return v!==void 0&&!jl(v)&&r.push(Se(e,`inputs.${ai}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(v)} \u2014 erlaubt ist eine ganze Zahl von ${Po} bis ${Do} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(v)} \u2014 a whole number from ${Po} to ${Do} days is allowed.`})),v===void 0&&$m(e).some(A=>A.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${ai}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" druckt die Antwortfrist (processSource 'responseDueInDays'), setzt aber kein responseDueInDays \u2014 das Dokument nennte eine Frist, die es nicht gibt.`,en:`[governedDocument/dueInDays] Node "${e.id}" prints the response deadline (processSource 'responseDueInDays') but sets no responseDueInDays \u2014 the document would name a deadline that does not exist.`})),r},"validate")};var t0={addPupil:{method:"POST",path:"/api/v1/admissions/AddPrPupilBasic/{schoolid}",kind:"create",body:"PrPupilBasicCreate",required:["forename","surname","genderId"],maxLength:{titleId:4,forename:50,surname:50,middleName:50,preferredForename:50,preferredSurname:50,genderId:4,firstLanguage:4}},addAdmissionDetails:{method:"POST",path:"/api/v1/admissions/AddAdmissionDetails/{schoolid}/{pupilid}",kind:"create",body:"AddPrPupilAdmissionDetails",required:[],maxLength:{boarderStatusId:4,ageAdjust:4,entryYear:4,entryTerm:4,entryYearGroup:4,currentSchoolId:20,enquirySource:4,currentAdmissionStageId:25}},addNationality:{method:"POST",path:"/api/v1/admissions/AddNationlityInfo/{schoolid}/{pupilid}",kind:"create",body:"NationalityInfoCreate",required:["nationalityId"],maxLength:{nationalityId:4,countryOfBirth:4}},addVisa:{method:"POST",path:"/api/v1/admissions/AddVisaInfo/{schoolid}/{pupilid}",kind:"create",body:"CreateVisaInfo",required:[],maxLength:{placeOfBirth:50,passportCountry:4,passportNumber:50,residenceVisaNumber:50,healthCardNumber:50}},addMedical:{method:"POST",path:"/api/v1/admissions/AddMedicalInfo/{schoolid}/{pupilid}",kind:"create",body:"MedicalInfoCreate",required:[],maxLength:{}},addContact:{method:"POST",path:"/api/v1/admissions/AddContactBasicInfo/{schoolid}/{pupilid}",kind:"create",body:"AddContactBasicInfo",required:["titleId","firstName","lastName","genderId"],maxLength:{relationshipId:4,titleId:4,firstName:50,middleName:50,lastName:50,contactName:200,greeting:200,languageId:4,secondLanguageId:4,genderId:4,professionId:4,companyName:50,jobTitle:50}},linkExistingContact:{method:"POST",path:"/api/v1/admissions/LinkExistingContact/{schoolid}/{pupilid}/{contactid}",kind:"create",body:"LinkContact",required:["relationshipId"],maxLength:{relationshipId:4}},addContactAddress:{method:"POST",path:"/api/v1/admissions/AddContactAddressNew/{schoolid}/{contactid}/{addressformatid}",kind:"create",body:"AddAddressVM",required:["countryId"],maxLength:{addressTypeId:4,countryId:4,addressLine1:100,addressLine2:100,addressLine3:100,addressLine4:100,addressLine5:100,addressLine6:100,lookup1:4,lookup2:4,lookup3:4,lookup4:4,lookup5:4}},addContactEmail:{method:"POST",path:"/api/v1/admissions/AddContactEmail/{schoolid}/{contactid}",kind:"create",body:"AddEmailAddress",required:["emailTypeId","email"],maxLength:{emailTypeId:4,email:254}},addContactTelephone:{method:"POST",path:"/api/v1/admissions/AddContactTelephone/{schoolid}/{contactid}",kind:"create",body:"AddTelephoneNumber",required:["typeId","number"],maxLength:{typeId:4}},linkAddressToPupil:{method:"PUT",path:"/api/v1/admissions/LinkAddressToPupil/{schoolId}/{pupilId}/{addressId}",kind:"update",required:[],maxLength:{}},updatePupilAif:{method:"POST",path:"/api/v1/additionalinformation/UpdatePupilAIF/{schoolid}/{pupilid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},updateContactAif:{method:"POST",path:"/api/v1/additionalinformation/UpdateContactAIF/{schoolid}/{contactid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},listPupils:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfo/{schoolid}",kind:"read",required:[],maxLength:{}},getPupil:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfoById/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},listContactsOfPupil:{method:"GET",path:"/api/v1/admissions/GetContactBasicInfoByPupilId/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},getContact:{method:"GET",path:"/api/v1/admissions/GetContactByContactId/{schoolid}/{contactid}",kind:"read",required:[],maxLength:{}}};function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Kn,"isRecord");var Cv=["field","join","literal","address","payment","contract"],T5=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),$5=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ir(e){return typeof e=="string"&&e.trim().length>0}s(ir,"nonEmptyString");function Rm(e,t,n,r,i="value"){if(!Kn(e)||!Kn(e.from)){r.push({path:t,code:"mappingShape",message:{de:`${t}: eine Zuordnung braucht \`from\`.`,en:`${t}: a mapping needs \`from\`.`}});return}let o=e.from,a=Cv.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${Cv.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${Cv.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ir(o.field)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.field\` ist leer.`,en:`${t}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(ir))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${t}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${t}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${t}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||ir(e.whenEmpty)||r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${t}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(xe(o.address)&&o.address.scope==="env"&&Yn(o.address.key))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${t}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.payment\` ist amount oder settledAt.`,en:`${t}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${t}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${t}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!T5.has(String(e.format))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekanntes Format \u201E${String(e.format)}".`,en:`${t}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(ir(e.lookup)&&Kn(n[e.lookup]))&&r.push({path:t,code:"unknownLookup",message:{de:`${t}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${t}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||Kn(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Kn(d)&&$5.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Rm,"checkMapping");function Gi(e,t,n,r,i){if(!Kn(e)){i.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${t}: expects an object field \u2192 mapping.`}});return}let o=t0[n];for(let a of o.required)a in e||i.push({path:`${t}.${a}`,code:"missingRequired",message:{de:`${t}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${t}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))Rm(l,`${t}.${a}`,r,i)}s(Gi,"checkBody");function n0(e,t,n,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet eine Liste.`,en:`${t}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${t}[${a}]`;if(!Kn(o)||!ir(o.fieldId)){r.push({path:l,code:"aifShape",message:{de:`${l}: \`fieldId\` fehlt.`,en:`${l}: \`fieldId\` is missing.`}});return}i.has(o.fieldId)&&r.push({path:l,code:"aifDuplicate",message:{de:`${l}: \u201E${o.fieldId}" doppelt.`,en:`${l}: "${o.fieldId}" appears twice.`}}),i.add(o.fieldId),Rm(o.value,`${l}.value`,n,r),o.unless!==void 0&&Rm(o.unless,`${l}.unless`,n,r,"condition")})}s(n0,"checkAif");function Pv(e){let t=[];if(!Kn(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Kn(e.lookups)?e.lookups:{};Kn(e.lookups)||t.push({path:"engage.lookups",code:"bodyShape",message:{de:"`engage.lookups` fehlt (Tabellen Name \u2192 Plexus-Wert \u2192 Engage-Id).",en:"`engage.lookups` is missing (tables name \u2192 Plexus value \u2192 Engage id)."}});for(let[r,i]of Object.entries(n))(!Kn(i)||!Object.values(i).every(ir))&&t.push({path:`engage.lookups.${r}`,code:"lookupShape",message:{de:`Lookup \u201E${r}": jede Engage-Id ist ein nicht leerer Text.`,en:`Lookup "${r}": every Engage id is a non-empty text.`}});if(ir(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Gi(e.pupil,"engage.pupil","addPupil",n,t),Gi(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Gi(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Gi(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Gi(e.medical,"engage.medical","addMedical",n,t),n0(e.pupilAif,"engage.pupilAif",n,t),!Array.isArray(e.contacts))t.push({path:"engage.contacts",code:"bodyShape",message:{de:"`engage.contacts` fehlt (Liste der Kontakte).",en:"`engage.contacts` is missing (list of contacts)."}});else{let r=new Set;e.contacts.forEach((i,o)=>{let a=`engage.contacts[${o}]`;if(!Kn(i)||!ir(i.key)||!ir(i.presentIf)){t.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&t.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Gi(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Gi(i.address,`${a}.address`,"addContactAddress",n,t);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){t.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Gi(u,`${a}.${l}[${p}]`,d,n,t))}}n0(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Rm(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Kn(r)||!ir(r.repeated)||!ir(r.field)||!ir(r.equals))&&t.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return t}s(Pv,"engagePushConfigIssues");function*Dv(e){let t=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let n of t)for(let r of Object.values(n??{}))yield{mapping:r};for(let n of e.pupilAif??[])yield{mapping:n.value},n.unless!==void 0&&(yield{mapping:n.unless});for(let n of e.contacts){let r=[n.basic,n.address,...n.emails??[],...n.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:n.key};for(let i of n.aif??[])yield{mapping:i.value,contactKey:n.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:n.key});n.linkAddressToPupilIf!==void 0&&(yield{mapping:n.linkAddressToPupilIf,contactKey:n.key})}}s(Dv,"mappingsOf");function r0(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Dv(e))for(let i of R5(n.from))t.add(I5(i,r));return[...t]}s(r0,"configFieldKeys");function R5(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(R5,"formFieldsOf");function I5(e,t){return e.startsWith(".")?(t===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(I5,"resolveFieldKey");function i0(e,t){for(let{mapping:n}of Dv(e))if(t in n.from)return!0;return!1}s(i0,"configReadsSource");function o0(e){let t=new Set;for(let{mapping:n}of Dv(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(o0,"configEnvLeaves");var s0="done",a0=["sandbox","production"];var Im="engagePush",dPe=660*1e3;function zi(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(zi,"issue");function Fv(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Fv,"literal");function l0(e){return Pv(e.engage).length===0?e.engage:null}s(l0,"validConfig");function O5(e,t){let n=new Map(e.nodes.map(a=>[a.id,a])),r=e.nodes.filter(a=>a.type==="eventTrigger"),i=new Set,o=r.map(a=>a.id);for(;o.length>0;){let a=o.pop();if(a===t||i.has(a))continue;i.add(a);let l=n.get(a);if(l!==void 0){if(l.type==="end"){let d=l.inputs?.applicationOutcome;if(d?.kind==="literal"&&d.value==="approved")return!0;continue}for(let d of Object.values(l.next??{})){let c=d?.to;typeof c=="string"&&o.push(c)}}}return!1}s(O5,"bypassingPath");var d0={role:"system-action",effect:"side-effect",outcomes:[{id:s0,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=l0(e);return t===null?[]:o0(t)},"envReads"),inputs:s(()=>[{id:"target",label:{de:"Ziel-Engage",en:"Target Engage"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"sandbox",label:{de:"Sandbox",en:"Sandbox"}},{value:"production",label:{de:"Produktion",en:"Production"}}]},{id:"contractFields",label:{de:"Vertragsfelder F01\u2013F25",en:"Contract fields F01\u2013F25"},type:"enum",required:!1,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"off",label:{de:"Nicht \xFCbertragen (Bedeutung offen)",en:"Do not transfer (meaning open)"}},{value:"on",label:{de:"\xDCbertragen",en:"Transfer"}}]}],"inputs"),validate:s((e,t,n)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=Fv(e,"target");a0.includes(a)||o.push(zi(e,"inputs.target",{de:`[engagePush/invalidTarget] \u201E${r}": das Ziel ist sandbox oder production.`,en:`[engagePush/invalidTarget] "${i}": the target is sandbox or production.`}));let l=Fv(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(zi(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[Im];(typeof d!="string"||d.length===0)&&o.push(zi(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Im}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Im}\` names the team.`}));for(let y of Pv(e.engage))o.push(zi(e,y.path,{de:`[engagePush/config] \u201E${r}": ${y.message.de}`,en:`[engagePush/config] "${i}": ${y.message.en}`}));let c=t.nodes.filter(y=>y.id!==e.id&&y.type==="engagePush"&&Fv(y,"target")===a);c.length>0&&o.push(zi(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(y=>`"${y.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(y=>`"${y.id}"`).join(", ")} already transfers to the same target.`})),O5(t,e.id)&&o.push(zi(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let u=l0(e),p=e;for(let[y,v,A,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!i0(u,y)||p[v]!==void 0||o.push(zi(e,v,{de:Ks("address/missing",{where:`\u201E${r}\u201C \u203A ${A}`},"de"),en:Ks("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let h=p.form,w=xe(h)&&h.scope==="node"?h.owner:void 0,k=w===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(w);if(u!==null&&k!==void 0){let y=new Set(k.keys()),v=r0(u).filter(A=>!y.has(A)&&!/\[\d+\]\./.test(A));if(v.length>0){let A=t.nodes.find(E=>E.id===w);o.push(zi(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${A?.label?.de??w}" nicht \u2014 sie werden nicht \xFCbertragen: ${v.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${A?.label?.en||w}" does not know these fields \u2014 they are not transferred: ${v.join(", ")}.`},"warning"))}}return o},"validate")};var Jo={join:LF,end:zO,roleAssign:qF,eventTrigger:KF,waitlist:rL,completenessCheck:uL,form:YF,setFlag:HF,if:JF,decision:Yo,review:pL,collectPayment:kL,governedDocument:e0,countersign:yC,engagePush:d0};UI(Jo);function c0(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new Error(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(c0,"graphOf");function u0(e){let t=new Map;for(let n of e.nodes)for(let r of Pr(e,n))t.set(pe(r.address),r.nodeId);return t}s(u0,"producedOf");function f0(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(xo(e,n).map(r=>pe(r.address))));return t}s(f0,"readsOf");function p0(e,t){let n=c0(e,"bundle"),r=c0(t.graph,"live head"),i=u0(n),o=u0(r),a={added:[],removed:[],moved:[]};for(let[u,p]of i){let h=o.get(u);h===void 0?a.added.push({address:u,nodeId:p}):h!==p&&a.moved.push({address:u,from:h,to:p})}for(let[u,p]of o)i.has(u)||a.removed.push({address:u,nodeId:p});let l=f0(n),d=f0(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let p=l.get(u)??new Set,h=d.get(u)??new Set,w=[...p].filter(y=>!h.has(y)),k=[...h].filter(y=>!p.has(y));(w.length>0||k.length>0)&&c.push({nodeId:u,added:w,removed:k})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(p0,"planAddresses");function m0(e){let t=[...e.produced.moved.map(i=>({icon:"~",target:`address:${i.address}`,status:`Knoten ${i.from} \u2192 ${i.to}`})),...e.produced.added.map(i=>({icon:"+",target:`address:${i.address}`,status:`neu (${i.nodeId})`})),...e.produced.removed.map(i=>({icon:"-",target:`address:${i.address}`,status:`entfernt (${i.nodeId})`})),...e.reads.map(i=>({icon:"~",target:`reads:${i.nodeId}`,status:[i.added.length>0?`+${i.added.join(", ")}`:"",i.removed.length>0?`\u2212${i.removed.join(", ")}`:""].filter(Boolean).join(" ")}))];if(t.length===0)return[];let{real:n,test:r}=e.pinnedApplications;return t.push({icon:"!",target:"pinned",status:`${n+r} Anmeldungen (${n} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),t}s(m0,"addressPlanRows");function h0(e,t){return t==null?!0:Ne(e)!==Ne(t)}s(h0,"changed");async function g0(e,t,n){if(t.index.module!==Qb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return HC(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return Qb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(g0,"applyOffer");async function y0(e,t,n,r="published"){let i=await e.query(x.setup.offerBundle.exportOfferBundle,{client:t,offerKey:n,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(y0,"exportOffer");async function Lv(e,t){let{index:n}=t,i=(await e.query(x.workflow.listManifests,{client:n.tenant})).find(w=>w.offerKey===n.slugs.manifest),o="create";i&&(o="same");let a={};for(let[w,k]of Object.entries(t.smartforms??{})){let y=i?await e.query(x.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:w}):null;a[w]=y?.def?h0(k,{label:y.def.label,...y.def.definition})?"change":"same":"create"}let l="absent",d=null;if(t.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let w=await e.query(x.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),k=w?.publishedVersion??w?.draftVersion;l=h0(k&&{graph:$s(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:$s(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let w=await e.query(x.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});w!==null&&(d=p0(t.workflow.graph,w))}}let c=n.program?.stages,u=c===void 0?[]:i?await Jb(e,n.tenant,n.slugs.manifest,c):dm(null,[],c),p=await mm(e,n.tenant,i?n.slugs.manifest:null,n),h=i?await e.query(x.workflow.getOfferPublishState,{client:n.tenant,offerKey:n.slugs.manifest}):null;return{manifest:o,smartforms:a,workflow:l,addresses:d,stages:u,capacities:p,publishPending:h?.draftDiffersFromExternal??null,draftRevision:h?.draftRevision??null,externalHeadRevision:h?.externalHeadRevision??null}}s(Lv,"diffOffer");function Om(e){if(e.type==="governedDocument"){let t=e.production;return t==="resolver"?"resolver":t==="template"?"template":t==="upload"||t==="none"?"manual":"unauthored"}return null}s(Om,"contractProductionModeOf");function w0(e){return Om(e)==="resolver"}s(w0,"isResolverCarrierNode");function _m(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Jr(n);return!w0(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(_m,"authoredPins");var k0={type:"address",dataType:"composite"};var b0={type:"boolean",dataType:"boolean"};var v0={type:"consent",dataType:"boolean"};var x0={type:"date",dataType:"date"};var S0={type:"docRef",dataType:"file"};var A0={type:"email",dataType:"text"};var E0={type:"enum",dataType:"option"};var T0={type:"string",dataType:"text"};var $0={type:"tel",dataType:"text"};var Nm={address:k0.dataType,boolean:b0.dataType,consent:v0.dataType,date:x0.dataType,docRef:S0.dataType,email:A0.dataType,enum:E0.dataType,string:T0.dataType,tel:$0.dataType};function Mv(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Mv,"shapeOf");function R0(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,Mv(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,Mv(l)))),o.repeated?.forEach(a=>n.push({key:a.key,itemTemplate:a.itemTemplate,effects:a.effects??[]})),o.subsections?.forEach(r)},"visit");e.sections.forEach(r);let i=[{pathPrefix:"",effects:e.effects??[],shapes:t}];for(let o of n){let a=new Map(t);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,Mv(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(R0,"fieldMapScopes");function _5(e){let t=new Set,n=s(r=>{r.computed?.forEach(i=>t.add(i.key)),r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(_5,"computedKeysOf");function I0(e){let t=[],n=_5(e);for(let r of R0(e))r.effects.forEach((i,o)=>{if(i.kind!=="fieldMap")return;let a=new Map;i.mappings.forEach((l,d)=>{let c=`${r.pathPrefix}effects[${o}].mappings[${d}]`;n.has(l.from)&&t.push({severity:"error",path:`${c}.from`,code:"fieldmap.computed-source",message:`Effect '${i.id}' fieldMap '${l.from}' \u2192 '${l.to}': '${l.from}' is a computed field. Its value is derived, never stored, and would never reach the party.`});let u=a.get(l.to);u!==void 0&&u!==l.from?t.push({severity:"error",path:`${c}.to`,code:"fieldmap.duplicate-target",message:`Effect '${i.id}' maps both '${u}' and '${l.from}' onto custom field '${l.to}'. One party field holds one value \u2014 the write would keep one and drop the other.`}):a.set(l.to,l.from)})});return t}s(I0,"validateFieldMapSources");function O0(e){let t=[],n=new Set;for(let o of R0(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)n.add(l.from);let r=s((o,a)=>{let l=a.some(d=>n.has(d));o.kind==="cf_value"&&!l?t.push({severity:"error",path:`field '${o.key}'`,code:"persist.cf-unmapped",message:`Field '${o.key}' declares kind 'cf_value' but is not the source of any fieldMap mapping. Either wire a fieldMap ('${o.key}' \u2192 a custom-field key) or set kind: 'control'.`}):o.kind==="control"&&l&&t.push({severity:"error",path:`field '${o.key}'`,code:"persist.control-mapped",message:`Field '${o.key}' declares kind 'control' but is used as a fieldMap source, which would persist it. Set kind: 'cf_value', or remove the fieldMap mapping (a control field may still feed OutcomeDef.output.fields).`})},"check"),i=s(o=>{o.fields.forEach(a=>r(a,[a.key])),o.groups?.forEach(a=>a.fields.forEach(l=>r(l,[l.key]))),o.repeated?.forEach(a=>a.itemTemplate.forEach(l=>r(l,[`$item.${l.key}`,l.key]))),o.subsections?.forEach(i)},"visit");return e.sections.forEach(i),t}s(O0,"validateFieldPersistence");var N5="$";function C5(e){return typeof e=="string"&&e.startsWith(N5)}s(C5,"isRef");function Cm(e){return e.slice(1)}s(Cm,"stripRef");function*P5(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let t of Object.values(e.meta))yield t;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(P5,"refSlots");function D5(e){let t=new Set;for(let n of P5(e))C5(n)&&t.add(Cm(n));return[...t]}s(D5,"collectRefs");function F5(e){let t=new Set(e.map(o=>o.id)),n=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),n.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of D5(o))t.has(a)&&(n.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=Cm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Cm(l.target)===a||l.kind==="shareValue"&&Cm(l.to)===a)||n.get(o.id).includes(l.id)||(n.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:n,successors:r,byId:i}}s(F5,"buildAdjacency");function _0(e){let{refsOf:t}=F5(e),r=Jf(e.map(i=>i.id),i=>(t.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(_0,"detectCycle");function N0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(N0,"escapeRegExp");function Wi(e){return new RegExp(`^${N0(e)}\\[(\\d+)\\]\\.(.+)$`)}s(Wi,"repeatedRowKeyPattern");function qv(e,t){let n=Wi(t),r=0;for(let i of Object.keys(e)){let o=i.match(n);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(qv,"countRepeatedRows");function C0(e,t,n){let r=Wi(t);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==n)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(C0,"repeatedRowHasData");function P0(e){return e.endsWith(".count")?e.slice(0,-6):e}s(P0,"readKeyOf");function Kv(e){return{sections:e,fields:[]}}s(Kv,"hiddenSectionsOnly");function D0(e,t,n){for(let r of e.fields)t.add(r.key);for(let r of e.groups??[])for(let i of r.fields)t.add(i.key);for(let r of e.computed??[])t.add(r.key);for(let r of e.repeated??[])n.add(r.key);for(let r of e.subsections??[])D0(r,t,n)}s(D0,"collectKeys");function F0(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;D0(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(Wi)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(F0,"restrictedSectionsOf");function L0(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(L0,"matchesKey");function L5(e,t){return t.find(n=>L0(e,n))??null}s(L5,"hiddenSectionOfKey");function M5(e,t){for(let n=e;;){if(L0(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(M5,"fieldOwnsKey");function q5(e,t){return t.find(n=>M5(e,n))??null}s(q5,"restrictedFieldOfKey");function K5(e,t){let n=L5(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=q5(e,t.fields);return r===null?null:{kind:"field",field:r}}s(K5,"hiddenOwnerOfKey");function Pm(e,t){return K5(e,t)!==null}s(Pm,"isKeyHidden");function j5(e,t,n,r,i){let o=[];r&&o.push({severity:"error",path:n,code:"section.visibleTo-nested",message:{de:`Abschnitt '${e}' liegt in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) und darf selbst keine tragen.`,en:`Section '${e}' sits inside a section with restricted visibility (visibleTo) and may not carry one itself.`}});let a=s(l=>typeof l!="string"||l.trim()==="","isBlank");if((t.length===0||t.some(a)||new Set(t).size!==t.length)&&o.push({severity:"error",path:n,code:"section.visibleTo-invalid",message:{de:`Abschnitt '${e}': visibleTo braucht mindestens ein Team, ohne leere oder doppelte Eintr\xE4ge.`,en:`Section '${e}': visibleTo needs at least one team, with no blank or repeated entries.`}}),i===void 0)return o;for(let l of t)a(l)||i.has(l)||o.push({severity:"error",path:n,code:"section.visibleTo-unknown",message:{de:`Abschnitt '${e}': '${l}' ist weder ein Team noch eine Rechtegruppe dieser Schule.`,en:`Section '${e}': '${l}' is neither a team nor a permission group of this school.`}});return o}s(j5,"visibleToListIssues");function M0(e,t,n){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...j5(c.id,h,`${u}.visibleTo`,p,n));let w=p||h!==void 0;if(w){let k=[...c.fields,...(c.groups??[]).flatMap(y=>y.fields),...(c.repeated??[]).flatMap(y=>y.itemTemplate)];for(let y of k)y.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${y.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${y.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,y)=>i(k,`${u}.subsections[${y}]`,w))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=F0(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=Kv(p);for(let w of It(c)){let k=P0(w);(Pm(w,h)||Pm(k,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${w}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${w}' from a section with restricted visibility (visibleTo) \u2014 whoever cannot see the section would get a different result here.`}})}},"checkAst"),l=s((c,u,p)=>{a(c.visibleIf,`${u}.visibleIf`,p),a(c.requiredIf,`${u}.requiredIf`,p),a(c.disabledIf,`${u}.disabledIf`,p),a(c.defaultValue,`${u}.defaultValue`,p),c.sameAs!==void 0&&Pm(c.sameAs.source,Kv(p))&&r.push({severity:"error",path:`${u}.sameAs`,code:"section.visibleTo-read-outside",message:{de:`${u} \xFCbernimmt '${c.sameAs.source}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo).`,en:`${u} copies '${c.sameAs.source}' from a section with restricted visibility (visibleTo).`}})},"checkField"),d=s((c,u,p)=>{let h=c.visibleTo!==void 0?c.id:p,w=o.filter(k=>k.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:w),c.fields.forEach((k,y)=>l(k,`${u}.fields[${y}]`,w)),c.groups?.forEach((k,y)=>{a(k.visibleIf,`${u}.groups[${y}].visibleIf`,w),k.fields.forEach((v,A)=>l(v,`${u}.groups[${y}].fields[${A}]`,w))}),c.repeated?.forEach((k,y)=>{a(k.itemVisibleIf,`${u}.repeated[${y}].itemVisibleIf`,w),k.itemTemplate.forEach((v,A)=>l(v,`${u}.repeated[${y}].itemTemplate[${A}]`,w))}),c.computed?.forEach((k,y)=>a(k.expression,`${u}.computed[${y}]`,w)),c.subsections?.forEach((k,y)=>d(k,`${u}.subsections[${y}]`,h))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(M0,"sectionVisibilityIssues");var jr="#";var q0=s(e=>{let t=hk.find(n=>n.systemColumn===e);return t===void 0&&F(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),vr={firstName:q0("persons.firstName"),lastName:q0("persons.lastName")};function K0(e,t){let n={firstName:[],lastName:[]},r=`$${e}`;for(let i of t)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===vr.firstName?n.firstName.push(o):a===vr.lastName&&n.lastName.push(o);return n}s(K0,"personNameKeys");function j0(e){return[...e.firstName,...e.lastName]}s(j0,"personNameKeyList");function V0(e){return e.firstName.length>0||e.lastName.length>0}s(V0,"hasPersonName");function Aa(e,t=[],n){let r=[];return e.forEach((i,o)=>{let a=[...t,o];r.push({section:i,path:a,parentId:n});for(let l of Aa(i.subsections??[],a,i.id))r.push(l)}),r}s(Aa,"walkSections");function V5(e,t){for(let n of e.fields)if(n.key===t)return n;for(let n of e.groups??[])for(let r of n.fields)if(r.key===t)return r;for(let n of e.repeated??[])for(let r of n.itemTemplate)if(r.key===t)return r;return null}s(V5,"findFieldInSection");function B0(e,t){for(let n of Aa(e.sections)){let r=V5(n.section,t);if(r)return{section:n.section,field:r}}return null}s(B0,"findField");var B5=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],U5=["blue","rose","amber","violet","teal","emerald","slate"];function U0(e){return B5.includes(e)}s(U0,"isBucketIconName");function G0(e){return U5.includes(e)}s(G0,"isBucketColorName");var G5="__clear__";function z0(e){return e===""?"empty":e===G5?"reserved":null}s(z0,"selectOptionValueDefect");var jv=XP.docRef.allowedMime;function Z0(e,t={}){let n=ra(e).compiled,r=[],i=new Set,o=new Map,a=new Set,l=new Set,d=new Set,c=new Map,u=new Map;function p(O,N){if(i.has(O))return;i.add(O);let K=o.get(O.id);K&&K!==O?r.push({severity:"error",path:`sections[${N.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let P=`sections[${N.join(".")}]`;O.fields.forEach((U,se)=>{Ea(a,U.key,`${P}.fields[${se}]`,"duplicate.field-key",r),l.add(U.key),u.set(U.key,U),c.set(U.key,Bv(U)),U.externalFlag&&(U.type!=="boolean"&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${U.key}' muss den Typ 'boolean' haben (ist '${U.type}').`,en:`External flag '${U.key}' must be type 'boolean' (got '${U.type}').`}}),U.reviewRequired!==void 0&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"review.on-flag",message:{de:`Externes Flag '${U.key}' ist als pr\xFCfpflichtig markiert \u2014 ein Flag setzt der Prozess, die Familie reicht nichts ein, was jemand pr\xFCfen k\xF6nnte.`,en:`External flag '${U.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),U.notice!==void 0&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${U.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${U.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),U.defaultValue==null&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"flag.missing-default",message:{de:`Externes Flag '${U.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${U.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...Y0(U,`${P}.fields[${se}]`)),r.push(...W0(U,`${P}.fields[${se}]`))}),O.groups?.forEach((U,se)=>{U.fields.forEach((le,De)=>{Ea(a,le.key,`${P}.groups[${se}].fields[${De}]`,"duplicate.field-key",r),l.add(le.key),u.set(le.key,le),c.set(le.key,Bv(le)),le.externalFlag&&r.push({severity:"error",path:`${P}.groups[${se}].fields[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${le.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${le.key}' must be a direct section field, not a group field.`}}),r.push(...Y0(le,`${P}.groups[${se}].fields[${De}]`)),r.push(...W0(le,`${P}.groups[${se}].fields[${De}]`))})}),O.repeated?.forEach((U,se)=>{U.itemTemplate.forEach((le,De)=>{Ea(a,le.key,`${P}.repeated[${se}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(le.key,Bv(le)),le.externalFlag&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${le.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${le.key}' must be a direct section field, not a repeated item field.`}}),le.export&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"export.in-repeated",message:{de:`Feld '${le.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${le.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),le.sameAs&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${le.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${le.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),le.reviewRequired!==void 0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"review.in-repeated",message:{de:`Feld '${le.key}' ist in einem itemTemplate einer Wiederholung als pr\xFCfpflichtig markiert \u2014 ein Zeilenfeld hat je Zeile einen Wert, kein Feld der Bewerbung, das man einmal abhaken k\xF6nnte.`,en:`Field '${le.key}' is marked as requiring review inside a repeated itemTemplate \u2014 a row field has one value per row, no field of the application to tick once.`}}),le.notice!==void 0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.notice-in-repeated",message:{de:`Feld '${le.key}' tr\xE4gt einen Hinweis (notice) in einem itemTemplate einer Wiederholung \u2014 dort wird er nicht angezeigt. Den Hinweis an den Abschnitt setzen.`,en:`Field '${le.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),le.type==="docRef"&&le.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${le.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${le.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(U=>{d.add(U.key),Ea(a,U.key,`${P}.computed[${U.key}]`,"duplicate.field-key",r),U.exportType==="consent"&&r.push({severity:"error",path:`${P}.computed[${U.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${U.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${U.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),U.export===!0&&U.exportType===void 0&&r.push({severity:"error",path:`${P}.computed[${U.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${U.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${U.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((U,se)=>p(U,[...N,se]))}s(p,"visitRawSection"),e.sections.forEach((O,N)=>p(O,[N]));let h=new Set;n.effects.forEach((O,N)=>{Ea(h,O.id,`effects[${N}]`,"duplicate.effect-id",r)});let w=new Set;n.outcomes.forEach((O,N)=>{Ea(w,O.id,`outcomes[${N}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,N)=>{O.output.effectRefs?.forEach((K,P)=>{h.has(K.effect)||r.push({severity:"error",path:`outcomes[${N}].output.effectRefs[${P}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${O.id}' verweist auf den unbekannten Effekt '${K.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${K.effect}'.`}})})}),n.outcomes.forEach((O,N)=>{O.output.fields?.forEach((K,P)=>{B0(n,K.path)||r.push({severity:"error",path:`outcomes[${N}].output.fields[${P}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${K.path}'.`,en:`Outcome '${O.id}' references unknown field '${K.path}'.`}})})});let k=new Set;for(let O of Aa(n.sections))for(let N of O.section.repeated??[])k.add(`${N.key}.count`);for(let O of k)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let y={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...pN(e)),r.push(...M0(e,n,t.visibleToKeys)),r.push(...YN(e)),r.push(...cN(e,t.stageKeys));for(let O of Aa(n.sections)){let N=O.section,K=`sections[${O.path.join(".")}]`;N.visibleIf&&(xr(N.visibleIf,`${K}.visibleIf`,y,!1,r),Ta(N.visibleIf,`${K}.visibleIf`,c,r)),N.fields.forEach((P,U)=>Vv(P,`${K}.fields[${U}]`,y,!1,c,r)),N.groups?.forEach((P,U)=>{P.visibleIf&&(xr(P.visibleIf,`${K}.groups[${U}].visibleIf`,y,!1,r),Ta(P.visibleIf,`${K}.groups[${U}].visibleIf`,c,r)),P.fields.forEach((se,le)=>Vv(se,`${K}.groups[${U}].fields[${le}]`,y,!1,c,r))}),N.repeated?.forEach((P,U)=>{P.itemVisibleIf&&(xr(P.itemVisibleIf,`${K}.repeated[${U}].itemVisibleIf`,y,!0,r),Ta(P.itemVisibleIf,`${K}.repeated[${U}].itemVisibleIf`,c,r)),P.itemTemplate.forEach((se,le)=>Vv(se,`${K}.repeated[${U}].itemTemplate[${le}]`,y,!0,c,r)),P.effects?.forEach((se,le)=>{se.when&&xr(se.when,`${K}.repeated[${U}].effects[${le}].when`,y,!0,r)})}),N.computed?.forEach((P,U)=>xr(P.expression,`${K}.computed[${U}].expression`,y,!1,r))}n.effects.forEach((O,N)=>{O.when&&xr(O.when,`effects[${N}].when`,y,!1,r)}),n.outcomes.forEach((O,N)=>{xr(O.when,`outcomes[${N}].when`,y,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function A(O,N){O.requiredFor&&O.requiredFor.forEach((K,P)=>{v.has(K)||r.push({severity:"error",path:`${N}.requiredFor[${P}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${K}"`,en:`field "${O.key}": requiredFor references unknown outcome "${K}"`}})})}s(A,"checkRequiredFor");for(let O of Aa(n.sections)){let N=O.section,K=`sections[${O.path.join(".")}]`;N.fields.forEach((P,U)=>A(P,`${K}.fields[${U}]`)),N.groups?.forEach((P,U)=>{P.fields.forEach((se,le)=>A(se,`${K}.groups[${U}].fields[${le}]`))}),N.repeated?.forEach((P,U)=>{P.itemTemplate.forEach((se,le)=>A(se,`${K}.repeated[${U}].itemTemplate[${le}]`))})}function E(O,N){let K=s((P,U)=>{let se=(P.type==="docRef"?P.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!jv.includes(Ee));se.length>0&&r.push({severity:"error",path:U,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${P.key}' erlaubt ${se.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${jv.join(", ")}).`,en:`Field '${P.key}' allows ${se.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${jv.join(", ")}).`}});let le=P.type==="docRef"?P.docRefConstraints?.minFiles:void 0;if(le!==void 0){let Ee=P.docRefConstraints?.multiple===!0,ft=typeof le=="number"&&Number.isInteger(le)&&le>=2;(!Ee||!ft)&&r.push({severity:"error",path:U,code:"config.docref-min-files",message:Ee?{de:`Feld '${P.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(le)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${P.key}' sets docRefConstraints.minFiles to ${JSON.stringify(le)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${P.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${P.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}P.multiple===!0&&P.type!=="enum"&&r.push({severity:"error",path:U,code:"config.multiple-non-enum",message:{de:`Feld '${P.key}' setzt multiple: true, hat aber den Typ '${P.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(P.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${P.key}' sets multiple: true but is type '${P.type}' \u2014 only 'enum' supports multi-select.`+(P.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),P.presentation==="yesNo"&&P.type!=="boolean"&&r.push({severity:"error",path:U,code:"config.yesno-non-boolean",message:{de:`Feld '${P.key}' setzt presentation: 'yesNo', hat aber den Typ '${P.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${P.key}' sets presentation: 'yesNo' but is type '${P.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),P.presentation==="yesNo"&&P.defaultValue!=null&&r.push({severity:"error",path:U,code:"config.yesno-default",message:{de:`Feld '${P.key}' ist eine Ja | Nein-Frage (presentation: 'yesNo') mit einem defaultValue \u2014 die Familie muss die Antwort selbst w\xE4hlen. Den defaultValue entfernen.`,en:`Field '${P.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...W5(P,U)),typeof P.minSelections=="number"&&typeof P.maxSelections=="number"&&P.minSelections>P.maxSelections&&r.push({severity:"error",path:U,code:"config.min-gt-max-selections",message:{de:`Feld '${P.key}' hat minSelections (${P.minSelections}) > maxSelections (${P.maxSelections}).`,en:`Field '${P.key}' has minSelections (${P.minSelections}) > maxSelections (${P.maxSelections}).`}}),r.push(...Y5(P,U));let De=P.enumRef;De!==void 0&&r.push({severity:"error",path:`${U}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${P.key}' nennt den entfernten Options-Katalog (enumRef '${String(De)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${P.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(P.enumOptions??[]).forEach((Ee,ft)=>{let He=z0(Ee);He!==null&&r.push({severity:"error",path:`${U}.enumOptions[${ft}]`,code:"config.enum-option-value",message:{de:He==="empty"?`Feld '${P.key}' hat einen leeren Enum-Optionswert \u2014 das Steuerelement kann ihn nicht tragen. Der Option einen Wert geben oder sie streichen: Ein Feld, das unbeantwortet bleiben darf, bietet bereits eine eigene Zeile zum Leeren.`:`Feld '${P.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:He==="empty"?`Field '${P.key}' has an empty enum option value \u2014 the control cannot carry it. Give the option a value, or drop it: a field that may be left unanswered already offers its own clear row.`:`Field '${P.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(P.attachments??[]).forEach((Ee,ft)=>{if("storageId"in Ee){r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${P.key}' tr\xE4gt eine rohe 'storageId' \u2014 Anh\xE4nge nennen eine Bibliotheksdatei jetzt per 'fileKey' (plexus-cli files put, dann field attach --file-key).`,en:`Field '${P.key}' attachment carries a raw 'storageId' \u2014 attachments name a library file by 'fileKey' now (plexus-cli files put, then field attach --file-key).`}});return}let He=Ee.fileKey!==void 0&&Ee.fileKey!=="",vt=Ee.url!==void 0&&Ee.url!=="";He===vt&&r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${P.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${He&&vt?"beide":"keines"}).`,en:`Field '${P.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${He&&vt?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${P.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${P.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");O.fields.forEach((P,U)=>K(P,`${N}.fields[${U}]`)),O.groups?.forEach((P,U)=>{P.fields.forEach((se,le)=>K(se,`${N}.groups[${U}].fields[${le}]`))}),O.repeated?.forEach((P,U)=>{P.itemTemplate.forEach((se,le)=>{let De=`${N}.repeated[${U}].itemTemplate[${le}]`;K(se,De),se.type==="consent"&&r.push({severity:"error",path:De,code:"config.consent-in-repeated",message:{de:`Feld '${se.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${se.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),O.subsections?.forEach((P,U)=>E(P,`${N}.subsections[${U}]`))}s(E,"visitFieldConfig"),e.sections.forEach((O,N)=>E(O,`sections[${N}]`)),e.effects.forEach((O,N)=>{if(O.kind==="person"){r.push(...Q0(O,e.effects,`effects[${N}]`,K=>l.has(K)));return}O.kind==="organization"&&O.nameFrom?.forEach((K,P)=>{l.has(K)||r.push({severity:"error",path:`effects[${N}].nameFrom[${P}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${K}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${K}'.`}})})});let I=s((O,N)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let K=O.display;if(!K){r.push({severity:"error",path:`${N}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}U0(K.icon)||r.push({severity:"error",path:`${N}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${K.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${K.icon}' is not a known bucket icon.`}}),G0(K.color)||r.push({severity:"error",path:`${N}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${K.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${K.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,N)=>I(O,`effects[${N}]`));let C=new Set,$=s(O=>{O.kind==="person"?C.add(O.bucket):O.kind==="organization"&&C.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach($);let b=new Set,R=s(O=>{for(let N of O)N.repeated?.forEach(K=>K.effects?.forEach(P=>$(P))),R(N.subsections??[])},"collectRepeatedBuckets");R(e.sections);let q=s((O,N)=>{C.size!==0&&O.forEach((K,P)=>{K.bucket===void 0||C.has(K.bucket)||r.push({severity:"error",path:`${N}[${P}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${K.key}' geh\xF6rt zum Bucket '${K.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${K.key}' belongs to bucket '${K.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),_=s((O,N)=>{if(b.has(O))return;b.add(O);let K=`sections[${N.join(".")}]`;q(O.fields,`${K}.fields`),O.groups?.forEach((P,U)=>q(P.fields,`${K}.groups[${U}].fields`)),O.repeated?.forEach((P,U)=>q(P.itemTemplate,`${K}.repeated[${U}].itemTemplate`)),O.subsections?.forEach((P,U)=>_(P,[...N,U]))},"visitBucketSection");e.sections.forEach((O,N)=>_(O,[N]));let J=e.effects.flatMap((O,N)=>O.kind==="person"&&O.subject===!0?[{e:O,i:N}]:[]);J.length>1&&J.slice(1).forEach(({e:O,i:N})=>{r.push({severity:"error",path:`effects[${N}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${J[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${J[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,N)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${N}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${N}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((K,P)=>{l.has(K)||r.push({severity:"error",path:`effects[${N}].nationalityFrom[${P}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${K}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${K}'.`}})})}});let Y=e.effects.flatMap((O,N)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:N,decl:O.contractParty}]:[]);if(Y.length>0){let O=new Map;Y.forEach(({e:K,i:P})=>{let U=O.get(K.bucket);if(U===void 0){O.set(K.bucket,K.id);return}r.push({severity:"error",path:`effects[${P}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${K.id}' deklariert eine Vertragspartei auf Bucket '${K.bucket}', aber '${U}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${K.id}' declares a contract party on bucket '${K.bucket}', but '${U}' already does. A bucket is at most one contract party.`}})});let N=Y.filter(({decl:K})=>K.role==="beneficiary");N.slice(1).forEach(({e:K,i:P})=>{r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${K.id}' deklariert contractParty.role 'beneficiary', aber '${N[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${K.id}' declares contractParty.role 'beneficiary', but '${N[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),N.forEach(({e:K,i:P})=>{K.subject!==!0&&r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${K.id}' ist der Leistungsempf\xE4nger des Vertrags, aber nicht das Subjekt der Bewerbung. Leistungsempf\xE4nger und Subjekt der Bewerbung sind dieselbe Person \u2014 subject:true auf '${K.id}' setzen.`,en:`Effect '${K.id}' is the contract beneficiary but not the application subject. The beneficiary and the application subject are the same person \u2014 set subject:true on '${K.id}'.`}})}),J.forEach(({e:K,i:P})=>{let U=K.contractParty?.role;U!==void 0&&U!=="beneficiary"&&r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${K.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${U}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${K.id}' is the application subject but declares contractParty.role '${U}'. The application subject is the contract beneficiary.`}})}),Y.some(({decl:K})=>K.signs===!0)||r.push({severity:"error",path:"effects",code:"contractParty.no-signer",message:{de:"Das Formular deklariert Vertragsparteien, aber keine unterschreibt (contractParty.signs). Ein Vertrag ohne Unterzeichner kann nicht erzeugt werden.",en:"The form declares contract parties, but none signs (contractParty.signs). A contract without a signatory cannot be generated."}})}e.effects.forEach((O,N)=>{O.kind==="fieldMap"&&O.mappings.forEach((K,P)=>{a.has(K.from)||r.push({severity:"error",path:`effects[${N}].mappings[${P}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${O.id}': fieldMap from '${K.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${K.from}' references unknown field.`}})})});for(let[O,N]of u){if(!N.sameAs)continue;let K=`fields[${O}].sameAs`,P=u.get(N.sameAs.source);P===void 0||N.sameAs.source===O?r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:N.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${N.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:N.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' sameAs.source references unknown field '${N.sameAs.source}' (must be a top-level or group field).`}}):P.type!==N.type?r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}' (${N.type}): sameAs.source '${N.sameAs.source}' hat einen anderen Typ (${P.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${N.type}) sameAs.source '${N.sameAs.source}' has a different type (${P.type}) \u2014 the mirror must be shape-identical.`}}):P.sameAs&&r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}': sameAs.source '${N.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${N.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let U=u.get(N.sameAs.toggle);(U===void 0||U.type!=="boolean")&&r.push({severity:"error",path:`${K}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:U===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${N.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${N.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${U.type}').`,en:U===void 0?`Field '${O}' sameAs.toggle references unknown field '${N.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${N.sameAs.toggle}' must be type 'boolean' (got '${U.type}').`}}),N.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${N.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${N.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(N=>O.set(N.id,N.kind)),e.effects.forEach((N,K)=>{if(N.kind!=="shareValue")return;[["from",N.from],["to",N.to]].forEach(([se,le])=>{let De=O.get(le.slice(1));De!==void 0&&De!=="person"&&De!=="organization"&&r.push({severity:"error",path:`effects[${K}].${se}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${N.id}': shareValue ${se} '${le}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${De}').`,en:`Effect '${N.id}' shareValue ${se} '${le}' must reference a person/organization effect (got '${De}').`}})});let P=N.from.slice(1);e.effects.some(se=>se.kind==="fieldMap"&&se.target.slice(1)===P&&se.mappings.some(le=>le.to===N.field)||se.kind==="shareValue"&&se.id!==N.id&&se.to.slice(1)===P&&se.field===N.field)||r.push({severity:"error",path:`effects[${K}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${N.id}' teilt das Feld '${N.field}' aus '${N.from}', aber kein fieldMap mit Ziel '${N.from}' bildet auf '${N.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${N.id}' shares field '${N.field}' from '${N.from}', but no fieldMap targeting '${N.from}' maps to '${N.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((O,N)=>{O.kind==="person"&&O.bucket.includes(jr)&&r.push({severity:"error",path:`effects[${N}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${jr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${jr}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(jr)&&r.push({severity:"error",path:`effects[${N}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${jr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${jr}' (reserved for the per-row namespace).`}})});let ue=new Set;function Q(O,N){O.repeated?.forEach((K,P)=>{let U=K.effects??[];if(U.length>0){let se=`${N}.repeated[${P}]`,le=new Set(U.map(oe=>oe.id)),De=new Set(K.itemTemplate.map(oe=>oe.key)),Ee=(K.uniqueBy?.length??0)>0,ft=s(oe=>oe.startsWith("$item.")?De.has(oe.slice(6)):l.has(oe),"resolvesName"),He=s(oe=>oe.startsWith("$item.")?De.has(oe.slice(6)):a.has(oe),"resolvesFrom"),vt=s(oe=>{let Mt=oe.slice(1);return le.has(Mt)||h.has(Mt)},"resolvesRef");U.forEach((oe,Mt)=>{let pt=`${se}.effects[${Mt}]`;if(h.has(oe.id)||ue.has(oe.id)?r.push({severity:"error",path:pt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${oe.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${oe.id}' is declared more than once.`}}):ue.add(oe.id),oe.kind==="person"||oe.kind==="organization"){I(oe,pt),oe.kind==="person"&&oe.subject===!0&&r.push({severity:"error",path:`${pt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert subject:true \u2014 eine Zeile gilt je Zeile, das Subjekt der Bewerbung je Bewerbung. Das Subjekt an einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${oe.id}' declares subject:true \u2014 a repeated row is per-row, the application subject is per-application. Declare the subject on a top-level effect.`}}),oe.kind==="person"&&oe.nationalityFrom!==void 0&&r.push({severity:"error",path:`${pt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${oe.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),oe.kind==="person"&&oe.contractParty!==void 0&&r.push({severity:"error",path:`${pt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert contractParty \u2014 wer unterschreibt, wird einmal je Bewerbung deklariert, nicht je Zeile. An einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${oe.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ee||r.push({severity:"error",path:se,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${K.key}' hat einen Parteien erzeugenden Effekt '${oe.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${K.key}' has a party-creating effect '${oe.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Fe=oe.kind==="person"?oe.bucket:oe.orgKind;Fe.includes(jr)&&r.push({severity:"error",path:`${pt}.${oe.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${oe.id}' der Wiederholung: ${oe.kind==="person"?"bucket":"orgKind"} '${Fe}' darf '${jr}' nicht enthalten.`,en:`Repeated effect '${oe.id}' ${oe.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${jr}'.`}}),oe.kind==="person"&&r.push(...Q0(oe,U,pt,ft)),oe.kind==="organization"&&oe.nameFrom?.forEach((Be,In)=>{ft(Be)||r.push({severity:"error",path:`${pt}.nameFrom[${In}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${oe.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${oe.id}' nameFrom references unknown field '${Be}'.`}})}),oe.identity?.strategy==="keyed"&&oe.identity.keyFrom.forEach((Be,In)=>{He(Be)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${In}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${oe.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${oe.id}' identity.keyFrom references unknown field '${Be}'.`}})})}else if(oe.kind==="relationship"){if([["from",oe.from],["to",oe.to]].forEach(([Fe,Be])=>{vt(Be)||r.push({severity:"error",path:`${pt}.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${oe.id}' der Wiederholung: ${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${oe.id}' ${Fe} references unknown effect '${Be}'.`}})}),oe.meta)for(let[Fe,Be]of Object.entries(oe.meta))typeof Be=="string"&&Be.startsWith("$")&&!vt(Be)&&r.push({severity:"error",path:`${pt}.meta.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${oe.id}' der Wiederholung: meta.${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${oe.id}' meta.${Fe} references unknown effect '${Be}'.`}})}else oe.kind==="fieldMap"?(vt(oe.target)||r.push({severity:"error",path:`${pt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${oe.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${oe.target}'.`,en:`Repeated fieldMap '${oe.id}' target references unknown effect '${oe.target}'.`}}),oe.mappings.forEach((Fe,Be)=>{He(Fe.from)||r.push({severity:"error",path:`${pt}.mappings[${Be}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${oe.id}' der Wiederholung: from '${Fe.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${oe.id}' from '${Fe.from}' references unknown field.`}})})):oe.kind==="shareValue"&&r.push({severity:"error",path:pt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${oe.id}': shareValue is not supported inside repeated row effects.`}})})}}),O.subsections?.forEach((K,P)=>Q(K,`${N}.subsections[${P}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((O,N)=>Q(O,`sections[${N}]`));let re=_0(n.effects);return re.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${re.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${re.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...z5(e)),r}s(Z0,"validateForm");function z5(e){let t={...e,effects:e.effects.map(X0),sections:e.sections.map(eM),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return np(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:vw(n)}))}s(z5,"missingTranslationIssues");function X0(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(X0,"withoutSubjectFlag");function eM(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(X0)})),subsections:e.subsections?.map(eM)}}s(eM,"withoutRowSubjectFlags");function W0(e,t){let n=e.reviewRequired;return n===void 0||n===!0?[]:[{severity:"error",path:t,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(n)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(n)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(W0,"reviewRequiredShapeIssues");function Y0(e,t){if(!e.export)return[];let n=[];return e.type==="docRef"&&n.push({severity:"error",path:t,code:"export.invalid-type",message:{de:`Feld '${e.key}' (docRef) kann nicht exportiert werden \u2014 ein Speicher-Handle ist kein bindbarer Dokumentwert.`,en:`Field '${e.key}' (docRef) cannot be exported \u2014 a storage handle is not a bindable document value.`}}),e.multiple===!0&&n.push({severity:"error",path:t,code:"export.multiple-enum",message:{de:`Feld '${e.key}' ist eine Mehrfachauswahl \u2014 N gew\xE4hlte Optionen sind kein einzelnes zusammengesetztes Blatt, deshalb nicht exportierbar.`,en:`Field '${e.key}' is a multi-select \u2014 N picked options are not one compound leaf, so it cannot be exported.`}}),n}s(Y0,"exportGateIssues");function Ea(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${H0(r,"de")} '${t}'`,en:`Duplicate ${H0(r,"en")}: '${t}'`}}):e.add(t)}s(Ea,"reportIfDup");function H0(e,t){let n=s((r,i)=>t==="de"?r:i,"label");switch(e){case"duplicate.section-id":return n("Abschnitts-ID","section id");case"duplicate.field-key":return n("Feldschl\xFCssel","field key");case"duplicate.effect-id":return n("Effekt-ID","effect id");case"duplicate.outcome-id":return n("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return n("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s(H0,"labelForCode");function Vv(e,t,n,r,i,o){e.visibleIf&&(xr(e.visibleIf,`${t}.visibleIf`,n,r,o),Ta(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(xr(e.requiredIf,`${t}.requiredIf`,n,r,o),Ta(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(xr(e.disabledIf,`${t}.disabledIf`,n,r,o),Ta(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&xr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(Vv,"checkFieldAsts");function Bv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Bv,"gatingMeta");function Ta(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(J0(o.left,o.right,o.op,t,n,r),J0(o.right,o.left,o.op,t,n,r)),i(o.left),i(o.right);return}case"unary":i(o.operand);return;case"if":i(o.cond),i(o.then),i(o.else);return;case"call":o.args.forEach(i);return;case"arr":o.items.forEach(i);return;default:return}}s(i,"walk"),i(e)}s(Ta,"checkGatingExpr");function J0(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&t.kind==="bool"&&t.value===!1){o.push({severity:"error",path:r,code:"expr.consent-compare-false",message:{de:`Gating-Ausdruck vergleicht die Zustimmung '${e.path}' mit false \u2014 eine Zustimmung ist true oder leer, nie false. '${e.path} != true' verwenden.`,en:`Gating expression compares the consent '${e.path}' to false \u2014 a consent is true or empty, never false. Use '${e.path} != true'.`}});return}a.isBoolean&&(a.hasDefault||t.kind!=="null"&&t.kind==="bool"&&(a.isYesNo&&n==="=="||o.push({severity:"error",path:r,code:"expr.gating-compare-undefaulted-field",message:{de:`Gating-Ausdruck vergleicht das Boolean-Feld '${e.path}' ohne Standardwert per '${n}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${n} ${t.value}' ${n==="=="?"false":"true"} \u2014 das Gate greift stillschweigend bei ungesetzten Werten. Dem Feld '${e.path}' einen 'defaultValue' geben (oder den Ausdruck umschreiben \u2014 z. B. '${e.path} != null' als ausdr\xFCckliche Gesetzt-Pr\xFCfung).`,en:`Gating expression compares undefaulted boolean field '${e.path}' to a bool literal via '${n}'. In three-valued logic, 'undefined ${n} ${t.value}' is ${n==="=="?"false":"true"} \u2014 the gate fires silently for unset values. Add a 'defaultValue' to field '${e.path}' (or rewrite the expression \u2014 e.g. '${e.path} != null' for an explicit set-check).`}})))}}s(J0,"inspectEqualityOperand");function xr(e,t,n,r,i){i.push(...fN(e,n.declaredContext,t)),i.push(...Zf(e,n.stageKeys,t));for(let o of It(e))n.known.has(o)||yw(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:t,code:"ref.unknown-ident",message:{de:o.startsWith("$")?`Bezeichner '${o}' ist kein Geltungsbereich, den ein Formular liest \u2014 Umgebungsvariablen sind '$env.<key>.<field>', Wiederholungszeilen '$item.*'.`:`Bezeichner '${o}' ist weder als Feld, berechneter Schl\xFCssel noch als $item-Slot deklariert.`,en:o.startsWith("$")?`Identifier '${o}' is no scope a form reads \u2014 environment variables are '$env.<key>.<field>', repeated rows '$item.*'.`:`Identifier '${o}' is not declared as a field, computed key, or $item slot.`}})}s(xr,"checkAst");function Q0(e,t,n,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${n}.nameFrom`,code:"person.name-from-removed",message:{de:`Effekt '${e.id}': eine Person hat kein nameFrom mehr \u2014 ihr Name ist die Feldzuordnung (fieldMap) auf ${vr.firstName} / ${vr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${vr.firstName} / ${vr.lastName}. Remove nameFrom.`}});let o=K0(e.id,t);V0(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${vr.firstName} oder ${vr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${vr.firstName} or ${vr.lastName} \u2014 the person would get no name.`}});for(let a of j0(o))r(a)||i.push({severity:"error",path:n,code:"ref.unknown-name-field",message:{de:`Effekt '${e.id}': der Name wird aus '${a}' gelesen, das kein eingegebenes Feld ist.`,en:`Effect '${e.id}': its name is read from '${a}', which is not an entered field.`}});return i}s(Q0,"personNameIssues");function W5(e,t){let n=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&n.push({severity:"error",path:t,code:"config.consent-default",message:{de:`Feld '${e.key}' ist eine Zustimmung mit einem defaultValue \u2014 zustimmen muss die Familie selbst. Den defaultValue entfernen.`,en:`Field '${e.key}' is a consent with a defaultValue \u2014 the family must give it themselves. Remove the defaultValue.`}}),e.sameAs!==void 0&&n.push({severity:"error",path:t,code:"config.consent-computed",message:{de:`Feld '${e.key}' ist eine Zustimmung, die ein anderes Feld spiegelt (sameAs) \u2014 zustimmen muss die Familie selbst. sameAs entfernen.`,en:`Field '${e.key}' is a consent mirroring another field (sameAs) \u2014 the family must give it themselves. Remove sameAs.`}}),r||n.push({severity:"error",path:t,code:"config.consent-not-required",message:{de:`Feld '${e.key}' ist eine Zustimmung, die nie verlangt wird \u2014 required: true oder requiredIf setzen, sonst Typ 'boolean' verwenden.`,en:`Field '${e.key}' is a consent nobody is asked to give \u2014 set required: true or requiredIf, or use type 'boolean'.`}})),e.type==="boolean"&&r&&e.defaultValue?.trim()==="false"&&n.push({severity:"warning",path:t,code:"config.boolean-required-default-false",message:{de:`Feld '${e.key}' ist ein Ja/Nein-Pflichtfeld, vorbelegt mit Nein \u2014 es gilt von Anfang an als ausgef\xFCllt. Ist es eine Zustimmung, Typ 'consent' verwenden.`,en:`Field '${e.key}' is a required yes/no preset to No \u2014 it counts as answered from the start. If it is a consent, use type 'consent'.`}}),n}s(W5,"consentConfigIssues");function Y5(e,t){let n=e.exclusiveOptions;if(n===void 0)return[];let r=s((a,l)=>[{severity:"error",path:t,code:"config.exclusive-options",message:{de:a,en:l}}],"refuse");if(e.type!=="enum"||e.multiple!==!0)return r(`Feld '${e.key}' setzt exclusiveOptions ohne Mehrfachauswahl \u2014 exklusive Optionen gibt es nur bei type: 'enum' mit multiple: true.`,`Field '${e.key}' sets exclusiveOptions without a multi-select \u2014 exclusive options exist only on type: 'enum' with multiple: true.`);if(e.enumListKey!==void 0)return r(`Feld '${e.key}' setzt exclusiveOptions auf einer Liste des Mandanten (enumListKey) \u2014 exklusive Optionen brauchen eigene enumOptions.`,`Field '${e.key}' sets exclusiveOptions on a tenant list (enumListKey) \u2014 exclusive options need inline enumOptions.`);if(!Array.isArray(n)||n.length===0||n.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(n)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(n)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=n.filter(a=>!i.includes(a));return o.length>0?r(`Feld '${e.key}' nennt in exclusiveOptions ${o.map(a=>`'${a}'`).join(", ")} \u2014 keine Option des Feldes.`,`Field '${e.key}' names ${o.map(a=>`'${a}'`).join(", ")} in exclusiveOptions \u2014 not an option of the field.`):new Set(n).size!==n.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(Y5,"exclusiveOptionIssues");var H5="blocked";function tM(e,t){let n={values:t};for(let r of e.outcomes){let i;try{i=gt(r.when,n)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(J5(i))return r.id===H5?null:r.id}return null}s(tM,"resolveActiveOutcome");function J5(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(J5,"truthy");function nM(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(nM,"isScalar");function Q5(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(nM(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))nM(a)&&(t[`${r}.${o}`]=a)}Z5(e,t,n)}s(Q5,"mergeRecord");function Z5(e,t,n){let r=new Set(n);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);Wi(a).test(i)&&r.add(a)}for(let i of r){let o=qv(e,i),a=0;for(let l=0;l<o;l++)C0(e,i,l)&&a++;t[`${i}.count`]=a}}s(Z5,"mergeRepeatedCounts");function rM(e,t,n){let r={...n};return Q5(e,r,t),r}s(rM,"flattenValues");function Uv(e,t,n){return{code:e,fieldKey:t,text:n}}s(Uv,"submitIssue");function iM(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(iM,"truthyEval");function oM(e){if(e==null)return!0;if(typeof e=="string")return e.trim()==="";if(Array.isArray(e))return e.length===0;if(typeof e=="object"){let t=e;if("storageId"in t)return!(typeof t.storageId=="string"&&t.storageId.trim()!=="");let n=t;return!n.street?.trim()||!n.hausnr?.trim()||!n.plz?.trim()||!n.ort?.trim()||!n.land?.trim()}return!1}s(oM,"isEmptyValue");function X5(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=iM(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(X5,"fieldIsLiveRequired");function eQ(e,t,n){return sM(e,t,n).evalCtx}s(eQ,"buildSubmitEvalContext");function sM(e,t,n){let r=tQ(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[w,k]of Object.entries(t))(r(w)===null||o.has(w))&&(l[w]=k);let d=aM(e,l,n),c=new Set,u=new Set;dM(e,d,w=>c.add(w.key),w=>u.add(w.key));let p=new Set(i.filter(w=>{let k=r(w);return k.kind==="field"?c.has(w):u.has(k.repeatedKey)}));if(p.size===o.size&&[...p].every(w=>o.has(w))){let w={};for(let k of i)o.has(k)||(w[k]=t[k]);return{visible:l,hidden:w,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let w=i.filter(k=>p.has(k)!==o.has(k));F(`[smartForm] visibility of ${w.join(", ")} does not settle \u2014 each depends on whether the other's value counts. The form's visibleIf conditions are contradictory.`)}a.add(h),o=p}}s(sM,"splitWithContext");function tQ(e){let t=new Map,n=[];for(let r of Fm(e.sections)){for(let i of r.fields)t.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)t.set(o.key,o);for(let i of r.repeated??[])n.push({key:i.key,pattern:Wi(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=t.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of n){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(tQ,"fieldOwnership");function aM(e,t,n){let r=[];for(let o of Fm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=rM(t,r,n);for(let o of Fm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(aM,"rawEvalContext");function lM(e,t,n){let{values:r,defaulted:i}=nQ(e,t,n),o=sM(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(lM,"splitDraftValues");function nQ(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of Fm(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||t[d.key]!=null||r?.(d.key))continue;a??=aM(e,t,n);let c;try{c=gt(d.defaultValue,{values:a})}catch(u){F(`[smartForm] defaultValue of '${d.key}' does not evaluate: ${u instanceof Error?u.message:String(u)}`)}c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(nQ,"applyFieldDefaults");function Fm(e){let t=[],n=s(r=>{t.push(r);for(let i of r.subsections??[])n(i)},"walk");for(let r of e)n(r);return t}s(Fm,"walkSectionsDeep");function rQ(e,t,n,r=!1){if(oM(t))return null;let i=n.fields[e.type];i||F(`[fieldFormatIssue] no field provider registered for type "${e.type}" (field "${e.key}"). Register it in the domain form registry.`);let o=i.validate(e,t,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(rQ,"fieldFormatIssue");function iQ(e,t){return oM(t)||e.type==="consent"&&t!==!0}s(iQ,"isUnanswered");function Dm(e,t){if(!e)return!0;try{return iM(gt(e,{values:t}))}catch{return!1}}s(Dm,"isVisibleUnder");function dM(e,t,n,r){let i=s(o=>{if(Dm(o.visibleIf,t)){for(let a of o.fields)Dm(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(Dm(a.visibleIf,t))for(let l of a.fields)Dm(l.visibleIf,t)&&n(l);if(r!==void 0)for(let a of o.repeated??[])r(a);for(let a of o.subsections??[])i(a)}},"walk");for(let o of e.sections)i(o)}s(dM,"forEachVisibleField");function cM(e,t,n,r={}){let i=eQ(e,t,n),o=[],a=tM(e,i);a===null&&r.requireOutcome!==!1&&o.push(Uv("no-outcome",null,{de:"Die Angaben ergeben keinen g\xFCltigen Abschluss \u2014 bitte pr\xFCfen Sie das Formular.",en:"The answers do not lead to a valid outcome \u2014 please check the form."}));let l=new Set(r.exemptFromRequired??[]);return dM(e,i,d=>{let c=t[d.key];if(iQ(d,c)){!l.has(d.type)&&X5(d,i,a)&&o.push(Uv("required",d.key,hl([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=rQ(d,c,r.registry,r.testMode===!0);u!==null&&o.push(Uv("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(cM,"checkSubmittable");function uM(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=ra(e),r=[];for(let i of t){let o=i.prefill??{};if(!aN(e,i.env))continue;let a=dN(e,i.env),{visible:l}=lM(n,o,a),d=cM(n,l,a,{exemptFromRequired:["docRef"]});for(let c of d.issues){if(c.code==="no-outcome"){r.push({severity:"error",path:`scenario:${i.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${i.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${i.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}});continue}if(c.code==="required"){r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${i.label.de}" l\xE4sst das Pflichtfeld ${c.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${i.label.en}" leaves the required field ${c.fieldKey} empty \u2013 no valid outcome.`}});continue}r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.invalid-value",message:hl([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(uM,"validateScenarios");function Lm(e){return e.filter(t=>(t.severity??"error")==="error")}s(Lm,"blockingIssues");function Mm(e,t={}){return[...Z0(e,t),...uM(e)]}s(Mm,"runFormValidators");function qm(e){return Lm(e)}s(qm,"blockingFormErrors");function fM(e,t,n){return vC(e,t,n)}s(fM,"runWorkflowValidators");function pM(e){return Lm(e)}s(pM,"blockingWorkflowErrors");var oQ=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],mM={join:{required:[],optional:[]},end:{required:[],optional:[]},eventTrigger:{required:[],optional:[]},form:{required:[],optional:["adoptForm","formExports"]},roleAssign:{required:[],optional:[]},setFlag:{required:[],optional:[]},if:{required:["condition"],optional:[]},countersign:{required:["contract"],optional:["signing","titles"]},engagePush:{required:["form"],optional:["contract","engage","payment"]},decision:{required:[],optional:["commentRequired","decisionAsTask","formView","reads","requiresOneOf"]},review:{required:[],optional:["commentRequired","decisionAsTask","form"]},waitlist:{required:[],optional:[]},completenessCheck:{required:["deadline","requires"],optional:[]},collectPayment:{required:[],optional:[]},governedDocument:{required:["approval","production","responseStrategy"],optional:["confirmBeforeIssue","confirmContractTerms","contractTermsQuestionText","form","generatorStamp","reads","responseLabels","templateStamp","titles"]}},fn={id:m.string(),label:Bi,actionTeams:m.optional(m.any()),artifacts:m.optional(m.any()),assign:m.optional(m.any()),inputs:m.optional(m.any()),library:m.optional(m.any()),next:m.optional(m.any()),notifications:m.optional(m.any()),optionalActions:m.optional(m.any()),outcomes:m.optional(m.any()),outputLabels:m.optional(m.any()),sublabel:m.optional(m.any()),tasks:m.optional(m.any())},sQ=m.object({...fn,type:m.literal("join")}),aQ=m.object({...fn,type:m.literal("end")}),lQ=m.object({...fn,type:m.literal("eventTrigger")}),dQ=m.object({...fn,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),cQ=m.object({...fn,type:m.literal("roleAssign")}),uQ=m.object({...fn,type:m.literal("setFlag")}),fQ=m.object({...fn,type:m.literal("if"),condition:m.optional(m.any())}),pQ=m.object({...fn,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),mQ=m.object({...fn,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),hQ=m.object({...fn,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),formView:m.optional(m.any())}),gQ=m.object({...fn,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),yQ=m.object({...fn,type:m.literal("waitlist")}),wQ=m.object({...fn,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),kQ=m.object({...fn,type:m.literal("collectPayment")}),bQ=m.object({...fn,type:m.literal("governedDocument"),approval:m.optional(m.any()),confirmBeforeIssue:m.optional(m.any()),confirmContractTerms:m.optional(m.any()),contractTermsQuestionText:m.optional(m.any()),form:m.optional(m.any()),generatorStamp:m.optional(m.any()),production:m.optional(m.any()),reads:m.optional(m.any()),responseLabels:m.optional(m.any()),responseStrategy:m.optional(m.any()),templateStamp:m.optional(m.any()),titles:m.optional(m.any())}),aLe=m.union(sQ,aQ,lQ,dQ,cQ,uQ,fQ,pQ,mQ,hQ,gQ,yQ,wQ,kQ,bQ);function hM(e){let t=[];return e.forEach((n,r)=>{if(n===null||typeof n!="object"||Array.isArray(n)){t.push(`graph.nodes[${r}]: a node must be an object`);return}let i=n,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&t.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in mM)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=mM[a],d=new Set(["id","type","label",...oQ,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||t.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),t}s(hM,"workflowNodeEnvelopeIssues");function gM(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(gM,"inlineEnumOptionLabel");var wM={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function kM(e){return wM[e]!==void 0}s(kM,"isExportableFieldType");function vQ(e){return e.exportType===void 0&&F(`formExports: computed '${e.key}' is exported without an exportType \u2014 the publish validator should have refused this form.`),{key:e.key,type:e.exportType,label:e.label??{de:e.key,en:e.key}}}s(vQ,"leafForComputed");function yM(e){let t=wM[e.type];return t===void 0&&F(`formExports: field '${e.key}' has type '${e.type}', which is not exportable \u2014 the publish validator should have refused this form.`),{key:e.key,type:t,label:e.label,...e.enumOptions!==void 0?{enumOptions:e.enumOptions.map(n=>({value:n,label:gM(e,n)}))}:{}}}s(yM,"leafFor");function Gv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(yM(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(yM(o));for(let i of r.computed??[])i.export===!0&&t.push(vQ(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(Gv,"exportedFormLeaves");var bM=s(e=>e,"asEffectId"),Yi=s(e=>e,"asOutcomeId"),$a=s(e=>e,"asSectionId"),tn=s(e=>e,"asFieldKey");var Sr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Cd=["person","organization","relationship","fieldMap"],Hi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],Ra=["fresh","keyed","manual"];function Qo(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new Error(`${n}: ${r}-en needs ${r} too`);return}return st(e,t,n,r)}s(Qo,"optionalLocalizedText");function zt(e,t){if(!(e===void 0||e===""))try{Rt(e)}catch(n){throw new Error(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(zt,"assertExpression");function Pd(e){return Object.keys(e.smartforms??{})}s(Pd,"carriedFormSlugs");function zv(e){let n=e.workflow?.graph?.nodes??[],r=[];for(let i of n){if(i.type!=="form")continue;let o=i.inputs?.smartForm;o?.kind==="literal"&&typeof o.value=="string"&&o.value&&r.push(o.value)}return r}s(zv,"boundFormSlugs");function Km(e,t){let n=Pd(e);if(t){if(!n.includes(t))throw new Error(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new Error(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(Km,"resolveFormSlug");function jm(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(jm,"getForm");function jn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(jn,"walkSections");function or(e,t){return jn(e).find(n=>n.id===t)}s(or,"findSection");function Zo(e,t){for(let n of jn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Zo,"findField");function Xo(e){let t=new Set;for(let n of jn(e))n.fields.forEach(r=>t.add(r.key)),n.groups?.forEach(r=>r.fields.forEach(i=>t.add(i.key))),n.repeated?.forEach(r=>r.itemTemplate.forEach(i=>t.add(i.key))),n.computed?.forEach(r=>t.add(r.key));return t}s(Xo,"allFieldKeys");function xQ(e){let t=st(e.label,e.labelEn,"offer form add"),n={id:$a("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Yi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(xQ,"buildSkeletonSmartForm");function Vm(e,t){let{key:n,label:r}=t;if(Pd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=xQ({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(Vm,"addForm");function vM(e,t){if(!Pd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(zv(e).includes(t))throw new Error(`offer form rm: smartform "${t}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[t],e.index.smartforms&&delete e.index.smartforms[t],t}s(vM,"removeForm");function xM(e,t){let n=jm(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new Error("offer form set: --label cannot be empty");wt(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(xM,"setForm");function SM(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new Error(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(SM,"nodesOf");function AM(e,t,n){let r=SM(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new Error(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(AM,"nodeOf");function EM(e){return e.flatMap(t=>{if(t.type!=="form"||kn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(EM,"creatingFormNodes");function TM(e){return qm(Mm(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(TM,"formErrors");function Bm(e){let t="offer workflow restamp-exports",n=SM(e,t),r=[];for(let{node:i,slug:o}of EM(n)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=TM(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
|
|
11291
|
+
`)}return this.print(r,i=>i.slots.map(o=>{let a=i.override?.[o.key];return{block:o.key,label:o.label,deviates:a===void 0?"":"yes",text:(a??o.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"]),0}},Bb=class extends D{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=f.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let t=j6(this.slot,this.slotFile);if(Object.keys(t).length===0)throw new Error("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let n=await this.caller(),r=await n.mutation(x.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Wb(this.locale,"letters set"),slots:t});return this.print({templateId:this.templateId,submitted:Object.keys(t),...r},i=>[{key:"letter",value:i.templateId},{key:"submitted",value:i.submitted.join(", ")},{key:"deviating blocks",value:i.overriddenSlotKeys.join(", ")||"\u2014 (back to the platform text)"}]),0}},Ub=class extends D{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=f.String({required:!0});locale=f.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=f.Array("--slot",{description:"Block key to reset (repeatable)"});all=f.Boolean("--all",!1,{description:"Reset every block of this letter"});async execute(){let t=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&t.length>0)throw new Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&t.length===0)throw new Error("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let n=await this.caller(),r=await n.mutation(x.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Wb(this.locale,"letters reset"),...this.all?{}:{slotKeys:t}});return this.print({templateId:this.templateId,reset:this.all?"all":t.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Rd=s((e,t)=>e==null?t:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function am(e,t,n){return["de","en"].map(r=>({field:`${e} (${r})`,school:t===null?"\u2014 (platform)":t[r]===""?"\u2014 (untranslated)":Rd(t[r],""),...n===null?{}:{platform:Rd(n[r],"")}}))}s(am,"chromeTextRows");var Gb=class extends D{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let t=await this.caller(),n=await t.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(t)});return this.print(n,r=>[...am("greeting",r.greeting,r.defaults.greeting),...am("closing",r.closing,r.defaults.closing),{field:"senderName",school:Rd(r.senderName,"\u2014 (platform)"),platform:Rd(r.defaults.senderName,"")}],["field","school","platform"]),0}},zb=class extends D{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=f.String("--greeting-de",{description:"Opening line, German"});greetingEn=f.String("--greeting-en",{description:"Opening line, English"});closingDe=f.String("--closing-de",{description:"Sign-off, German"});closingEn=f.String("--closing-en",{description:"Sign-off, English"});senderName=f.String("--sender-name",{description:"Name the school signs with (empty string clears it)"});async execute(){let t=s((l,d,c)=>{if(!(d===void 0&&c===void 0)){if(d===void 0||c===void 0)throw new Error(`notifications chrome set: --${l}-de and --${l}-en go together \u2014 the frame is worded in every language`);return{de:d,en:c}}},"pair"),n=t("greeting",this.greetingDe,this.greetingEn),r=t("closing",this.closingDe,this.closingEn);if(n===void 0&&r===void 0&&this.senderName===void 0)throw new Error("notifications chrome set: nothing to change \u2014 pass --greeting-de/--greeting-en, --closing-de/--closing-en or --sender-name");let i=await this.caller(),o=this.requireTenant(i);await i.mutation(x.notifications.saveTenantChrome,{tenantSlug:o,...n!==void 0?{greeting:n}:{},...r!==void 0?{closing:r}:{},...this.senderName!==void 0?{senderName:this.senderName}:{}});let a=await i.query(x.notifications.getTenantChrome,{tenantSlug:o});return this.print(a,l=>[...am("greeting",l.greeting,null),...am("closing",l.closing,null),{field:"senderName",school:Rd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},OF=[Fb,Lb,Mb,qb,Kb,jb,Vb,Bb,Ub,Gb,zb];var B6="-stufe-",U6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Yb(e){return`${e}${B6}`}s(Yb,"stageKeyPrefix");function Hb(e,t){return`${Yb(e)}${t}`}s(Hb,"stageStorageKey");function NF(e,t){let n=Yb(e);return t.startsWith(n)&&t.length>n.length}s(NF,"isUnderProgram");function Kr(e,t){let n=Yb(e);return NF(e,t)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${t}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C). F\xFChren Sie die Stufe in bundle.yaml unter einem neuen Schl\xFCssel auf; der n\xE4chste Apply archiviert diese Zeile (hinter der Archivsperre) und legt die Stufe mit dem neuen Schl\xFCssel an.`,en:`[stage/foreignKey] The level key "${t}" is not under the program "${e}" (expected: "${n}<key>"). List the level in bundle.yaml under a new key; the next apply archives this row (behind the archive lock) and creates the level with the new key.`}),t.slice(n.length)}s(Kr,"bareStageKey");function lm(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=$t(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.stages[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"stage/nameMissing",index:i,message:{de:`[stage/nameMissing] ${l}: jede Klassenstufe braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[stage/nameMissing] ${l}: every stage needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"stage/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"stage/keyMissing",index:i,message:{de:`[stage/keyMissing] ${l}: jede Klassenstufe braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[stage/keyMissing] ${l}: every stage needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!U6.test(d)){t.push({code:"stage/keyInvalid",index:i,message:{de:`[stage/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[stage/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"stage/duplicateKey",index:i,message:{de:`[stage/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.stages[${c}] verwendet`,en:`[stage/duplicateKey] ${l}: key "${d}" is already used by program.stages[${c}]`}});return}n.set(d,i)}),t}s(lm,"stageSpecIssues");function _F(e){return{de:e.de.trim(),en:e.en.trim()}}s(_F,"trimmedText");function G6(e,t){let n=[];return e.de!==t.de&&n.push(`"${e.de}" \u2192 "${t.de}"`),e.en!==t.en&&n.push(`en "${e.en}" \u2192 "${t.en}"`),n.join(", ")}s(G6,"describeNameChange");function dm(e,t,n){if(e===null)return t.length>0&&F("planStageReconcile: stages exist but the offer has no program key"),n.map((a,l)=>({op:"insert",key:a.key,name:_F(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(t.map(a=>[a.key,a])),i=new Set,o=[];n.forEach(({name:a,...l},d)=>{let c={...l,name:_F(a)},u=Hb(e,c.key);i.add(u);let p=d+1,h=r.get(u);if(h===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:p});return}let w={};xs(h.name,c.name)||(w.name=[h.name,c.name]);let k=h.gradeLevel??null,y=c.gradeLevel??null;k!==y&&(w.gradeLevel=[k,y]),h.sequence!==p&&(w.sequence=[h.sequence,p]),(Object.keys(w).length>0||h.archived)&&o.push({op:"update",key:c.key,stageId:h.stageId,name:c.name,changes:w,unarchive:h.archived})});for(let a of[...t].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:NF(e,a.key)?Kr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(dm,"planStageReconcile");function cm(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let t=e.occupancy,n=[...t&&t.activeApplications>0?[`REFUSED: ${t.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...t&&t.openLeads>0?[`${t.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${n.length>0?` \u2014 ${n.join("; ")}`:""}`}case"update":{let t=[];if(e.unarchive&&t.push("restored"),e.changes.name&&t.push(G6(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[n,r]=e.changes.gradeLevel;t.push(`grade ${n??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&t.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${t.join(", ")})`}}}s(cm,"describeStageStep");var z6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function fi(e,t){return`${e}-${t}`}s(fi,"runStorageKey");function CF(e,t){typeof t!="string"&&ae("CONFLICT",{de:`[run/keyNotServed] Das Deployment liefert f\xFCr ein Schuljahr von \u201E${e}\u201C keinen Schl\xFCssel \u2014 es l\xE4uft ein \xE4lteres Release als die CLI. Nach dem n\xE4chsten Release erneut versuchen.`,en:`[run/keyNotServed] The deployment provides no key for a school year of "${e}" \u2014 it runs an older release than the CLI. Try again after the next release.`});let n=`${e}-`;return(!t.startsWith(n)||t.length===n.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${t}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${n}<key>\u201C).`,en:`[run/foreignKey] The key "${t}" of the school year is not under the program "${e}" (expected: "${n}<key>").`}),t.slice(n.length)}s(CF,"bareRunKey");function um(e){let t=[],n=new Map;return e.forEach((r,i)=>{let o=$t(r.name),a=o!=="not-localized"&&!o.includes("de")?r.name.de:void 0,l=`program.runs[${i}]${a!==void 0?` ("${a}")`:""}`;o==="not-localized"||o.length===2?t.push({code:"run/nameMissing",index:i,message:{de:`[run/nameMissing] ${l}: jedes Schuljahr braucht einen \`name\` auf Deutsch und Englisch (\`{ de, en }\`)`,en:`[run/nameMissing] ${l}: every run needs a \`name\` in German and English (\`{ de, en }\`)`}}):o.length>0&&t.push({code:"run/nameUntranslated",index:i,message:{de:`[i18n/missingTranslation] ${l}.name fehlt in: ${o.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`,en:`[i18n/missingTranslation] ${l}.name is missing in: ${o.join(", ")} \u2014 every displayed text needs German and English.`}});let d=r.key;if(d==null||d===""){t.push({code:"run/keyMissing",index:i,message:{de:`[run/keyMissing] ${l}: jedes Schuljahr braucht einen stabilen \`key\` \u2014 der Name dient nur der Anzeige`,en:`[run/keyMissing] ${l}: every run needs a stable \`key\` \u2014 the name is display only`}});return}if(typeof d!="string"||!z6.test(d)){t.push({code:"run/keyInvalid",index:i,message:{de:`[run/keyInvalid] ${l}: der Schl\xFCssel ${JSON.stringify(d)} muss ein kleingeschriebener Slug sein (a-z, 0-9, einzelnes \u201E-\u201C)`,en:`[run/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`}});return}let c=n.get(d);if(c!==void 0){t.push({code:"run/duplicateKey",index:i,message:{de:`[run/duplicateKey] ${l}: der Schl\xFCssel \u201E${d}\u201C wird bereits von program.runs[${c}] verwendet`,en:`[run/duplicateKey] ${l}: key "${d}" is already used by program.runs[${c}]`}});return}n.set(d,i)}),t}s(um,"runSpecIssues");var W6={capacity:null,isOpen:!1},Y6={capacity:null,isOpen:!0};function H6(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(H6,"isCapacity");function fm(e,t){let n=[],r=t===void 0?void 0:new Set(t);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&n.push(`[capacity/runIsOpenWithCells] ${a}: \`isOpen\` on the run AND \`capacities\` \u2014 the open state lives on each cell; drop the run-level \`isOpen\``),i.capacities===null||typeof i.capacities!="object"||Array.isArray(i.capacities)){n.push(`[capacity/shape] ${a}: \`capacities\` must map stage keys to { isOpen, capacity }`);return}for(let[l,d]of Object.entries(i.capacities)){let c=`${a}.capacities.${l}`;r!==void 0&&!r.has(l)&&n.push(`[capacity/unknownStage] ${c}: no stage with key "${l}" in program.stages (have: ${[...r].join(", ")||"none"})`);let u=d;if(u===null||typeof u!="object"){n.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&n.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!H6(u.capacity))&&n.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),n}s(fm,"capacitySpecIssues");function DF(e,t,n={stageKeys:[],runKeys:[]}){let r=e.programKey,i=new Map;if(r!==null)for(let c of e.stages)c.archived||i.set(Kr(r,c.key),c.stageId);let o=new Set(n.stageKeys),a=new Set(n.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of t){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===fi(r,c.key));if(u===void 0&&!a.has(c.key))throw new Error(`offer[admission]: run "${c.key}" does not exist and is not created by this apply`);for(let[p,h]of Object.entries(c.capacities)){let w=i.get(p);if(w===void 0&&!o.has(p))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${p}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:h.capacity,isOpen:h.isOpen},y=u!==void 0&&w!==void 0?l.get(`${u.runId}|${w}`):void 0,v=y!==void 0?{capacity:y.capacity,isOpen:y.isOpen}:u===void 0?W6:Y6;v.capacity===k.capacity&&v.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:v,to:k})}}return d}s(DF,"planRunCapacities");function PF(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(PF,"describeCell");function pm(e){return`~cap ${e.run}\xD7${e.stageKey} ${PF(e.from)} \u2192 ${PF(e.to)}`}s(pm,"describeCapacityStep");function FF(e){if(e.programKey===void 0)throw new Error("offer[admission]: the target backend predates stage keys \u2014 deploy it before running offer plan / apply / export with this CLI")}s(FF,"assertBackendHasStageKeys");async function Jb(e,t,n,r){let i=await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),o=i.stages.map(u=>({stageId:u.stageId,key:u.key,name:u.name,...u.gradeLevel!==void 0?{gradeLevel:u.gradeLevel}:{},sequence:u.sequence,archived:u.archived}));FF(i);let a=dm(i.programKey,o,r),l=a.flatMap(u=>u.op==="archive"?[u.stageId]:[]);if(l.length===0)return a;let d=await e.query(x.programAdmin.getStageOccupancy,{client:t,offerKey:n,stageIds:l}),c=new Map(d.map(u=>[u.stageId,u]));return a.map(u=>{if(u.op!=="archive")return u;let p=c.get(u.stageId);if(p===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:p.activeApplications,openLeads:p.openLeads}}})}s(Jb,"planStages");async function mm(e,t,n,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=n===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n});FF(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Kr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return DF(o,i,{stageKeys:l.filter(c=>!a.has(c)),runKeys:i.map(c=>c.key).filter(c=>d===null||!o.runs.some(u=>u.key===fi(d,c)))})}s(mm,"planCapacities");async function J6(e,t,n,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===fi(a,d)&&c.status==="archived"));if(l.length>0)throw new Error(`offer[admission]: run(s) ${l.map(d=>`"${d}"`).join(", ")} exist only ARCHIVED \u2014 restore with \`offer run restore --run <key>\` or drop the bundle entry`)}s(J6,"assertNoArchivedRunKey");var Qb={name:"admission",async scaffold(e,t,n,r){let i=n.tenant,o=n.program?.stages,a=[...lm(o??[]),...um(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(y=>y.message.de).join("; ")}`);let l=fm(n.program?.runs??[],o?.map(y=>y.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await J6(e,i,t,n);let d=await mm(e,i,t,n),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t}),u=Q6(n);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let p=c.units.find(y=>y.key===u);if(!p)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(y=>y.key===null?[]:[y.key]).join(", ")||"(none)"}`);let h=[];if(r.dryRun||(await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:i,unitId:p.unitId}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:i,offerKey:t,unitId:p.unitId,...n.program?.key!==void 0?{programKey:n.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let y=await Jb(e,i,t,o);h.push(...y.map(cm))}else{let y=await e.mutation(x.programAdmin.reconcileProgramStages,{client:i,offerKey:t,stages:o.map(v=>({key:v.key,name:v.name,...v.gradeLevel!==void 0?{gradeLevel:v.gradeLevel}:{}}))});h.push(...y.steps,...y.warnings.map(v=>`warning ${v}`))}let w=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t});for(let y of n.program?.runs??[]){let v=w.programKey===null?void 0:w.runs.find(A=>A.key===fi(w.programKey,y.key));if(v!==void 0){xs(v.name,y.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:t,runId:v.runId,name:y.name}),h.push(`~run ${y.key} ("${Pe(v.name)}" \u2192 "${Pe(y.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:t,key:y.key,name:y.name,isOpen:y.capacities!==void 0?!1:y.isOpen??!0,...y.startDate?{startDate:y.startDate}:{},...y.endDate?{endDate:y.endDate}:{}}),h.push(`+run ${y.key} (${Pe(y.name)})`)}let k=r.dryRun?d:await mm(e,i,t,n);if(!r.dryRun&&k.length>0){let y=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:t}),v=y.programKey;if(v===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of k){let E=y.runs.find(C=>C.key===fi(v,A.run))?.runId,I=y.stages.find(C=>Kr(v,C.key)===A.stageKey)?.stageId;if(E===void 0||I===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:t,runId:E,stageId:I,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return h.push(...k.map(pm)),h.join(", ")}};function Q6(e){let t=e.program?.unitKey,n=e.links?.unitKey;if(t!==void 0&&n!==void 0&&t!==n)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${t}" and links.unitKey "${n}"; keep one`);return t??n}s(Q6,"bundleUnitKey");var LF={role:"control",effect:"pure",cardinality:"N-to-1"};var hm=["add","remove","replace"];function MF(e,t){let n=e.inputs?.[t];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}s(MF,"roleAssignLiteral");var qF={role:"method",effect:"context-mutation",inputs:s(()=>[{id:"person",label:{de:"Person",en:"Person"},type:"personRef",required:!0},{id:"roleKey",label:{de:"Rolle",en:"Role"},type:"roleKey",required:!0,optionSource:"tenantRoles"},{id:"mode",label:{de:"Modus",en:"Mode"},type:"enum",defaultValue:"add",optionSource:"declared",enumOptions:[{value:"add",label:{de:"Rolle hinzuf\xFCgen",en:"Add role"}},{value:"remove",label:{de:"Rolle entziehen",en:"Remove role"}},{value:"replace",label:{de:"Alle Rollen ersetzen",en:"Replace all roles"}}]}],"inputs"),validate:s((e,t,n)=>{let r=[],i=MF(e,"roleKey")?.trim()??"",o=MF(e,"mode")??"add";return i===""?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/missingRoleKey] roleAssign-Knoten "${e.id}" nennt keine Rolle \u2014 welche Rolle vergeben wird, muss der Autor aus dem Rollenkatalog des Mandanten w\xE4hlen.`,en:`[roleAssign/missingRoleKey] roleAssign node "${e.id}" names no role \u2014 the author must choose which role is assigned from the school's role catalog.`},severity:"error"}):n?.roleKeys!==void 0&&!n.roleKeys.has(i)?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/unknownRoleKey] Rolle "${i}" existiert nicht im Rollenkatalog des Mandanten \u2014 der Knoten w\xFCrde bei jeder Ausf\xFChrung abbrechen. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[roleAssign/unknownRoleKey] Role "${i}" does not exist in the school's role catalog \u2014 the node would abort on every run. Known roles: ${[...n.roleKeys].sort().join(", ")}.`},severity:"error"}):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(i)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.roleKey`,reason:{de:`[roleAssign/nonLeafRoleKey] Rolle "${i}" hat untergeordnete Rollen und ist deshalb nicht vergebbar \u2014 eine Partei bekommt ein Blatt, keine Oberkategorie. Vergebbare Rollen: ${[...n.assignableRoleKeys].sort().join(", ")}.`,en:`[roleAssign/nonLeafRoleKey] Role "${i}" has sub-roles and therefore cannot be assigned \u2014 a party gets a leaf role, not a parent category. Assignable roles: ${[...n.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),hm.includes(o)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.mode`,reason:{de:`[roleAssign/unknownMode] roleAssign-Knoten "${e.id}" deklariert Modus "${o}" \u2014 erlaubt sind ${hm.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${hm.join(" | ")}.`},severity:"error"}),r},"validate")};var Z6=["event","effect","outcomes"],Zb=s((e,t,n)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:t,en:n},severity:"error"}),"issue"),KF={outcomes:[{id:gr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,t)=>{let n=[],r=e;for(let i of Z6)i in r&&n.push(Zb(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${gr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${gr}" itself.`));return Zn(t.nodes).some(i=>i.target===e.id)&&n.push(Zb(`nodes.${e.id}`,`[eventTrigger/notStart] Knoten "${e.id}" ist ein Start-Knoten, hat aber eine eingehende Kante \u2014 nur der Start l\xF6st ihn aus, jeder Vorgang bliebe hier stehen.`,`[eventTrigger/notStart] Node "${e.id}" is a start node but has an incoming edge \u2014 only the start triggers it, every process would stop here.`)),e.next?.[gr]===void 0&&n.push(Zb(`nodes.${e.id}.next.${gr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${gr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${gr}" nowhere.`)),n},"validate")};var X6="submit",jF=[{id:X6,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function VF(e){return e==="draft"}s(VF,"isWritableSmartFormState");var Xb=["draft","committed"],ARe=Xb.filter(e=>VF(e));async function BF(e,t,n){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",t).eq("formNodeId",n)).take(2);return r.length>1&&F(`application ${t}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(BF,"getSmartFormInstance");var UF="form:fill",ev="request:collectPayment",GF="request:collectPaymentSeparate",tv="confirmPayment";var e3={key:UF,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},zF={key:"bearbeitung",label:ne("In Bearbeitung","In progress"),scope:"node"},WF={[qR]:{label:ne("In Bearbeitung","In progress"),tone:"neutral",phase:zF,external:Ze(ne("Entwurf","Draft"),"neutral",ne("Bewerbung fortsetzen","Continue application"),ne("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),ne("Bewerbung fortsetzen","Continue application"),"continue-form")},[ef]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:zF,external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung ist eingereicht","Your application has been submitted"),ne("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},YF={role:"user-action",effect:"side-effect",progressDefaults:WF,progressEvents:Ft(WF),actions:s(()=>jF,"actions"),workItemTemplates:s(()=>[e3],"workItemTemplates"),states:Xb,currentState:s(async(e,t)=>{let n=await BF(e,t.applicationId,t.node.id);return n===null?"draft":n.state},"currentState"),inputs:s(e=>[{id:"smartForm",label:{de:"Formular",en:"Form"},type:"smartForm",optionSource:"offerSmartForms",required:e.adoptForm===void 0,inspector:"literal-only"}],"inputs"),outputs:s(e=>[{name:"admission",type:"admission",label:{de:"Anmeldung",en:"Application"},schema:[{key:"beneficiary",type:"personRef",label:{de:"Beschulte Person",en:"Student"}},{key:"signers",type:"personList",label:{de:"Unterzeichner",en:"Signers"}},...e.formExports??[]]}],"outputs"),notificationEvents:s(e=>kn(e)?[]:[{id:tf,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[],n=e.inputs?.smartForm,r=n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0,i=e.adoptForm!==void 0;return r&&i?t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.adoptForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" hat sowohl ein smartForm als auch adoptForm \u2014 genau eines ist erlaubt.`,en:`[form.adopt-xor-create] Form node "${e.id}" has both a smartForm and adoptForm \u2014 exactly one is allowed.`},severity:"error"}):!r&&!i&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.smartForm`,reason:{de:`[form.adopt-xor-create] Form-Knoten "${e.id}" braucht entweder ein smartForm (neu erzeugen) oder adoptForm (bestehende Instanz \xFCbernehmen).`,en:`[form.adopt-xor-create] Form node "${e.id}" needs either a smartForm (create new) or adoptForm (adopt an existing instance).`},severity:"error"}),t},"validate")};var HF={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Ot.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Ot.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Ot.value,label:{de:"Setzen oder zur\xFCcknehmen",en:"Raise or lower"},type:"boolean",defaultValue:!0,inspector:"literal-only",enumOptions:[{value:"true",label:{de:"Setzen",en:"Raise"}},{value:"false",label:{de:"Zur\xFCcknehmen",en:"Lower"}}]}],"inputs"),notificationEvents:s(e=>[{id:"unlocked",label:{de:"Abschnitt freigeschaltet",en:"Section unlocked"},audience:"external",required:sO(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let t=[];e.inputs?.[Ot.flagKey]?.kind==="literal"&&bf(e)===null&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ot.flagKey}`,reason:{de:`[setFlag/missingFlagKey] setFlag-Knoten "${e.id}" nennt kein Merkmal (Parameter \u201EMerkmal im Formular\u201C).`,en:`[setFlag/missingFlagKey] setFlag node "${e.id}" names no flag (parameter "Flag in the form").`},severity:"error"});let r=e.inputs?.[Ot.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ot.value}`,reason:{de:`[setFlag/valueType] setFlag-Knoten "${e.id}": \u201ESetzen oder zur\xFCcknehmen\u201C ist ein Ja/Nein-Wert (true/false), kein Text.`,en:`[setFlag/valueType] setFlag node "${e.id}": "Raise or lower" is a yes/no value (true/false), not text.`},severity:"error"}),t},"validate")};var t3="true",n3="false",nv=[{id:t3,label:{de:"Ja",en:"Yes"}},{id:n3,label:{de:"Nein",en:"No"}}];var JF={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:nv,validate:s((e,t,n)=>r3(e,t,n),"validate")};function r3(e,t,n){let r=s(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${o.de}`,en:`[if/condition] Node "${e.id}": ${o.en}`},severity:"error"}),"issue"),i=nv.filter(o=>e.next?.[o.id]===void 0).map(o=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${o.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${o.label.de}\u201C (${o.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${o.label.en}" (${o.id}) leads nowhere.`},severity:"error"}));return typeof e.condition!="string"||e.condition.trim()===""?[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})]:[...i,...Xf(e.condition,eI(t),n).map(r)]}s(r3,"ifNodeIssues");var Sa="decision",i3=new Set(["decision","review"]),YRe=new Set([...i3,"governedDocument"]);var ZF=[{id:"approved",label:{de:"Freigeben",en:"Approve"},semantic:"granted"},{id:"rejected",label:{de:"Ablehnen",en:"Reject"},semantic:"rejected"},{id:"waitlisted",label:{de:"Auf Warteliste",en:"Waitlist"},semantic:"waitlisted"}],QF={released:{label:ne("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:ne("Freigabe","Release"),scope:"node"},external:Ze(ne("Freigegeben","Released"),"green",ne("Ihre Bewerbung wurde freigegeben","Your application has been released"),ne("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Yo={role:"user-action",effect:"side-effect",outcomes:ZF,progressDefaults:QF,progressEvents:Ft(QF),notificationEvents:s(e=>(e.outcomes??[]).map(t=>({id:t.id,label:t.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(t=>({id:t.id,kind:"advance",outcome:t.id,label:t.label,...Ii(t.semantic)?{semantic:t.semantic}:{}})),...NN(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:Sa,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(t=>t.id).filter(t=>typeof t=="string"&&t.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,t)=>t===Sa&&Array.isArray(e.reads)?e.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),taskFormView:s((e,t)=>t===Sa?e.formView:void 0,"taskFormView"),validate:rv};function rv(e,t,n){let r=[],i=e.outcomes??[];i.length===0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[decision/missingOutcomes] Entscheidungs-Knoten "${e.id}" hat keine Outcomes \u2014 die Entscheidung w\xE4re niemals aufl\xF6sbar.`,en:`[decision/missingOutcomes] Decision node "${e.id}" has no outcomes \u2014 the decision could never be resolved.`},severity:"error"});let o=new Set(i.map(l=>l.id));for(let l of i){let d=l.label;(typeof d=="string"?d.trim().length>0:d!=null&&typeof d=="object"&&Object.values(d).some(p=>typeof p=="string"&&p.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}`,reason:{de:`[decision/outcomeMissingLabel] Outcome "${l.id}" von "${e.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,en:`[decision/outcomeMissingLabel] Outcome "${l.id}" of "${e.id}" has no label \u2014 it is the text of the button in the cockpit.`},severity:"error"});let u=l.semantic;u===void 0?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticMissing] Outcome "${l.id}" von "${e.id}" sagt nicht, was es bedeutet \u2014 eines von ${wn.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${wn.join(", ")}.`},severity:"error"}):Ii(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes.${l.id}.semantic`,reason:{de:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" von "${e.id}" hat die Bedeutung "${String(u)}" \u2014 erlaubt: ${wn.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${wn.join(", ")}.`},severity:"error"})}for(let l of Object.keys(e.commentRequired??{}))o.has(l)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.commentRequired.${l}`,reason:{de:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${l}" in commentRequired; erlaubt: ${[...o].join(", ")}`,en:`[decision/commentRequiredUnknownOutcome] Unknown outcome "${l}" in commentRequired; allowed: ${[...o].join(", ")}`},severity:"error"});let a=e.decisionAsTask?.title;return a!==void 0&&(a!==null&&typeof a=="object"&&Object.values(a).some(d=>typeof d=="string"&&d.length>0)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.decisionAsTask.title`,reason:{de:"[decision/decisionTaskMissingTitle] decisionAsTask.title ist gesetzt, aber leer \u2014 entweder einen nicht-leeren lokalisierten Text angeben oder das Feld weglassen (dann greift der Standardtitel).",en:"[decision/decisionTaskMissingTitle] decisionAsTask.title is set but empty \u2014 either give a non-empty localized text or omit the field (the default title then applies)."},severity:"error"})),r}s(rv,"validateDecisionNode");var iv=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],XF=[{id:"complete",label:{de:"Vollst\xE4ndig",en:"Complete"}},{id:"acceptedIncomplete",label:{de:"Ohne Nachreichung abgeschlossen",en:"Closed without the missing documents"}},{id:"rejected",label:{de:"Abgelehnt",en:"Rejected"}},{id:"absage",label:{de:"Zur\xFCckgezogen",en:"Withdrawn"}}];var ov="promoted";var eL="promote",tL="Nachr\xFCcken";var sv={key:"warteliste",label:ne("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},nL={waitlisted:{label:ne("Warteliste","Waitlisted"),tone:"amber",phase:sv,external:Ze(ne("Warteliste","Waiting list"),"amber",ne("Sie stehen auf der Warteliste","You are on the waiting list"),ne("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:ne("Nachger\xFCckt","Promoted"),tone:"green",phase:sv,external:Ze(ne("Nachger\xFCckt","Moved up"),"green",ne("Sie sind nachger\xFCckt","You have moved up"),ne("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:ne("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:sv,external:Ze(ne("Warteliste geschlossen","Waiting list closed"),"red",ne("Die Warteliste wurde geschlossen","The waiting list has been closed"),ne("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},rL={outcomes:iv,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Hn.map(e=>({value:e,label:fI[e]}))}],"inputs"),validate:s((e,t)=>{let n=ly(e);if(n===null)return[];let r=t.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=t.nodes.indexOf(e);for(let o of r){if(t.nodes.indexOf(o)>i)continue;let a=ly(o);if(a!==null&&a.waitlistOrder!==n.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different orders \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:nL,progressEvents:Ft(nL),notificationEvents:s(()=>[{id:"placed",label:{de:"Auf die Warteliste gesetzt",en:"Placed on the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]},{id:"promoted",label:{de:"Nachger\xFCckt",en:"Promoted from the waiting list"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"rank",type:"number"}]}],"notificationEvents"),actions:s(e=>(e.outcomes!==void 0&&e.outcomes.length>0?e.outcomes:iv).some(n=>n.id===ov)?[{id:eL,kind:"advance",outcome:ov,semantic:"other",label:{de:tL,en:"Promote from waitlist"},surface:Xn,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var av="complete",Id="acceptedIncomplete",gm="rejected",o3="absage",iL="closeWithoutDocuments",oL="rejectAtCompleteness",sL="Ohne Nachreichung abschlie\xDFen",aL="Ablehnen",lL="awaitingDocuments",lv="documentsComplete",dv="closedWithoutDocuments",cv="rejected",uv="withdrawn",dL="requested",hIe={[av]:{event:lv,status:"complete",endsRole:!0},[Id]:{event:dv,status:"acceptedIncomplete",endsRole:!1},[gm]:{event:cv,status:"rejected",endsRole:!0},[o3]:{event:uv,status:"withdrawn",endsRole:!0}};var Od=s(()=>xl[0],"beneficiary"),fv=366;function s3(e){let t=e.reads,n=Sl(e).flatMap(({address:r})=>ct(r)&&!xl.includes(r.path)?[r]:[]);return[...Array.isArray(t)?t.filter(ct):[],...n]}s(s3,"printedFields");function a3(e,t){let n=pe(t);return e.nodes.filter(r=>r.type==="governedDocument"&&s3(r).some(i=>pe(i)===n))}s(a3,"documentsPrinting");function l3(e,t){if(!ct(t)||t.path!==Od())return!1;let n=e.nodes.find(r=>r.id===t.owner);return n!==void 0&&n.type==="form"&&!kn(n)}s(l3,"isCreatedFormBeneficiary");function Lt(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Lt,"issue");function d3(e,t,n){let r=new Map(e.nodes.map(l=>[l.id,l])),i=t.next??{},o=new Set,a=[av,Id].flatMap(l=>{let d=i[l]?.to;return d===void 0?[]:[d]});for(;a.length>0;){let l=a.pop();if(o.has(l))continue;o.add(l);let d=r.get(l);if(d!==void 0&&!(d.type==="review"&&xe(d.form)&&wr(d.form)&&d.form.owner===n)){if(d.type==="end"){if(To(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(d3,"reachesApprovedEndUnreviewed");var pv={key:"unterlagen",label:ne("Unterlagen nachreichen","Outstanding documents"),scope:"node"},cL={[lL]:{label:ne("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:pv,external:Ze(ne("Unterlagen fehlen","Documents missing"),"amber",ne("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),ne("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[lv]:{label:ne("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:pv,external:Ze(ne("Unterlagen vollst\xE4ndig","Documents complete"),"green",ne("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),ne("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[dv]:{label:ne("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:pv,external:Ze(ne("Abgeschlossen","Closed"),"neutral",ne("Die Nachreichung ist abgeschlossen","The document request is closed"),ne("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[cv]:{label:ne("Abgelehnt","Rejected"),tone:"red",phase:UO,external:Ze(ne("Abgelehnt","Rejected"),"red",ne("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),ne("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[uv]:{label:ne("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:Pf,external:Ze(ne("Zur\xFCckgezogen","Withdrawn"),"red",ne("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),ne("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},uL={outcomes:XF,progressDefaults:cL,progressEvents:Ft(cL),notificationEvents:s(()=>[{id:dL,label:{de:"Unterlagen angefordert",en:"Documents requested"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"fieldLabels",type:"localizedText",required:!0},{key:"dueAt",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=s(r=>e.next?.[r]!==void 0,"wired"),n=[];return t(Id)&&n.push({id:iL,kind:"advance",outcome:Id,semantic:"other",label:{de:sL,en:"Close without documents"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Es geht ohne die fehlenden Unterlagen weiter. Die Anfrage an die Familie wird geschlossen.",en:"The application continues without the missing documents. The request to the family is closed."},confirmLabel:{de:"Abschlie\xDFen",en:"Close"}}}),t(gm)&&n.push({id:oL,kind:"advance",outcome:gm,semantic:"rejected",label:{de:aL,en:"Reject application"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Der Platz wird abgesagt und die Anfrage an die Familie geschlossen. Das l\xE4sst sich nicht r\xFCckg\xE4ngig machen.",en:"The application is rejected and the request to the family is closed. This cannot be undone."},confirmLabel:{de:"Ablehnen",en:"Reject"}}}),n},"actions"),inputs:s(()=>[{id:"person",label:{de:"Person (Gasth\xF6rer-Rolle)",en:"Person (guest role)"},type:"personRef",required:!1},{id:"guestRole",label:{de:"Gastrolle bis zur Nachreichung",en:"Guest role until submitted"},type:"roleKey",required:!1,inspector:"literal-only",optionSource:"tenantRoles"}],"inputs"),validate:s((e,t,n)=>{let r=[],i=`Vollst\xE4ndigkeitspr\xFCfung \u201E${e.label?.de??e.id}\u201C (${e.id})`,o=`Completeness check "${e.label?.en||e.id}" (${e.id})`,a=s(A=>je(t,A,"de"),"shown"),l=s(A=>je(t,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Lt(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let E of d){if(!xe(E))continue;let I=pe(E);if(A.has(I)){r.push(Lt(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(E)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(E)} appears twice in \`requires\`.`}));continue}if(A.add(I),!ct(E)){r.push(Lt(e,"requires",{de:`[completenessCheck/unknownField] ${a(E)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(E)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let C=ni(n,E);if(C==null)continue;let $=Vs("requires",js(C));$==="computed"||$==="repeated"?r.push(Lt(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(E)} ist ${C.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(E)} is ${C.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):$==="untranslated"&&r.push(Lt(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(E)} (\u201E${Fi(C,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(E)} ("${Fi(C,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},p="inDays"in u,h="until"in u;if(p===h)r.push(Lt(e,"deadline",{de:`[completenessCheck/deadlineShape] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" braucht genau eine Frist: \`{ inDays: n }\` (Tage ab Eintritt) oder \`{ until: "JJJJ-MM-TT" }\`.`,en:`[completenessCheck/deadlineShape] Completeness check "${e.id}" needs exactly one deadline: \`{ inDays: n }\` (days after entry) or \`{ until: "YYYY-MM-DD" }\`.`}));else if(p){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>fv)&&r.push(Lt(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${fv} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${fv} days.`}))}else typeof u.until!="string"||Yy(u.until)===null?r.push(Lt(e,"deadline.until",{de:`[completenessCheck/deadlineDate] Frist "${String(u.until)}" ist kein g\xFCltiges Datum (JJJJ-MM-TT).`,en:`[completenessCheck/deadlineDate] Deadline "${String(u.until)}" is not a valid date (YYYY-MM-DD).`})):u.until<l_(Date.now())&&r.push({...Lt(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(ct).map(E=>[pe(E),E]));for(let E of A.values())for(let I of a3(t,E))r.push(Lt(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(E)} flie\xDFt in das Dokument \u201E${I.label?.de??I.id}" (${I.id}) ein \u2014 nach dessen Ausstellung kann die Familie es nicht mehr nachreichen. Feld aus \`requires\` oder aus dem Dokument nehmen.`,en:`[completenessCheck/requiresConsumedUpstream] Field ${l(E)} flows into the document "${I.label?.en||I.id}" (${I.id}) \u2014 once it is issued, the family can no longer submit it later. Remove the field from \`requires\` or from the document.`}))}if(Array.isArray(d)&&n!==void 0){let A=d.filter(ct).filter(C=>{let $=ni(n,C);return $!=null&&ep($)}),I=[...new Set(A.map(C=>C.owner))].filter(C=>d3(t,e,C));if(I.length>0){let C=A.filter($=>I.includes($.owner));r.push({...Lt(e,"next",{de:`[review/unreviewedAfterSupply] ${C.map(a).join(", ")} ist pr\xFCfpflichtig und wird hier nachgereicht, aber nach \u201Evollst\xE4ndig\u201C oder \u201Eohne Nachreichung\u201C f\xFChrt ein Weg ohne Pr\xFCfknoten dieses Formulars zur Aufnahme \u2014 niemand pr\xFCft das Nachgereichte. Dort einen Pr\xFCfknoten einf\xFCgen (z. B. \u201EWenn nichts zu pr\xFCfen ist: Durchreichen\u201C).`,en:`[review/unreviewedAfterSupply] ${C.map(l).join(", ")} requires review and is supplied here, but after "complete" or "accepted incomplete" a path without a review node of this form leads to admission \u2014 nobody reviews what was supplied. Insert a review node there (e.g. "When nothing is owed: pass through").`}),severity:"warning"})}}let w=e.inputs?.guestRole,k=w?.kind==="literal"?w.value:void 0,y=e.inputs?.person,v=y?.kind==="binding"?y.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Lt(e,"inputs.guestRole",{de:"[completenessCheck/guestRoleEmpty] `guestRole` ist leer \u2014 Rollenschl\xFCssel angeben oder das Feld weglassen.",en:"[completenessCheck/guestRoleEmpty] `guestRole` is empty \u2014 give a role key or omit the field."})):n?.roleKeys!==void 0&&!n.roleKeys.has(k)?r.push(Lt(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...n.roleKeys].sort().join(", ")}.`})):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(k)&&r.push(Lt(e,"inputs.guestRole",{de:`[completenessCheck/nonLeafRole] Rolle "${k}" hat untergeordnete Rollen und ist nicht vergebbar.`,en:`[completenessCheck/nonLeafRole] Role "${k}" has sub-roles and cannot be assigned.`})),v===null&&r.push(Lt(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${en}.${Od()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${en}.${Od()}).`}))),xe(v)&&!l3(t,v)&&r.push(Lt(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(v)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${en}.${Od()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(v)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${en}.${Od()}).`})),v!==null&&k===void 0&&r.push(Lt(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Lt(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var c3=[{id:mI,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],ym=s(e=>e,"asDecision"),fL={[hI]:{label:ne("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:ne("In Pr\xFCfung","In review"),scope:"node"},external:Ze(ne("Eingereicht","Submitted"),"blue",ne("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),ne("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},pL={role:"user-action",effect:"side-effect",outcomes:c3,progressDefaults:fL,progressEvents:Ft(fL),notificationEvents:s(e=>Yo.notificationEvents(ym(e)),"notificationEvents"),inputs:s(()=>[{id:tr,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Mo.map(e=>({value:e,label:IC[e]}))}],"inputs"),actions:s(e=>[...Yo.actions(ym(e)).map(t=>t.kind==="advance"&&(e.outcomes??[]).length===1?{...t,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:t),{id:uy,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Yo.optionalActionKinds,workItemTemplates:s(e=>Yo.workItemTemplates(ym(e)).map(t=>t.key===Sa?{...t,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...t.unlocks,uy]}:t),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,t,n)=>{let r=rv(ym(e),t,n);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!hf.includes(u)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/rejectingOutcome] Pr\xFCf-Knoten "${e.id}" deklariert das Outcome "${c.id}" mit der Bedeutung "${String(u)}" \u2014 eine Pr\xFCfung lehnt nicht ab und setzt nicht auf die Warteliste; das ist die Entscheidung der Freigabe bzw. \u201EBewerbung ablehnen".`,en:`[review/rejectingOutcome] Review node "${e.id}" declares the outcome "${c.id}" meaning "${String(u)}" \u2014 a review neither rejects nor waitlists; that is the decision of the approval or "Reject application".`},severity:"error"})}let i={de:`\u201E${e.label?.de??e.id}\u201C (${e.id})`,en:`"${e.label?.en||e.id}" (${e.id})`},o=e.inputs?.[tr],a=OC(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${tr}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Mo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Mo.join(" or ")}.`},severity:"error"});let l=a==="advance",d=e.form;if(l&&d===void 0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:{de:`[review/advanceNeedsForm] Pr\xFCf-Knoten ${i.de} reicht durch, wenn nichts zu pr\xFCfen ist, nennt aber kein Formular \u2014 er w\xFCrde immer durchreichen. Nenne das Formular, dessen pr\xFCfpflichtige Felder er pr\xFCft.`,en:`[review/advanceNeedsForm] Review node ${i.en} passes through when nothing is owed but names no form \u2014 it would always pass through. Name the form whose review-required fields it checks.`},severity:"error"}),l&&(e.outcomes??[]).length!==1&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.outcomes`,reason:{de:`[review/advanceOneOutcome] Pr\xFCf-Knoten ${i.de} reicht durch, hat aber ${(e.outcomes??[]).length} Outcomes \u2014 durchgereicht wird \xFCber genau eines.`,en:`[review/advanceOneOutcome] Review node ${i.en} passes through but has ${(e.outcomes??[]).length} outcomes \u2014 it passes through over exactly one.`},severity:"error"}),xe(d)&&wr(d)){let c=n?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(ep)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${pe(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt w\xFCrde jedes Mal durchreichen. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${pe(d)}, but that form declares no field review-required \u2014 the step would pass through every time. Mark the fields "Review required" in the form.`}:{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${pe(d)}, aber dieses Formular erkl\xE4rt kein Feld als pr\xFCfpflichtig \u2014 der Schritt wartet, ohne dass etwas abzuhaken ist. Markiere die Felder im Formular als \u201EPr\xFCfpflichtig\u201C.`,en:`[review/nothingDeclared] Review node ${i.en} reviews ${pe(d)}, but that form declares no field review-required \u2014 the step waits with nothing to tick. Mark the fields "Review required" in the form.`},severity:l?"error":"warning"})}return r},"validate")};var mL=["awaitingAnswer","answered"];async function hL(e,t){return(await Nl(e,{applicationId:t.applicationId,nodeId:t.nodeId})).filter(r=>r.templateKey===t.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(hL,"externalRequestState");var wL=[{id:Ao,label:{de:"Bezahlt",en:"Paid"}}],XIe=new Set(wL.map(e=>e.id));var u3=Ao,gL=[{id:u3,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],f3={id:My,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:Xn,confirm:{title:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},body:{de:"Die Geb\xFChr ist au\xDFerhalb von Plexus eingegangen. Der Schritt wird als separat bezahlt abgeschlossen, die Aufgabe der Familie schlie\xDFt mit.",en:"The fee was received outside Plexus. The step is completed as paid separately; the family's task closes with it."},confirmLabel:{de:"Best\xE4tigen",en:"Confirm"}}},p3={id:Ly,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:Xn,superUserOnly:!0,confirm:{title:{de:"Zahlung \xFCberspringen",en:"Skip payment"},body:{de:"Die Geb\xFChr wird au\xDFerhalb von Plexus abgerechnet. Der Schritt wird ohne Zahlung abgeschlossen; es wird kein Betrag als bezahlt verbucht.",en:"The fee is billed outside Plexus. The step is completed without a payment; no amount is recorded as paid."},confirmLabel:{de:"\xDCberspringen",en:"Skip"}}},m3={id:Ly,kind:"advance",outcome:Ao,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:Xn,superUserOnly:!0,availableIn:["awaitingAnswer"],confirm:{title:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},body:{de:"Die Familie hat nicht online \xFCber Plexus bezahlt. Der Schritt wird ohne Online-Zahlung abgeschlossen; eine offene Zahlungsseite wird geschlossen. Bitte den Grund angeben (z. B. bar bezahlt).",en:"The family did not pay online through Plexus. The step is completed without an online payment; an open payment page is closed. Please give the reason (e.g. paid in cash)."},confirmLabel:{de:"Abschlie\xDFen",en:"Complete"}},commentRequired:!0};function mv(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(mv,"literalOf");function Ho(e){let t=mv(e,Jn);return Af(t)?t:null}s(Ho,"settlementOrNull");function h3(e){let t=mv(e,Pi);return typeof t=="string"&&t.length>0?t:null}s(h3,"articleKeyOrNull");function g3(e){let t=mv(e,Qn);return typeof t=="string"&&t.length>0&&t===t.trim()?t:null}s(g3,"payeeKeyOrNull");var y3={id:Pi,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},w3={id:Jn,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},k3={id:Di,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},b3={id:Qn,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function v3(e){return[y3,w3,...Ho(e)==="online"?[b3]:[],k3]}s(v3,"collectPaymentInputs");var x3=["amount","currency","settlement"],S3={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},A3={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function E3(e,t){if(Ho(e)!=="online")return[];let n=g3(e);if(n===null)return[];let r=`nodes.${e.id}.inputs.${Qn}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return t?.traeger!==void 0&&!t.traeger.has(n)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${n}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${n}" is not a legal entity of this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})]:t?.stripeReadyTraegerKeys!==void 0&&!t.stripeReadyTraegerKeys.has(n)?[i({de:`[collectPayment/onlineWithoutStripe] Abrechnung \u201Eonline" an \u201E${n}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${n}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "online" to "${n}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${n}") \u2014 otherwise no family can pay. Until then, choose "separate".`})]:[]}s(E3,"payeeIssues");var yL={awaitingPayment:{label:ne("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:ne("Zahlung","Payment"),scope:"node"},external:Ze(ne("Zahlung offen","Payment due"),"amber",ne("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),ne("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},kL={outputs:s(()=>[{name:HI,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>v3(e),"inputs"),outcomes:wL,progressDefaults:yL,progressEvents:Ft(yL),notificationEvents:s(e=>Ho(e)!=="online"?[]:[{id:"requested",label:{de:"Zahlung angefordert",en:"Payment requested"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"amount",type:"number",required:!0}]}],"notificationEvents"),actions:s(e=>{let t=Ho(e);return t==="online"?[...gL,m3]:t==="separate"?[f3,p3]:[]},"actions"),states:mL,currentState:s((e,t)=>hL(e,{applicationId:t.applicationId,nodeId:t.node.id,templateKey:ev}),"currentState"),workItemTemplates:s(e=>{let t=e,n=Ho(t);return n==="separate"?[{key:tv,recipient:"internal",title:S3,unlocks:[My],advancesNode:!0},{key:GF,recipient:"external",title:A3,unlocks:[],informational:!0,advancesNode:!1}]:n!=="online"?[]:[{key:ev,recipient:"external",title:t.label,unlocks:gL.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,t,n)=>{let r=[],i=s((d,c)=>r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${d}`,reason:c,severity:"error"}),"push");for(let d of x3)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});if(r.push(...E3(e,n)),Ho(e)==="separate"){let d=e.assign?.[tv];(typeof d!="string"||d.length===0)&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird separat abgerechnet, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is billed separately, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."})}Ho(e)===null&&i(`inputs.${Jn}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Ms.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Jn])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Ms.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Jn])}.`});let o=e.inputs?.[Di];if(o?.kind==="literal"){let d=Sf(o.value);d!==null&&i(`inputs.${Di}`,{de:`[collectPayment/reasonText] Der Hinweis f\xFCr die Familie braucht einen Text auf Deutsch und auf Englisch (${d}).`,en:`[collectPayment/reasonText] The note for the family needs a text in German and in English (${d}).`})}let a=h3(e);if(a===null)return i(`inputs.${Pi}`,{de:'[collectPayment/missingArticle] Der Zahlungsknoten nennt keinen Artikel \u2014 unter \u201EParameter" einen einmaligen Artikel des Programms w\xE4hlen (Finanzen \u2192 Artikel).',en:'[collectPayment/missingArticle] The payment node names no article \u2014 under "Parameters" choose a one-time article of the program (Finance \u2192 Articles).'}),r;let l=`inputs.${Pi}`;return n?.billingItemKeys!==void 0&&!n.billingItemKeys.has(a)?(i(l,{de:`[collectPayment/unknownArticle] Artikel \u201E${a}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel.`,en:`[collectPayment/unknownArticle] Article "${a}" \u2014 no article of this school has this key.`}),r):(n?.oneTimeBillingItemKeys!==void 0&&!n.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${qy.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${qy.join(", ")}.`}),n?.offerProgram===null?i(l,{de:"[collectPayment/articleOfferWithoutProgram] Das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.",en:"[collectPayment/articleOfferWithoutProgram] The offer is not assigned to a program, so no article belongs to it; give the offer a program."}):n?.offerProgram?.directBillingItemKeys!==void 0&&!n.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${n.offerProgram.nameDe}" des Angebots nicht direkt zugeordnet \u2014 unter Finanzen \u2192 Artikel zuordnen (ein Paket z\xE4hlt nicht: es kann den Artikel anders bepreisen).`,en:`[collectPayment/articleNotInProgram] Article "${a}" is not directly assigned to the offer's program "${n.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function bL(e){return{de:`[governedDocument/localeFieldMissing] Die Vorlage "${e}" nennt kein Sprachfeld \u2014 ein Schreiben entsteht in genau einer Sprache. Ein Pflicht-Auswahlfeld mit den Optionen de/en unter den Parametern der Vorlage anlegen, es als localeField der Vorlage nennen und im Knoten an die Sprache des Benutzerkontos binden ($env.applicant.language); die Word-Datei h\xE4lt je Sprache einen Abschnitt <<#input.<feld>.de>> \u2026 <</input.<feld>.de>>.`,en:`[governedDocument/localeFieldMissing] The template "${e}" names no language field \u2014 a letter is written in exactly one language. Create a required choice field with the options de/en among the template's parameters, name it as the template's localeField and bind it in the node to the language of the user account ($env.applicant.language); the Word file holds one section per language <<#input.<field>.de>> \u2026 <</input.<field>.de>>.`}}s(bL,"localeFieldMissingText");var hv=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),vL=/^[a-z][a-z0-9_]*$/;function xL(e,t){let n=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${t}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${t}" declares no parameters \u2014 expected { fields } (the placeholders input.<key> a node fills).`}}];let i=r,o=new Set;for(let a of i){if(typeof a?.key!="string"||!vL.test(a.key)||o.has(a.key)){n.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${t}" ist ${o.has(a?.key)?"doppelt":"kein g\xFCltiger Schl\xFCssel"} \u2014 erlaubt sind eindeutige Kleinbuchstaben, Ziffern und _ (gedruckt als input.<schl\xFCssel>).`,en:`[governedDocument/templateFieldKey] Field "${String(a?.key)}" of the template "${t}" is ${o.has(a?.key)?"duplicated":"not a valid key"} \u2014 allowed are unique lower-case letters, digits and _ (printed as input.<key>).`}});continue}o.add(a.key);let l=`fields.${a.key}`;if(!Ci(a.type)){n.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${t}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Ls.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${t}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${Ls.join(", ")}).`}});continue}if(hv.has(a.type)||n.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${t}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...hv].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${t}" has the type "${a.type}" \u2014 a letter only prints ${[...hv].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!vL.test(String(d.value)))&&n.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${t}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${t}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&n.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${t}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${t}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${t}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${t}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&n.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?n.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Brief aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a letter from a template is not countersigned.`}}):a.processSource!==void 0&&!up.includes(a.processSource)&&n.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${up.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${up.join(", ")}.`}})}return n.push(...T3(e,t)),n}s(xL,"templateParameterIssues");function T3(e,t){if(e.localeField===void 0)return[{path:"localeField",reason:bL(t)}];let n=e.fields.find(i=>i.key===e.localeField),r=n===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:n.type!=="enum"?{de:`ist ${n.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${n.type}, a select field (enum) is expected`}:n.required!==!0?{de:"ist kein Pflichtfeld \u2014 ohne Sprache gibt es keine Variante",en:"is not a required field \u2014 without a language there is no variant"}:(n.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(n.options??[]).some(i=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${t}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${t}" ${r.en}.`}}]}s(T3,"localeFieldIssues");function SL(e,t){if(t===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(t.fields),...t.localeField===void 0?{}:{localeField:t.localeField}}}s(SL,"applyTemplateStamp");var gv=50;async function wm(e,t){let n=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",t)).take(gv+1);return n.length>gv&&F(`signing_returns: Vorgang ${t} has more than ${gv} returns`),n}s(wm,"returnsOf");var yv=50;async function wv(e,t){let n=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",t)).take(yv+1);return n.length>yv&&F(`signing_returns: return ${t} has more than ${yv} files`),n.length===0&&F(`[signing/noDocument] return ${t} carries no file`),n}s(wv,"returnDocumentsOf");async function AL(e,t){let n=await wv(e,t);return n.length!==1&&F(`[signing/severalDocuments] return ${t} carries ${n.length} files; this reader handles one`),n[0]}s(AL,"soleReturnDocumentOf");var km=200,yOe=km*20;async function $3(e,t){let n=await e.db.get(t);return n===null&&F(`[process] application ${t} not found`),n.redactedAt!==void 0}s($3,"processRedacted");async function kv(e,t){await $3(e,t)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(kv,"assertProcessReadable");function R3(e){let t={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...t,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...t,scope:"node",result:e.result}}s(R3,"rowOf");async function EL(e,t,n){await kv(e,t);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",t).eq("scope",n.scope).eq("owner",n.owner).eq("key",n.key)).order("desc").take(km+1);return r.length>km&&F(`[process] application ${t} has more than ${km} results of ${n.scope}.${n.owner}.${n.key}`),r.map(R3)}s(EL,"storeHistory");async function I3(e,t,n){if(n.key===en){await kv(e,t);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",t).eq("formNodeId",n.owner)).unique();return i===null||i.state!=="committed"?{state:"pending",reason:null}:{state:"present",result:{kind:"ref",ref:{kind:"form",formInstanceId:i._id}},row:null}}let[r]=await EL(e,t,{scope:"node",owner:n.owner,key:n.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(I3,"nodeResultAt");async function bm(e,t){let n={scope:"node",owner:t.nodeId,key:t.key};return O3(await I3(e,t.applicationId,n),n,t.applicationId)}s(bm,"readOwnResult");function O3(e,t,n){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${pe(t)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(O3,"refOf");var bv={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},_3=Object.keys(bv),N3=_3.filter(e=>bv[e]==="open"),TOe=N3.filter(e=>e!=="pending");function TL(e){return bv[e]==="terminal"}s(TL,"isTerminalSigningStatus");var Ui=["docusign","insign"];var _d={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var P3=TL;function RL(e){return!P3(e.status)&&e.voidRequestedAt===void 0}s(RL,"holdsContract");async function IL(e,t){return await e.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",t)).unique()}s(IL,"traegerLegalEntityOfParty");async function D3(e,t){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",t)).first()!==null}s(D3,"isOrganizationParty");async function OL(e,t){return await IL(e,t)!==null?"traeger":await D3(e,t)?"organization":"person"}s(OL,"signerKindOf");async function _L(e,t){t.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let n of t)if(await F3(e,n.partyId)==="family")return"family";return"traeger"}s(_L,"signingSideOf");async function F3(e,t){return await OL(e,t)==="traeger"?"traeger":"family"}s(F3,"sideOfParty");var c_e=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),CL=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var vv=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),vm=m.object({period:vv,anchorDate:m.string()});var h_e=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),g_e=m.union(m.literal("line"),m.literal("aggregate")),xm=m.record(m.string(),m.string());var L3=m.union(m.literal("active"),m.literal("ended")),xv=m.union(m.object({mode:m.literal("track")}),m.object({mode:m.literal("pin"),billingItemVersionId:Ve.restrict(m.id("billing_item_versions"),{unindexed:"pinned price version inside the pricing union"})}),m.object({mode:m.literal("override"),amount:m.number()})),M3=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),q3={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:xv,pricingSelections:m.optional(xm),paymentSchedule:m.optional(vm),resolvedSnapshot:m.any(),feeGroup:m.optional(CL),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},K3={...q3,period:M3,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:L3,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},A_e=_n(K3).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var br=m.union(m.string(),m.null()),PL=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),j3=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string(),representative:m.optional(m.object({userId:m.id("users"),nameAtSigning:m.string(),email:m.string()}))}),DL=m.object({sourceAllocationId:m.id("payer_allocations"),scope:m.union(m.object({kind:m.literal("contract")}),m.object({kind:m.literal("contract_line"),contractLineId:m.id("contract_lines")})),payer:m.union(m.object({kind:m.literal("party"),partyId:m.id("parties"),nameAtSigning:m.string()}),m.object({kind:m.literal("payment_method"),paymentMethodId:m.id("payment_methods"),label:m.string(),ownersAtSigning:m.array(PL)})),sharePct:m.union(m.number(),m.null()),flatAmount:m.union(m.number(),m.null()),cap:m.union(m.number(),m.null()),activeFrom:m.string(),activeTo:br}),FL=m.object({sourceAppliedGrantId:m.string(),sourceGrantTemplateId:m.union(m.string(),m.null()),name:m.string(),reason:m.string(),kind:m.string(),value:m.number(),rule:m.optional(m.any()),scope:m.optional(m.union(m.literal("line"),m.literal("aggregate"))),floorTotal:m.optional(m.number()),pricePeriod:m.optional(vv),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:br,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),V3={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:br,pricing:xv,paymentSchedule:m.optional(vm),pricingSelections:m.optional(xm),billingItemDefinition:m.object({sourceBillingItemDefinitionId:m.id("billing_item_definitions"),name:m.string(),itemType:m.string(),configOpaque:m.any()}),resolvedSnapshotOpaque:m.any(),enrolment:m.union(m.object({sourceEnrolmentId:m.id("enrollments"),status:m.string(),startDate:br,endDate:br,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:br,programName:br,runName:br,groupName:br}),m.null()),grants:m.array(FL),payerAllocations:m.array(DL)},B3=m.object({...V3,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:br,sourceValidTo:br})}),U3=m.object({formatVersion:m.literal(2),contract:m.object({scope:m.string(),generator:m.object({sourceGeneratorDefinitionId:m.id("contract_generator_definitions"),sourceCreationTime:m.number(),name:m.string(),bodyOpaque:m.any()})}),parties:m.array(PL),declaredSigners:m.array(j3),payerAllocations:m.array(DL),aggregateGrants:m.optional(m.array(FL)),lines:m.array(B3)}),G3=U3;var z3=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),W3=m.object({pageCount:m.number(),spots:m.array(m.object({signer:m.union(m.object({kind:m.literal("party"),role:m.string(),ordinal:m.union(m.number(),m.null())}),m.object({kind:m.literal("named"),label:Bi})),caption:m.string(),page:m.number(),box:z3}))});var Y3=m.object({storageId:Ve.holds(m.id("_storage")),sourceArtifactId:m.optional(Ve.history(m.id("admission_documents"))),sha256:m.string(),mimeType:m.optional(m.string()),sizeBytes:m.optional(m.number()),filename:m.string(),source:m.union(m.object({kind:m.literal("uploaded")}),m.object({kind:m.literal("machine_rendered"),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),signaturePlacement:m.optional(W3)}))}),H3=m.object({storageId:Ve.holds(m.id("_storage")),sha256:m.string(),filename:m.string(),rendererVersion:m.string(),renderInput:m.record(m.string(),m.any()),confirmationRequired:m.boolean()}),J3={importedTemplateSource:m.optional(m.object({id:m.string(),creationTime:m.number()})),tenantId:Ve.tenant(m.id("tenants")),contractId:Ve.restrict(m.id("contracts")),snapshotNumber:m.optional(m.number()),revisionNumber:m.optional(m.number()),supersedesSnapshotId:m.optional(Ve.history(m.id("contract_snapshots"))),frozenAt:m.number(),frozenByUserId:m.optional(Ve.history(m.id("users"))),document:Y3,coverLetter:m.optional(H3),snapshot:Ve.historyOf(G3),generation:m.optional(m.object({generatorVersionId:m.optional(Ve.history(m.id("contract_generator_versions"))),generatorRevisionId:m.optional(m.string()),implementationKey:m.string(),implementationChecksum:m.string(),input:m.any(),output:m.any()}))},C_e=_n(J3).index("by_tenantId",["tenantId"]).index("by_document_storageId",["document.storageId"]).index("by_coverLetter_storageId",["coverLetter.storageId"]).index("by_contractId_and_snapshotNumber",["contractId","snapshotNumber"]).index("by_supersedesSnapshotId",["supersedesSnapshotId"]).index("by_generation_generatorVersionId",["generation.generatorVersionId"]);var W_e=16*1024;var Y_e=15*6e4;var H_e=10*6e4;var Sv={contractSnapshotId:Ve.restrict(m.id("contract_snapshots")),storageId:Ve.restrict(m.id("_storage")),sha256:m.string(),filename:m.string(),uploadedAt:m.number(),signers:m.array(m.object({partyId:Ve.history(m.id("parties")),role:m.string()}))},fNe=_n({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...Sv}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var yNe=m.object(Sv);var Av=200;async function Q3(e,t,n,r){t.length>Av&&F(`${r} is carried by more than ${Av} signing requests`);let i=[],o=new Set;for(let l of t){if(o.has(l.signingRequestId))continue;o.add(l.signingRequestId);let d=await e.db.get(l.signingRequestId);d===null&&F(`signing_request_documents ${l._id} names a missing signing request ${l.signingRequestId}`),i.push(d)}let a=n==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(Q3,"requestsOfMembers");async function LL(e,t,n="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",t)).take(Av+1);return await Q3(e,r,n,`revision ${t}`)}s(LL,"requestsOfSnapshot");var ML=100;async function Z3(e,t){let n=await LL(e,t);n.length>ML&&F(`requestsBySideOf: revision ${t} has more than ${ML} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((o,a)=>o._creationTime-a._creationTime))r[await _L(e,i.signers)].push(i);return r}s(Z3,"requestsBySideOf");async function Ev(e,t){return(await Z3(e,t)).family}s(Ev,"familyRequestsOf");var Tv=100;async function X3(e,t){let n=await e;return n.length>Tv&&F(`contractChain: more than ${Tv} ${t}`),n}s(X3,"bounded");async function e5(e,t,n){let r=await bm(e,{applicationId:t,nodeId:n,key:Cs});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${n}.${Cs} of application ${t} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(e5,"nodeContractRef");async function qL(e,t){return await X3(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",n=>n.eq("contractId",t)).take(Tv+1),`revisions on contract ${t}`)}s(qL,"snapshotsAsc");async function $v(e,t){let n=(await Ev(e,t)).filter(RL);return n.length>1&&F(`contractChain: revision ${t} has ${n.length} open family Vorg\xE4nge`),n[0]??null}s($v,"openFamilyRequest");async function t5(e,t){for(let n of await qL(e,t))if((await Ev(e,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(t5,"familyRoute");async function KL(e,t){for(let n of t)if(await t5(e,n)==="paper")return"paper";return"provider"}s(KL,"familyRouteOf");async function n5(e,t){let n=await AL(e,t._id),r=await e.db.system.get("_storage",n.storageId);return r===null&&F(`contractChain: return ${t._id} holds missing file ${n.storageId}`),{_id:t._id,_creationTime:t._creationTime,storageId:n.storageId,filename:n.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:t._id}}s(n5,"toReturn");function Sm(e){async function t(a,l){return await e5(a,l,e.id)}s(t,"contractOrNull");async function n(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await t(a,l);return(p===null||h===null||p.contractId!==h)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${h??"(none yet)"} \u2014 corrupt arc`),p}s(n,"snapshotOf");async function r(a,l){let d=await t(a,l);return d===null?null:(await qL(a,d)).at(-1)??null}return s(r,"newestSnapshot"),{reads:{kind:"contract",async returned(a,l,d){if(d.askedAbout===void 0){if(d.onUnpinned==="notReturned")return null;F(`returned(${d.where}): an ask of the contract chain is always pinned to its revision`)}let c=await n(a,l,d.askedAbout,`returned(${d.where})`),u=await $v(a,c._id);if(u===null)return null;let p=(await wm(a,u._id)).filter(h=>h.review.status==="pending"&&h._id!==d.rejected);return p.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${p.length} returns pending \u2014 one is checked at a time`),p[0]===void 0?null:await n5(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:t,snapshotOf:n,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await t(a,l);return d===null?[]:[d]}}.contractsOf}}s(Sm,"contractNodeReads");function Am(e){return e.addedParts??[]}s(Am,"addedPartsOf");var Rv=50;async function r5(e,t){let n=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",t)).take(Rv+1);return n.length>Rv&&F(`groupRunsOf: generation group ${t} has more than ${Rv} runs`),n.length===0&&F(`groupRunsOf: generation group ${t} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}s(r5,"groupRunsOf");async function jL(e,t){let n=await r5(e,t),r=n[0].packageRunId;if(r!==void 0){(n.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(n.map(l=>l.partKey)).size!==n.length)&&F(`groupRunsInOrder: package group ${t} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${t} is missing`);let o=await e.db.query("contract_package_parts").withIndex("by_packageVersionId_and_position",l=>l.eq("packageVersionId",i.packageVersionId)).take(51),a=[...o.map(l=>l.partKey),...Am(i).map(l=>l.partKey)];return(o.length>50||n.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${t} names an unknown part`),n.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${t} has no package reference.`)}s(jL,"groupRunsInOrder");function VL(e){return e.every(t=>t.status==="succeeded"&&t.contractId!==void 0&&t.contractSnapshotId!==void 0)}s(VL,"isCompleteGroup");var Iv=200;function i5(e){let t=e.generatorStamp?.parts;return t===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),t.map(n=>n.partKey)}s(i5,"groupPartKeys");async function o5(e,t,n){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",t).eq("workflowNodeId",n)).take(Iv+1);return r.length>Iv&&F(`groupChain: more than ${Iv} generation runs on node ${n}`),r}s(o5,"nodeRuns");async function s5(e,t,n){let r=i5(n),i=new Set;for(let a of await o5(e,t,n.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${n.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await jL(e,a);if(!VL(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(Am(d).map(p=>p.partKey)),u=[];for(let p of l){!r.includes(p.partKey)&&!c.has(p.partKey)&&F(`groupChain: run ${p._id} renders part "${p.partKey}", which node "${n.id}"'s pin does not declare and nobody added`);let h=await e.db.get(p.contractSnapshotId);h===null&&F(`groupChain: run ${p._id} names revision ${p.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:p,snapshot:h})}o.push({packageRunId:a,startedAt:Math.min(...l.map(p=>p._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(s5,"groupRevisionRows");async function Ov(e,t,n){let r=await bm(e,{applicationId:t,nodeId:n,key:Ps});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${n}.${Ps} of application ${t} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Ov,"nodeGroupContracts");async function a5(e,t){let n=new Map;for(let{snapshot:r}of t.members){let i=await $v(e,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&F(`groupChain: generation group ${t.packageRunId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}s(a5,"openGroupRequest");async function l5(e,t){let n=[];for(let i of await wv(e,t._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${t._id} holds missing file ${i.storageId}`),n.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=n[0];return{_id:t._id,_creationTime:t._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:t._id,documents:n}}s(l5,"toGroupReturn");function BL(e){async function t(i,o,a,l){let d=(await s5(i,o,e)).find(c=>c.members[0]?.snapshot._id===a);return d===void 0&&F(`${l}: ${a} is no revision of node "${e.id}"'s generation groups \u2014 corrupt arc`),d}return s(t,"revisionRowOf"),{reads:{kind:"group",async returned(i,o,a){if(a.askedAbout===void 0){if(a.onUnpinned==="notReturned")return null;F(`returned(${a.where}): an ask of the group chain is always pinned to its lead revision`)}let l=await t(i,o,a.askedAbout,`returned(${a.where})`),d=await a5(i,l);if(d===null)return null;let c=(await wm(i,d._id)).filter(u=>u.review.status==="pending"&&u._id!==a.rejected);return c.length>1&&F(`returned(${a.where}): Vorgang ${d._id} has ${c.length} returns pending \u2014 one is checked at a time`),c[0]===void 0?null:await l5(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:t,contractsOf:{async contractsOf(i,o){return(await Ov(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(BL,"groupNodeReads");async function d5(e,t){let n=t.lifecycle.kind==="draft"?void 0:t.lifecycle.kind;return{_id:t._id,_creationTime:t._creationTime,versionNumber:t.versionNumber,...n!==void 0?{status:n}:{},origin:t.origin.kind,storageId:t.storageId,...await yk(e,t.storageId),...t.filename!==void 0?{filename:t.filename}:{}}}s(d5,"toRevision");async function c5(e,t){let n=await d5(e,t);return{_id:n._id,_creationTime:n._creationTime,storageId:n.storageId,...n.filename!==void 0?{filename:n.filename}:{},...n.mimeType!==void 0?{mimeType:n.mimeType}:{},round:n.versionNumber}}s(c5,"toReturn");function UL(e){let t=mp(e);async function n(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",t)).collect()}return s(n,"contentRowsAsc"),{reads:{kind:"artifact",async returned(o,a,l){if(l.askedAbout===void 0){if(l.onUnpinned==="notReturned")return null;ae("CONFLICT",{de:"Die offene Antwort-Aufgabe ist an keine Dokumentversion gebunden, daher l\xE4sst sich die unterschriebene Fassung nicht vom versandten Dokument unterscheiden. Stellen Sie das Dokument neu aus (Zur\xFCckziehen & neu ausstellen).",en:"The open response task is not bound to a document version, so the signed copy cannot be told apart from the document that was sent. Issue the document again (withdraw and reissue)."})}let d=await n(o,a),c=d[d.length-1];if(c===void 0||c._id===l.askedAbout||c.origin.kind!=="uploaded")return null;if(l.rejected!==void 0){let u=d.find(p=>p._id===l.rejected);if(u===void 0&&F(`returned(${l.where}): the handed-back scan ${l.rejected} is no version of slot "${t}"`),c.versionNumber<=u.versionNumber)return null}return await c5(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:n,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(UL,"artifactNodeReads");function Em(e){return e.production==="none"&&F(`documentChainKind: node "${e.id}" has production 'none' \u2014 it keeps no document`),e.production!=="resolver"?"artifact":e.generatorStamp?.parts!==void 0?"group":"contract"}s(Em,"documentChainKind");function GL(e){switch(Em(e)){case"contract":return Sm(e).reads;case"group":return BL(e).reads;case"artifact":return UL(e).reads}}s(GL,"documentReadsFor");var u5={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Nd(e){let t=e.responseStrategy;return typeof t=="string"&&t in li?li[t].producesResponseArtifact:!1}s(Nd,"returnsSignedCopy");function f5(e){return Nd(e)&&e.confirmContractTerms!==!1}s(f5,"asksContractTerms");function zL(e){return f5(e)?{title:e.contractTermsQuestionText??u5,body:{de:"Die unterschriebene Fassung wird erst nach Ihrer Best\xE4tigung hochgeladen. Die Best\xE4tigung wird mit Zeitpunkt und Person festgehalten.",en:"The signed copy is uploaded only after you confirm. The confirmation is recorded with time and person."},confirmLabel:{de:"OK",en:"OK"}}:null}s(zL,"contractTermsConfirm");async function p5(e,t,n){if(n.revisesWorkItemId===void 0)return;let r=await e.db.get(n.revisesWorkItemId),i=r===null?null:lw(r),o=i?.context,a=o?.kind==="admission"?t.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Lr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${Lr} row`),a}s(p5,"rejectedReturnOfAsk");async function WL(e,t){return await t.chain.returned(e,t.applicationId,{askedAbout:t.chain.pinOf(t.ask),rejected:await p5(e,t.chain,t.ask),onUnpinned:t.onUnpinned,where:t.where})}s(WL,"returnedCopyOfAsk");var _v=new Set([...$w,Fr,No,oa,Lr,cn]),QL={id:jt,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},ZL={id:go,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function m5(e){let t=[],n=[{slot:QL,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:ZL,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of n){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){t.push(Se(e,l,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber ${o.a} ${r.label.de} \u2014 nur production '${i}' verwendet sie.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a ${r.label.en.toLowerCase()} \u2014 only production '${i}' uses it.`}));continue}if(a.kind==="binding"){t.push(Se(e,l,{de:`[governedDocument/referenceNotLiteral] Knoten "${e.id}": ${o.the} ${r.label.de} ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ${o.it} aus.`,en:`[governedDocument/referenceNotLiteral] Node "${e.id}": the ${r.label.en.toLowerCase()} is a fixed value of the node, not a binding \u2014 choose it from the list.`}));continue}if(a.kind!=="literal")continue;let d=Al(a.value,{type:r.type});d!==null&&t.push(Se(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return t}s(m5,"referenceInputIssues");var h5={id:ai,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},g5={id:sa,type:"boolean",label:{de:"Coverletter best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},y5={id:Pn,type:"legalEntity",label:QN,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function w5(e,t){let n=`inputs.${Pn}`,r=e.inputs?.[Pn];if(r!==void 0&&r.kind==="binding")return[Se(e,n,{de:`[governedDocument/traegerNotLiteral] Knoten "${e.id}": der Tr\xE4ger ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ihn aus.`,en:`[governedDocument/traegerNotLiteral] Node "${e.id}": the legal entity is a fixed value of the node, not a binding \u2014 choose it from the list.`})];let i=ia(e),o=t?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=t?.traeger?.get(l);t?.traeger!==void 0&&d===void 0?a.push(Se(e,n,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...t.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...t.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Se(e,n,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${ip.address}), aber "${l}" hat keine \u2014 in der Konfiguration des Mandanten nachtragen (foundation.legalEntities[].address).`,en:`[governedDocument/traegerAddressMissing] The generator template on node "${e.id}" prints the legal entity's address (${ip.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(w5,"traegerIssues");function $m(e){if(e.production==="template"){let n=e.templateStamp?.fields;return Array.isArray(n)?n:[]}if(e.production!=="resolver")return[];let t=e.generatorStamp?.inputSchema?.fields;return Array.isArray(t)?t.map(n=>{let{label:r}=n;return r===void 0?{...n,label:{de:n.key,en:n.key}}:(Ti(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${n.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...n,label:r})}):[]}s($m,"generatorFields");function k5(e,t){return e.inputs?.[t]?.kind==="cockpit"}s(k5,"deferredToCockpit");function b5(e){return Ci(e.type)?e.type:void 0}s(b5,"resolverSlotType");function v5(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let t=da(e);return{confirm:{title:{de:`\u201E${t.de}\u201C jetzt senden?`,en:`Send "${t.en}" now?`},body:{de:"Das Dokument wird danach f\xFCr die Familie sichtbar.",en:"The family will be able to see the document afterwards."},confirmLabel:{de:"Senden",en:"Send"}}}}s(v5,"issueConfirmation");function Se(e,t,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:"error"}}s(Se,"issue");function Tm(e){return cp.includes(e.production)&&Lo.includes(e.approval)&&fp.includes(e.responseStrategy)}s(Tm,"hasValidModes");async function Nv(e,t){let n=await Nl(e,{applicationId:t.applicationId,nodeId:t.node.id});if(n.length===0)return"pending";let r=n.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&$w.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";if(r.some(l=>l.templateKey===oa))return"awaitingCoverLetter";let o=r.find(l=>l.templateKey===Fr);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===cn))return"signatureStalled";let a=r.find(l=>l.templateKey===No);if(a!==void 0){if(di(t.node).issuesBy==="provider"){let d=Em(t.node)==="group"?(await Ov(e,t.applicationId,t.node.id)).map(c=>c.contractId):[await Sm(t.node).contractOrNull(e,t.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&F(`governedDocCurrentState: eSignature node "${t.node.id}" has an open ask but no contract`),await KL(e,d)==="provider")return"awaitingSignature"}return di(t.node).producesResponseArtifact?await WL(e,{chain:GL(t.node),applicationId:t.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${t.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Lr)?"responseInCheck":"done"}s(Nv,"governedDocCurrentState");function YL(e){return e.production!=="none"&&Em(e)!=="artifact"}s(YL,"keepsDocumentInContractDomain");function x5(e,t){let n=e.inputs?.[t.key];if(n?.kind!=="binding")return[];let r=n.address;if(!xe(r)||r.scope!=="env"||!Yn(r.key))return[];let i=ho(r.key);if(t.type!==i.type)return[Se(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" ist ${t.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${pe(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${t.key}" is ${t.type}, the environment variable "${i.label.en}" (${pe(r)}) supplies ${i.type}.`})];let o=new Set((t.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Se(e,`inputs.${t.key}`,{de:`[governedDocument/envNotCovered] Feld "${t.key}" kennt ${a.map(l=>`\u201E${l.label.de}\u201C (${l.value})`).join(", ")} nicht \u2014 die Umgebungsvariable \u201E${i.label.de}\u201C kann diese Werte liefern. Jeder Wert braucht eine Option.`,en:`[governedDocument/envNotCovered] Field "${t.key}" does not know ${a.map(l=>`"${l.label.en}" (${l.value})`).join(", ")} \u2014 the environment variable "${i.label.en}" can supply these values. Every value needs an option.`})]}s(x5,"envCoverageIssues");function XL(e,t){let n=[];for(let r of $m(e)){if(r.type==="party"||r.type==="personList")continue;if(n.push(...x5(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${xe(a.address)?pe(a.address):JSON.stringify(a.address)}`,en:`a binding to ${xe(a.address)?pe(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:k5(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/processSourceConflict] "${r.label.de}" wird vom Vorgang selbst gef\xFCllt (${r.processSource}), daneben steht ${l.de}. Eine der beiden Quellen bliebe wirkungslos \u2014 entferne die Verdrahtung.`,en:`[governedDocument/processSourceConflict] "${r.label.en}" is filled by the case itself (${r.processSource}), and ${l.en} is set as well. One of the two sources would have no effect \u2014 remove the wiring.`},severity:"error"});continue}if(r.required!==!0)continue;let i=e.inputs?.[r.key];i?.kind==="binding"||i?.kind==="literal"||i?.kind==="cockpit"||r.defaultValue!==void 0||n.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${t.de} hat keine Quelle \u2014 binde es an ein Formular-Export-Feld, setze einen festen Wert oder lass es ausdr\xFCcklich im Cockpit erg\xE4nzen.`,en:`[governedDocument/unsourcedRequiredField] Required field "${r.label.en}" of the generator ${t.en} has no source \u2014 bind it to a form export field, set a fixed value or leave it explicitly to the cockpit.`},severity:"error"})}return n}s(XL,"fieldSourceIssues");function S5(e){let t=hr(e)??"\u2014";if(e.templateStamp===void 0)return[];let n=xL(e.templateStamp,t).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return n.push(...XL(e,{de:`Vorlage "${t}"`,en:`template "${t}"`})),n}s(S5,"templateIssues");function A5(e,t){return(t?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${n.pin}" wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the generator template "${n.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=n.signerAnchors.filter(i=>!n.documentAnchors.has(i));return r.length===0?[]:[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${n.pin}" tr\xE4gt keinen Anker f\xFCr ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 der Anbieter f\xE4nde f\xFCr diese Personen kein Unterschriftsfeld.`,en:`[governedDocument/eSignatureAnchorMissing] Node "${e.id}" is signed electronically, but the template of "${n.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(A5,"eSignatureAnchorIssues");function E5(e,t){return t===void 0||t.sendable?[]:di(e).issuesBy!=="provider"?[]:[Se(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${t.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${t.reason.en}`})]}s(E5,"eSignatureProviderIssues");var HL={key:"dokument",label:ne("Dokument","Document"),scope:"node"},JL={producing:{label:ne("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:HL,external:Ze(ne("In Vorbereitung","In preparation"),"blue",ne("Ihr Dokument wird vorbereitet","Your document is being prepared"),ne("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:ne("Dokument bereitgestellt","Document issued"),tone:"blue",phase:HL,external:Ze(ne("Dokument bereit","Document ready"),"amber",ne("Ihr Dokument liegt bereit","Your document is ready"),ne("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),ne("Dokument beantworten","Respond to the document"))}},e0={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>_o,"processHoldTemplate"),progressDefaults:JL,progressEvents:Ft(JL),notificationEvents:s(e=>[{id:"issued",label:{de:"Dokument bereitgestellt",en:"Document issued"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number"}]},{id:"responded",label:{de:"Antwort eingegangen",en:"Response received"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]},{id:"coverLetterAsked",label:{de:"Coverletter zur Best\xE4tigung",en:"Cover letter to confirm"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"dueInDays",type:"number",required:!1}]},{id:"responseRejected",label:{de:"R\xFCcklauf zur\xFCckgegeben",en:"Returned copy handed back"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0},{key:"reason",type:"string",required:!0}]}],"notificationEvents"),strictActionCoverage:!0,actions:s(e=>{if(!Tm(e))return[];let t=di(e),n=[],r=t.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=t.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...Fo(e)?["awaitingCoverLetter"]:[],...i,...t.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(n.push({id:Rw(e),kind:"internal",surface:aa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...v5(e)??{}}),n.push({id:tC,kind:"internal",surface:aa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:nC,kind:"internal",surface:aa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),n.push(t.checksReturn?{id:ap,kind:"internal",label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:t.acceptOutcomeId,kind:"advance",outcome:t.acceptOutcomeId,semantic:t.outcomeSemantics.accept,label:e.responseLabels?.accept??t.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:t.declineOutcomeId,kind:"advance",outcome:t.declineOutcomeId,semantic:t.outcomeSemantics.decline,label:e.responseLabels?.decline??t.defaultLabels.decline,availableIn:Fo(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),Fo(e)&&(n.push({id:op,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),n.push({id:sp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),t.producesResponseArtifact&&n.push({id:lp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),t.issuesBy==="provider"&&n.push({id:dp,kind:"internal",surface:aa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Co,kind:"internal",surface:aa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:rC,currentState:Nv,workItemTemplates:s(e=>{let t=e;return Tm(t)?Iw(t):[]},"workItemTemplates"),taskDocuments:s((e,t)=>{let n=e;if(!Tm(n)||n.production==="none")return[];let r=Iw(n).find(i=>i.key===t);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:mp(n)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[QL,y5]:[],...e.production==="template"?[ZL]:[],h5,...e.generatorStamp?.coverLetter===!0?[g5]:[],...$m(e).filter(t=>t.type!=="party"&&t.type!=="personList").flatMap(t=>{let n=b5(t);return n===void 0?[]:[{field:t,type:n}]}).map(({field:t,type:n})=>({id:t.key,type:n,label:t.label,required:t.required===!0&&t.processSource===void 0,...t.processSource===void 0?{deferrable:!0}:{},...t.defaultValue!==void 0&&(typeof t.defaultValue=="string"||typeof t.defaultValue=="number"||typeof t.defaultValue=="boolean"||t.defaultValue===null||n==="pricedItem"&&Oi(t.defaultValue))?{defaultValue:t.defaultValue}:{},...t.options!==void 0?{enumOptions:t.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:bl,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,t)=>{if(t===No||t===oa||t===ql||t===Lr||t===cn){let n=t===No?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:t===Lr?{de:"die Pr\xFCfung des R\xFCcklaufs entsteht erst mit dem R\xFCcklauf der Familie",en:"the check of the returned copy only arises once the family returns it"}:t===cn?{de:"die Kl\xE4rung der elektronischen Unterschrift entsteht erst, wenn sie nicht zustande kommt",en:"resolving the electronic signature only arises when it does not come about"}:{de:"die \xDCberarbeitungs-Aufgabe entsteht nur durch eine Ablehnung",en:"the revision task only arises from a rejection"};return{de:`[governedDocument/blocksTarget] 'blocks' auf "${t}" (Knoten "${e.id}") ist verboten \u2014 ${n.de}; zul\xE4ssige intrinsische Ziele: ${_o}${e.approval==="release"?`, ${Fr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${t}" (node "${e.id}") is not allowed \u2014 ${n.en}; allowed intrinsic targets: ${_o}${e.approval==="release"?`, ${Fr}`:""}.`}}return t===Fr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Fr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Fr}" on node "${e.id}" \u2014 with approval 'none' this template does not exist; the blocker would postpone a phantom.`}:null},"refuseBlocksTarget"),userUploadGate:s(async(e,t)=>{if(YL(t.node))return!1;let n=await Nv(e,t),r=(n==="awaitingResponse"||n==="responseReturned")&&di(t.node).producesResponseArtifact;return t.actor==="recipient"?r:n==="producing"&&t.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,t)=>{let n=zL(t.node);if(n===null||YL(t.node))return null;let r=await Nv(e,t);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:s((e,t,n)=>{let r=[];if(!Tm(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${cp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Lo.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${fp.join(", ")}} (ist: ${JSON.stringify(e.responseStrategy)}). Eine Betriebsart ist eine erkl\xE4rte Entscheidung, nie aus der Verdrahtung abgeleitet.`,en:`[governedDocument/unknownMode] Node "${e.id}" declares no valid mode \u2014 required: production \u2208 {${cp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Lo.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${fp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=li[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Se(e,"production",{de:`[governedDocument/modeContract] Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben und nichts zu unterschreiben: approval muss 'none' sein (ist: '${e.approval}') und responseStrategy 'confirm' (ist: '${e.responseStrategy}').`,en:`[governedDocument/modeContract] Node "${e.id}" has production 'none' \u2014 with no document there is nothing to release and nothing to sign: approval must be 'none' (is: '${e.approval}') and responseStrategy 'confirm' (is: '${e.responseStrategy}').`}));let o=e.artifacts??[];if(e.production==="none")o.length!==0&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" hat production 'none', deklariert aber ${o.length} Artefakt-Slot(s) \u2014 ein dokumentloser Best\xE4tigungs-Knoten verwaltet keinen Slot.`,en:`[governedDocument/slotContract] Node "${e.id}" has production 'none' but declares ${o.length} artifact slot(s) \u2014 a confirmation node without a document manages no slot.`}));else{o.length!==1&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Knoten "${e.id}" deklariert ${o.length} Artefakt-Slots \u2014 genau EINER (das verwaltete Dokument) ist erforderlich.`,en:`[governedDocument/slotContract] Node "${e.id}" declares ${o.length} artifact slots \u2014 exactly ONE (the managed document) is required.`}));for(let A of o)A.visibility!=="external"&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${A.key}" auf Knoten "${e.id}" hat visibility "${A.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${A.key}" on node "${e.id}" has visibility "${A.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(A=>A.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(A=>l.includes(A)))&&r.push(Se(e,"outcomes",{de:`[governedDocument/outcomeContract] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') muss genau ZWEI Outcomes deklarieren \u2014 das Accept-Terminal "${i.acceptOutcomeId}" und das Decline-Terminal "${i.declineOutcomeId}" (deklariert: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"keine"}). Beide sind Pflicht: der Knoten besitzt die Antwort, nicht nur die Freigabe.`,en:`[governedDocument/outcomeContract] Node "${e.id}" (responseStrategy '${e.responseStrategy}') must declare exactly TWO outcomes \u2014 the accept terminal "${i.acceptOutcomeId}" and the decline terminal "${i.declineOutcomeId}" (declared: ${l.length>0?l.map(A=>`"${A}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(A=>{let E=c?.[A];return E===null||typeof E!="object"||!Object.values(E??{}).some(I=>typeof I=="string"&&I.length>0)},"missingTitle"),p=[];e.production!=="none"&&p.push("prepare","revise"),e.approval==="release"&&p.push("approve"),i.checksReturn&&p.push("check");let h=p.filter(u);h.length>0&&r.push(Se(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${h.join(", ")} \u2014 der Knotentyp ist dokument-agnostisch, die Betitelung ist Pflicht-Konfiguration seiner Betriebsart.`,en:`[governedDocument/missingTitles] Node "${e.id}" is missing the task titles ${h.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let w=e.assign??{};if(e.production!=="none"){let A=w.prepareDocument;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`}))}if(e.approval==="none"&&(w.releaseApproval!==void 0&&r.push(Se(e,"assign.releaseApproval",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', verdrahtet aber assign.releaseApproval \u2014 tote Verdrahtung darf nicht als konfiguriert durchgehen (Betriebsart explizit \xE4ndern statt Gruppen zuweisen).`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but wires assign.releaseApproval \u2014 dead wiring must not pass as configured (change the mode explicitly instead of assigning groups).`})),c?.approve!==void 0&&r.push(Se(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn){let A=w.responseCheck;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.responseCheck",{de:`[governedDocument/checkAssign] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') verdrahtet kein Team f\xFCr die Pr\xFCfung des R\xFCcklaufs (assign.responseCheck) \u2014 ohne Team l\xE4ge jeder R\xFCcklauf bei niemandem.`,en:`[governedDocument/checkAssign] Node "${e.id}" (responseStrategy '${e.responseStrategy}') wires no team for checking the returned copy (assign.responseCheck) \u2014 without a team every returned copy would lie with nobody.`})),e.production!=="resolver"&&i.issuesBy==="provider"?r.push(Se(e,"responseStrategy",{de:`[governedDocument/eSignatureNeedsResolver] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben (eSignature), erzeugt das Dokument aber mit production '${e.production}' \u2014 der Anbieter bekommt eine eingefrorene Vertragsrevision mit Unterschriftsankern und deklarierten Unterzeichnern, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/eSignatureNeedsResolver] Node "${e.id}" is signed electronically (eSignature) but produces the document with production '${e.production}' \u2014 the provider gets a frozen contract revision with signature anchors and declared signatories, and that only exists with production 'resolver'.`})):e.production!=="resolver"&&r.push(Se(e,"responseStrategy",{de:`[governedDocument/checkNeedsContract] Knoten "${e.id}" pr\xFCft den R\xFCcklauf (signedUploadChecked), erzeugt das Dokument aber mit production '${e.production}' \u2014 die Pr\xFCfung hakt die unterzeichnenden Personen einer eingefrorenen Vertragsrevision ab, und die entsteht nur mit production 'resolver'.`,en:`[governedDocument/checkNeedsContract] Node "${e.id}" checks the returned copy (signedUploadChecked) but produces the document with production '${e.production}' \u2014 the check ticks off the signatories of a frozen contract revision, and that only exists with production 'resolver'.`}))}else{e.production==="resolver"&&r.push(Se(e,"responseStrategy",{de:`[governedDocument/contractNeedsCheckedReturn] Knoten "${e.id}" erzeugt einen Vertrag (production 'resolver'), beantwortet ihn aber mit '${e.responseStrategy}' \u2014 ein Vertrag gilt erst als unterschrieben, wenn die Schule den R\xFCcklauf gepr\xFCft hat oder ein Anbieter die Unterschrift belegt: responseStrategy muss 'signedUploadChecked' oder 'eSignature' sein (mit assign.responseCheck und titles.check).`,en:`[governedDocument/contractNeedsCheckedReturn] Node "${e.id}" produces a contract (production 'resolver') but answers it with '${e.responseStrategy}' \u2014 a contract only counts as signed once the school has checked the returned copy or a provider proves the signature: responseStrategy must be 'signedUploadChecked' or 'eSignature' (with assign.responseCheck and titles.check).`}));for(let[A,E]of[["assign.responseCheck",w.responseCheck!==void 0],["titles.check",c?.check!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 eine Pr\xFCfung des R\xFCcklaufs gibt es nur mit responseStrategy 'signedUploadChecked' oder 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let A=w.signingRecovery;(typeof A!="string"||A.length===0)&&r.push(Se(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`}))}else w.signingRecovery!==void 0&&r.push(Se(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`}));if(i.issuesBy==="provider"&&r.push(...A5(e,n),...E5(e,n?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Se(e,"confirmBeforeIssue",{de:`[governedDocument/confirmBeforeIssue] Knoten "${e.id}" setzt confirmBeforeIssue auf ${JSON.stringify(e.confirmBeforeIssue)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmBeforeIssue] Node "${e.id}" sets confirmBeforeIssue to ${JSON.stringify(e.confirmBeforeIssue)} \u2014 only true or false is allowed.`})):e.confirmBeforeIssue===!0&&e.approval==="release"&&r.push(Se(e,"confirmBeforeIssue",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'release', deklariert aber confirmBeforeIssue \u2014 \u201EFreigabe anfordern" schickt noch nichts an die Familie, und die Freigabe selbst ist die bewusste Pr\xFCfung vor dem Versand. Die R\xFCckfrage gibt es nur mit approval 'none'.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'release' but declares confirmBeforeIssue \u2014 "Request release" sends nothing to the family yet, and the release itself is the deliberate check before sending. The confirmation prompt only exists with approval 'none'.`})),e.confirmContractTerms!==void 0&&typeof e.confirmContractTerms!="boolean"&&r.push(Se(e,"confirmContractTerms",{de:`[governedDocument/confirmContractTerms] Knoten "${e.id}" setzt confirmContractTerms auf ${JSON.stringify(e.confirmContractTerms)} \u2014 erlaubt ist nur true oder false.`,en:`[governedDocument/confirmContractTerms] Node "${e.id}" sets confirmContractTerms to ${JSON.stringify(e.confirmContractTerms)} \u2014 only true or false is allowed.`})),Nd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Se(e,"contractTermsQuestionText",{de:`[governedDocument/deadWiring] Knoten "${e.id}" schaltet die Best\xE4tigung der Vertragsbedingungen ab (confirmContractTerms: false), formuliert aber die Frage um \u2014 ohne Best\xE4tigung wird sie nie gestellt.`,en:`[governedDocument/deadWiring] Node "${e.id}" switches off the confirmation of the contract terms (confirmContractTerms: false) but rewords the question \u2014 without the confirmation it is never asked.`}));else for(let[A,E]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${A} \u2014 die Best\xE4tigung der Vertragsbedingungen geh\xF6rt zum Hochladen der unterschriebenen Fassung, das es nur mit responseStrategy 'signedUpload' oder 'signedUploadChecked' gibt.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares ${A} \u2014 the confirmation of the contract terms belongs to uploading the signed copy, which only exists with responseStrategy 'signedUpload' or 'signedUploadChecked'.`}));if(e.production==="none")for(let[A,E]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",w.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])E&&r.push(Se(e,A,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${A} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${A} \u2014 without a production phase there is nothing to carry it.`}));for(let A of e.tasks??[])_v.has(A.key)&&r.push(Se(e,`tasks.${A.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${A.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[..._v].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${A.key}" on node "${e.id}" collides with an intrinsic template (${[..._v].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...w5(e,n)):e.inputs?.[Pn]!==void 0&&r.push(Se(e,`inputs.${Pn}`,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', nennt aber einen Tr\xE4ger \u2014 nur ein erzeugter Vertrag hat eine Vertragspartei der Schule.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but names a legal entity \u2014 only a generated contract has a contracting party on the school's side.`})),r.push(...m5(e)),e.production==="resolver"){let A=Jr(e);if(A!==null){let E=aI(A);for(let I of $m(e)){if(!Ci(I.type)){r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/unknownFieldType] Generator "${E}" typisiert das Feld "${I.key}" als "${String(I.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Ls.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${E}" types the field "${I.key}" as "${String(I.type)}" \u2014 that is not part of the platform's value vocabulary (${Ls.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(I.type==="personList"){r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${E}" deklariert das Feld "${I.key}" als personList \u2014 daf\xFCr gibt es keine Platzhalter-Heimat im Dokument und keine Eingabe. Eine Liste von Personen geh\xF6rt als Rolle mit Kapazit\xE4t deklariert oder als berechneter Textwert.`,en:`[governedDocument/partyListUnsupported] Generator "${E}" declares the field "${I.key}" as personList \u2014 there is no placeholder home for it in the document and no input. A list of people belongs declared as a role with capacity or as a computed text value.`}));continue}I.type==="party"&&(I.key.endsWith("PartyId")||r.push(Se(e,`generatorStamp.inputSchema.${I.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${I.key}" endet nicht auf "PartyId" \u2014 aus diesem Suffix wird der Platzhalter-Pr\xE4fix im Dokument abgeleitet (emergencyContactPartyId \u2192 emergency_contact).`,en:`[governedDocument/partyFieldKey] Party field "${I.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...XL(e,{de:`"${E}"`,en:`"${E}"`}))}}else e.generatorStamp!==void 0&&r.push(Se(e,"generatorStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber den Stempel eines Generators \u2014 ohne maschinelle Produktion l\xE4uft keiner.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a generator stamp \u2014 without machine production none runs.`}));e.production==="template"?r.push(...S5(e)):e.templateStamp!==void 0&&r.push(Se(e,"templateStamp",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production '${e.production}', tr\xE4gt aber die Parameter einer Vorlage \u2014 ohne Vorlagen-Produktion wird sie nie gef\xFCllt.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production '${e.production}' but carries a template's parameters \u2014 without template production it is never filled.`}));let k=e.inputs?.[sa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${sa}`,{de:`[governedDocument/coverLetterInput] Knoten "${e.id}": Die Best\xE4tigung des Coverletters ist ein fester Wert ja oder nein.`,en:`[governedDocument/coverLetterInput] Node "${e.id}": the cover letter's confirmation is a fixed yes or no.`})),Fo(e)&&(n!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${sa}`,{de:`[governedDocument/coverLetterNotDeclared] Knoten "${e.id}" l\xE4sst ein Coverletter best\xE4tigen, sein Generator erzeugt aber keines.`,en:`[governedDocument/coverLetterNotDeclared] Node "${e.id}" asks to confirm a cover letter, but its generator produces none.`})),e.approval!=="release"&&r.push(Se(e,"approval",{de:`[governedDocument/coverLetterNeedsRelease] Knoten "${e.id}": Ein Coverletter mit Best\xE4tigung braucht die Freigabe, denn Vertrag und Coverletter werden zusammen freigegeben.`,en:`[governedDocument/coverLetterNeedsRelease] Node "${e.id}": a cover letter with confirmation needs the release, because contract and letter are released together.`})),di(e).producesResponseArtifact||r.push(Se(e,"responseStrategy",{de:`[governedDocument/coverLetterNeedsSigning] Knoten "${e.id}": Ein Coverletter steht vor einer Unterschrift; dieser Knoten l\xE4sst nicht unterschreiben.`,en:`[governedDocument/coverLetterNeedsSigning] Node "${e.id}": a cover letter comes before a signature; this node takes none.`})));let y=e.inputs?.[ai],v=y===void 0||y.kind==="unset"?void 0:y.kind==="literal"?y.value:y;return v!==void 0&&!jl(v)&&r.push(Se(e,`inputs.${ai}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(v)} \u2014 erlaubt ist eine ganze Zahl von ${Po} bis ${Do} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(v)} \u2014 a whole number from ${Po} to ${Do} days is allowed.`})),v===void 0&&$m(e).some(A=>A.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${ai}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" druckt die Antwortfrist (processSource 'responseDueInDays'), setzt aber kein responseDueInDays \u2014 das Dokument nennte eine Frist, die es nicht gibt.`,en:`[governedDocument/dueInDays] Node "${e.id}" prints the response deadline (processSource 'responseDueInDays') but sets no responseDueInDays \u2014 the document would name a deadline that does not exist.`})),r},"validate")};var t0={addPupil:{method:"POST",path:"/api/v1/admissions/AddPrPupilBasic/{schoolid}",kind:"create",body:"PrPupilBasicCreate",required:["forename","surname","genderId"],maxLength:{titleId:4,forename:50,surname:50,middleName:50,preferredForename:50,preferredSurname:50,genderId:4,firstLanguage:4}},addAdmissionDetails:{method:"POST",path:"/api/v1/admissions/AddAdmissionDetails/{schoolid}/{pupilid}",kind:"create",body:"AddPrPupilAdmissionDetails",required:[],maxLength:{boarderStatusId:4,ageAdjust:4,entryYear:4,entryTerm:4,entryYearGroup:4,currentSchoolId:20,enquirySource:4,currentAdmissionStageId:25}},addNationality:{method:"POST",path:"/api/v1/admissions/AddNationlityInfo/{schoolid}/{pupilid}",kind:"create",body:"NationalityInfoCreate",required:["nationalityId"],maxLength:{nationalityId:4,countryOfBirth:4}},addVisa:{method:"POST",path:"/api/v1/admissions/AddVisaInfo/{schoolid}/{pupilid}",kind:"create",body:"CreateVisaInfo",required:[],maxLength:{placeOfBirth:50,passportCountry:4,passportNumber:50,residenceVisaNumber:50,healthCardNumber:50}},addMedical:{method:"POST",path:"/api/v1/admissions/AddMedicalInfo/{schoolid}/{pupilid}",kind:"create",body:"MedicalInfoCreate",required:[],maxLength:{}},addContact:{method:"POST",path:"/api/v1/admissions/AddContactBasicInfo/{schoolid}/{pupilid}",kind:"create",body:"AddContactBasicInfo",required:["titleId","firstName","lastName","genderId"],maxLength:{relationshipId:4,titleId:4,firstName:50,middleName:50,lastName:50,contactName:200,greeting:200,languageId:4,secondLanguageId:4,genderId:4,professionId:4,companyName:50,jobTitle:50}},linkExistingContact:{method:"POST",path:"/api/v1/admissions/LinkExistingContact/{schoolid}/{pupilid}/{contactid}",kind:"create",body:"LinkContact",required:["relationshipId"],maxLength:{relationshipId:4}},addContactAddress:{method:"POST",path:"/api/v1/admissions/AddContactAddressNew/{schoolid}/{contactid}/{addressformatid}",kind:"create",body:"AddAddressVM",required:["countryId"],maxLength:{addressTypeId:4,countryId:4,addressLine1:100,addressLine2:100,addressLine3:100,addressLine4:100,addressLine5:100,addressLine6:100,lookup1:4,lookup2:4,lookup3:4,lookup4:4,lookup5:4}},addContactEmail:{method:"POST",path:"/api/v1/admissions/AddContactEmail/{schoolid}/{contactid}",kind:"create",body:"AddEmailAddress",required:["emailTypeId","email"],maxLength:{emailTypeId:4,email:254}},addContactTelephone:{method:"POST",path:"/api/v1/admissions/AddContactTelephone/{schoolid}/{contactid}",kind:"create",body:"AddTelephoneNumber",required:["typeId","number"],maxLength:{typeId:4}},linkAddressToPupil:{method:"PUT",path:"/api/v1/admissions/LinkAddressToPupil/{schoolId}/{pupilId}/{addressId}",kind:"update",required:[],maxLength:{}},updatePupilAif:{method:"POST",path:"/api/v1/additionalinformation/UpdatePupilAIF/{schoolid}/{pupilid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},updateContactAif:{method:"POST",path:"/api/v1/additionalinformation/UpdateContactAIF/{schoolid}/{contactid}",kind:"update",body:"AifFieldValueVM",required:[],maxLength:{}},listPupils:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfo/{schoolid}",kind:"read",required:[],maxLength:{}},getPupil:{method:"GET",path:"/api/v1/admissions/GetPrPupilBasicInfoById/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},listContactsOfPupil:{method:"GET",path:"/api/v1/admissions/GetContactBasicInfoByPupilId/{schoolid}/{pupilid}",kind:"read",required:[],maxLength:{}},getContact:{method:"GET",path:"/api/v1/admissions/GetContactByContactId/{schoolid}/{contactid}",kind:"read",required:[],maxLength:{}}};function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Kn,"isRecord");var Cv=["field","join","literal","address","payment","contract"],T5=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),$5=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ir(e){return typeof e=="string"&&e.trim().length>0}s(ir,"nonEmptyString");function Rm(e,t,n,r,i="value"){if(!Kn(e)||!Kn(e.from)){r.push({path:t,code:"mappingShape",message:{de:`${t}: eine Zuordnung braucht \`from\`.`,en:`${t}: a mapping needs \`from\`.`}});return}let o=e.from,a=Cv.filter(c=>c in o);if(a.length!==1){r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from\` nennt genau eine Quelle (${Cv.join(" | ")}).`,en:`${t}: \`from\` names exactly one source (${Cv.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ir(o.field)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.field\` ist leer.`,en:`${t}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(ir))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${t}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${t}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${t}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||ir(e.whenEmpty)||r.push({path:t,code:"mappingShape",message:{de:`${t}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${t}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(xe(o.address)&&o.address.scope==="env"&&Yn(o.address.key))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${t}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.payment\` ist amount oder settledAt.`,en:`${t}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${t}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:t,code:"mappingShape",message:{de:`${t}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${t}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!T5.has(String(e.format))&&r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekanntes Format \u201E${String(e.format)}".`,en:`${t}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(ir(e.lookup)&&Kn(n[e.lookup]))&&r.push({path:t,code:"unknownLookup",message:{de:`${t}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${t}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||Kn(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Kn(d)&&$5.has(String(d.address))||r.push({path:t,code:"mappingShape",message:{de:`${t}: unbekannte Auswahl \`pick\`.`,en:`${t}: unknown selection \`pick\`.`}}))}s(Rm,"checkMapping");function Gi(e,t,n,r,i){if(!Kn(e)){i.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${t}: expects an object field \u2192 mapping.`}});return}let o=t0[n];for(let a of o.required)a in e||i.push({path:`${t}.${a}`,code:"missingRequired",message:{de:`${t}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${t}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))Rm(l,`${t}.${a}`,r,i)}s(Gi,"checkBody");function n0(e,t,n,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,code:"bodyShape",message:{de:`${t}: erwartet eine Liste.`,en:`${t}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${t}[${a}]`;if(!Kn(o)||!ir(o.fieldId)){r.push({path:l,code:"aifShape",message:{de:`${l}: \`fieldId\` fehlt.`,en:`${l}: \`fieldId\` is missing.`}});return}i.has(o.fieldId)&&r.push({path:l,code:"aifDuplicate",message:{de:`${l}: \u201E${o.fieldId}" doppelt.`,en:`${l}: "${o.fieldId}" appears twice.`}}),i.add(o.fieldId),Rm(o.value,`${l}.value`,n,r),o.unless!==void 0&&Rm(o.unless,`${l}.unless`,n,r,"condition")})}s(n0,"checkAif");function Pv(e){let t=[];if(!Kn(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let n=Kn(e.lookups)?e.lookups:{};Kn(e.lookups)||t.push({path:"engage.lookups",code:"bodyShape",message:{de:"`engage.lookups` fehlt (Tabellen Name \u2192 Plexus-Wert \u2192 Engage-Id).",en:"`engage.lookups` is missing (tables name \u2192 Plexus value \u2192 Engage id)."}});for(let[r,i]of Object.entries(n))(!Kn(i)||!Object.values(i).every(ir))&&t.push({path:`engage.lookups.${r}`,code:"lookupShape",message:{de:`Lookup \u201E${r}": jede Engage-Id ist ein nicht leerer Text.`,en:`Lookup "${r}": every Engage id is a non-empty text.`}});if(ir(e.addressFormatId)||t.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Gi(e.pupil,"engage.pupil","addPupil",n,t),Gi(e.admission,"engage.admission","addAdmissionDetails",n,t),e.nationality!==void 0&&Gi(e.nationality,"engage.nationality","addNationality",n,t),e.visa!==void 0&&Gi(e.visa,"engage.visa","addVisa",n,t),e.medical!==void 0&&Gi(e.medical,"engage.medical","addMedical",n,t),n0(e.pupilAif,"engage.pupilAif",n,t),!Array.isArray(e.contacts))t.push({path:"engage.contacts",code:"bodyShape",message:{de:"`engage.contacts` fehlt (Liste der Kontakte).",en:"`engage.contacts` is missing (list of contacts)."}});else{let r=new Set;e.contacts.forEach((i,o)=>{let a=`engage.contacts[${o}]`;if(!Kn(i)||!ir(i.key)||!ir(i.presentIf)){t.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&t.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Gi(i.basic,`${a}.basic`,"addContact",n,t),i.address!==void 0&&Gi(i.address,`${a}.address`,"addContactAddress",n,t);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){t.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Gi(u,`${a}.${l}[${p}]`,d,n,t))}}n0(i.aif,`${a}.aif`,n,t),i.linkAddressToPupilIf!==void 0&&Rm(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,t,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Kn(r)||!ir(r.repeated)||!ir(r.field)||!ir(r.equals))&&t.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return t}s(Pv,"engagePushConfigIssues");function*Dv(e){let t=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let n of t)for(let r of Object.values(n??{}))yield{mapping:r};for(let n of e.pupilAif??[])yield{mapping:n.value},n.unless!==void 0&&(yield{mapping:n.unless});for(let n of e.contacts){let r=[n.basic,n.address,...n.emails??[],...n.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:n.key};for(let i of n.aif??[])yield{mapping:i.value,contactKey:n.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:n.key});n.linkAddressToPupilIf!==void 0&&(yield{mapping:n.linkAddressToPupilIf,contactKey:n.key})}}s(Dv,"mappingsOf");function r0(e){let t=new Set(e.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of Dv(e))for(let i of R5(n.from))t.add(I5(i,r));return[...t]}s(r0,"configFieldKeys");function R5(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(R5,"formFieldsOf");function I5(e,t){return e.startsWith(".")?(t===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${t}${e}`):e}s(I5,"resolveFieldKey");function i0(e,t){for(let{mapping:n}of Dv(e))if(t in n.from)return!0;return!1}s(i0,"configReadsSource");function o0(e){let t=new Set;for(let{mapping:n}of Dv(e))"address"in n.from&&t.add(n.from.address.key);return[...t]}s(o0,"configEnvLeaves");var s0="done",a0=["sandbox","production"];var Im="engagePush",dPe=660*1e3;function zi(e,t,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${t}`,reason:n,severity:r}}s(zi,"issue");function Fv(e,t){let n=e.inputs?.[t];return n?.kind==="literal"?n.value:void 0}s(Fv,"literal");function l0(e){return Pv(e.engage).length===0?e.engage:null}s(l0,"validConfig");function O5(e,t){let n=new Map(e.nodes.map(a=>[a.id,a])),r=e.nodes.filter(a=>a.type==="eventTrigger"),i=new Set,o=r.map(a=>a.id);for(;o.length>0;){let a=o.pop();if(a===t||i.has(a))continue;i.add(a);let l=n.get(a);if(l!==void 0){if(l.type==="end"){let d=l.inputs?.applicationOutcome;if(d?.kind==="literal"&&d.value==="approved")return!0;continue}for(let d of Object.values(l.next??{})){let c=d?.to;typeof c=="string"&&o.push(c)}}}return!1}s(O5,"bypassingPath");var d0={role:"system-action",effect:"side-effect",outcomes:[{id:s0,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let t=l0(e);return t===null?[]:o0(t)},"envReads"),inputs:s(()=>[{id:"target",label:{de:"Ziel-Engage",en:"Target Engage"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"sandbox",label:{de:"Sandbox",en:"Sandbox"}},{value:"production",label:{de:"Produktion",en:"Production"}}]},{id:"contractFields",label:{de:"Vertragsfelder F01\u2013F25",en:"Contract fields F01\u2013F25"},type:"enum",required:!1,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"off",label:{de:"Nicht \xFCbertragen (Bedeutung offen)",en:"Do not transfer (meaning open)"}},{value:"on",label:{de:"\xDCbertragen",en:"Transfer"}}]}],"inputs"),validate:s((e,t,n)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=Fv(e,"target");a0.includes(a)||o.push(zi(e,"inputs.target",{de:`[engagePush/invalidTarget] \u201E${r}": das Ziel ist sandbox oder production.`,en:`[engagePush/invalidTarget] "${i}": the target is sandbox or production.`}));let l=Fv(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(zi(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[Im];(typeof d!="string"||d.length===0)&&o.push(zi(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Im}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Im}\` names the team.`}));for(let y of Pv(e.engage))o.push(zi(e,y.path,{de:`[engagePush/config] \u201E${r}": ${y.message.de}`,en:`[engagePush/config] "${i}": ${y.message.en}`}));let c=t.nodes.filter(y=>y.id!==e.id&&y.type==="engagePush"&&Fv(y,"target")===a);c.length>0&&o.push(zi(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(y=>`"${y.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(y=>`"${y.id}"`).join(", ")} already transfers to the same target.`})),O5(t,e.id)&&o.push(zi(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let u=l0(e),p=e;for(let[y,v,A,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!i0(u,y)||p[v]!==void 0||o.push(zi(e,v,{de:Ks("address/missing",{where:`\u201E${r}\u201C \u203A ${A}`},"de"),en:Ks("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let h=p.form,w=xe(h)&&h.scope==="node"?h.owner:void 0,k=w===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(w);if(u!==null&&k!==void 0){let y=new Set(k.keys()),v=r0(u).filter(A=>!y.has(A)&&!/\[\d+\]\./.test(A));if(v.length>0){let A=t.nodes.find(E=>E.id===w);o.push(zi(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${A?.label?.de??w}" nicht \u2014 sie werden nicht \xFCbertragen: ${v.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${A?.label?.en||w}" does not know these fields \u2014 they are not transferred: ${v.join(", ")}.`},"warning"))}}return o},"validate")};var Jo={join:LF,end:zO,roleAssign:qF,eventTrigger:KF,waitlist:rL,completenessCheck:uL,form:YF,setFlag:HF,if:JF,decision:Yo,review:pL,collectPayment:kL,governedDocument:e0,countersign:yC,engagePush:d0};UI(Jo);function c0(e,t){let n=e;if(n==null||!Array.isArray(n.nodes))throw new Error(`offer plan: the ${t} carries no workflow graph with nodes`);return e}s(c0,"graphOf");function u0(e){let t=new Map;for(let n of e.nodes)for(let r of Pr(e,n))t.set(pe(r.address),r.nodeId);return t}s(u0,"producedOf");function f0(e){let t=new Map;for(let n of e.nodes)t.set(n.id,new Set(xo(e,n).map(r=>pe(r.address))));return t}s(f0,"readsOf");function p0(e,t){let n=c0(e,"bundle"),r=c0(t.graph,"live head"),i=u0(n),o=u0(r),a={added:[],removed:[],moved:[]};for(let[u,p]of i){let h=o.get(u);h===void 0?a.added.push({address:u,nodeId:p}):h!==p&&a.moved.push({address:u,from:h,to:p})}for(let[u,p]of o)i.has(u)||a.removed.push({address:u,nodeId:p});let l=f0(n),d=f0(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let p=l.get(u)??new Set,h=d.get(u)??new Set,w=[...p].filter(y=>!h.has(y)),k=[...h].filter(y=>!p.has(y));(w.length>0||k.length>0)&&c.push({nodeId:u,added:w,removed:k})}return{headRevision:t.revision,pinnedApplications:t.pinnedApplications,produced:a,reads:c}}s(p0,"planAddresses");function m0(e){let t=[...e.produced.moved.map(i=>({icon:"~",target:`address:${i.address}`,status:`Knoten ${i.from} \u2192 ${i.to}`})),...e.produced.added.map(i=>({icon:"+",target:`address:${i.address}`,status:`neu (${i.nodeId})`})),...e.produced.removed.map(i=>({icon:"-",target:`address:${i.address}`,status:`entfernt (${i.nodeId})`})),...e.reads.map(i=>({icon:"~",target:`reads:${i.nodeId}`,status:[i.added.length>0?`+${i.added.join(", ")}`:"",i.removed.length>0?`\u2212${i.removed.join(", ")}`:""].filter(Boolean).join(" ")}))];if(t.length===0)return[];let{real:n,test:r}=e.pinnedApplications;return t.push({icon:"!",target:"pinned",status:`${n+r} Anmeldungen (${n} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),t}s(m0,"addressPlanRows");function h0(e,t){return t==null?!0:Ne(e)!==Ne(t)}s(h0,"changed");async function g0(e,t,n){if(t.index.module!==Qb.name)throw new Error(`offer: unknown module "${t.index.module}"`);return HC(e,t,n,{afterManifestPublish:s(async()=>{if(t.index.links?.unitKey||t.index.program)return Qb.scaffold(e,t.index.slugs.manifest,t.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}s(g0,"applyOffer");async function y0(e,t,n,r="published"){let i=await e.query(x.setup.offerBundle.exportOfferBundle,{client:t,offerKey:n,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(y0,"exportOffer");async function Lv(e,t){let{index:n}=t,i=(await e.query(x.workflow.listManifests,{client:n.tenant})).find(w=>w.offerKey===n.slugs.manifest),o="create";i&&(o="same");let a={};for(let[w,k]of Object.entries(t.smartforms??{})){let y=i?await e.query(x.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:w}):null;a[w]=y?.def?h0(k,{label:y.def.label,...y.def.definition})?"change":"same":"create"}let l="absent",d=null;if(t.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let w=await e.query(x.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),k=w?.publishedVersion??w?.draftVersion;l=h0(k&&{graph:$s(t.workflow.graph),progressLayout:t.workflow.progressLayout??k.progressLayout,progressWiring:t.workflow.progressWiring??k.progressWiring},k&&{graph:$s(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let w=await e.query(x.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});w!==null&&(d=p0(t.workflow.graph,w))}}let c=n.program?.stages,u=c===void 0?[]:i?await Jb(e,n.tenant,n.slugs.manifest,c):dm(null,[],c),p=await mm(e,n.tenant,i?n.slugs.manifest:null,n),h=i?await e.query(x.workflow.getOfferPublishState,{client:n.tenant,offerKey:n.slugs.manifest}):null;return{manifest:o,smartforms:a,workflow:l,addresses:d,stages:u,capacities:p,publishPending:h?.draftDiffersFromExternal??null,draftRevision:h?.draftRevision??null,externalHeadRevision:h?.externalHeadRevision??null}}s(Lv,"diffOffer");function Om(e){if(e.type==="governedDocument"){let t=e.production;return t==="resolver"?"resolver":t==="template"?"template":t==="upload"||t==="none"?"manual":"unauthored"}return null}s(Om,"contractProductionModeOf");function w0(e){return Om(e)==="resolver"}s(w0,"isResolverCarrierNode");function _m(e){return(e.workflow?.graph?.nodes??[]).flatMap(n=>{let r=Jr(n);return!w0(n)||r===null?[]:[{node:n,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(_m,"authoredPins");var k0={type:"address",dataType:"composite"};var b0={type:"boolean",dataType:"boolean"};var v0={type:"consent",dataType:"boolean"};var x0={type:"date",dataType:"date"};var S0={type:"docRef",dataType:"file"};var A0={type:"email",dataType:"text"};var E0={type:"enum",dataType:"option"};var T0={type:"string",dataType:"text"};var $0={type:"tel",dataType:"text"};var Nm={address:k0.dataType,boolean:b0.dataType,consent:v0.dataType,date:x0.dataType,docRef:S0.dataType,email:A0.dataType,enum:E0.dataType,string:T0.dataType,tel:$0.dataType};function Mv(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Mv,"shapeOf");function R0(e){let t=new Map,n=[],r=s(o=>{o.fields.forEach(a=>t.set(a.key,Mv(a))),o.groups?.forEach(a=>a.fields.forEach(l=>t.set(l.key,Mv(l)))),o.repeated?.forEach(a=>n.push({key:a.key,itemTemplate:a.itemTemplate,effects:a.effects??[]})),o.subsections?.forEach(r)},"visit");e.sections.forEach(r);let i=[{pathPrefix:"",effects:e.effects??[],shapes:t}];for(let o of n){let a=new Map(t);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,Mv(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(R0,"fieldMapScopes");function _5(e){let t=new Set,n=s(r=>{r.computed?.forEach(i=>t.add(i.key)),r.subsections?.forEach(n)},"visit");return e.sections.forEach(n),t}s(_5,"computedKeysOf");function I0(e){let t=[],n=_5(e);for(let r of R0(e))r.effects.forEach((i,o)=>{if(i.kind!=="fieldMap")return;let a=new Map;i.mappings.forEach((l,d)=>{let c=`${r.pathPrefix}effects[${o}].mappings[${d}]`;n.has(l.from)&&t.push({severity:"error",path:`${c}.from`,code:"fieldmap.computed-source",message:`Effect '${i.id}' fieldMap '${l.from}' \u2192 '${l.to}': '${l.from}' is a computed field. Its value is derived, never stored, and would never reach the party.`});let u=a.get(l.to);u!==void 0&&u!==l.from?t.push({severity:"error",path:`${c}.to`,code:"fieldmap.duplicate-target",message:`Effect '${i.id}' maps both '${u}' and '${l.from}' onto custom field '${l.to}'. One party field holds one value \u2014 the write would keep one and drop the other.`}):a.set(l.to,l.from)})});return t}s(I0,"validateFieldMapSources");function O0(e){let t=[],n=new Set;for(let o of R0(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)n.add(l.from);let r=s((o,a)=>{let l=a.some(d=>n.has(d));o.kind==="cf_value"&&!l?t.push({severity:"error",path:`field '${o.key}'`,code:"persist.cf-unmapped",message:`Field '${o.key}' declares kind 'cf_value' but is not the source of any fieldMap mapping. Either wire a fieldMap ('${o.key}' \u2192 a custom-field key) or set kind: 'control'.`}):o.kind==="control"&&l&&t.push({severity:"error",path:`field '${o.key}'`,code:"persist.control-mapped",message:`Field '${o.key}' declares kind 'control' but is used as a fieldMap source, which would persist it. Set kind: 'cf_value', or remove the fieldMap mapping (a control field may still feed OutcomeDef.output.fields).`})},"check"),i=s(o=>{o.fields.forEach(a=>r(a,[a.key])),o.groups?.forEach(a=>a.fields.forEach(l=>r(l,[l.key]))),o.repeated?.forEach(a=>a.itemTemplate.forEach(l=>r(l,[`$item.${l.key}`,l.key]))),o.subsections?.forEach(i)},"visit");return e.sections.forEach(i),t}s(O0,"validateFieldPersistence");var N5="$";function C5(e){return typeof e=="string"&&e.startsWith(N5)}s(C5,"isRef");function Cm(e){return e.slice(1)}s(Cm,"stripRef");function*P5(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let t of Object.values(e.meta))yield t;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(P5,"refSlots");function D5(e){let t=new Set;for(let n of P5(e))C5(n)&&t.add(Cm(n));return[...t]}s(D5,"collectRefs");function F5(e){let t=new Set(e.map(o=>o.id)),n=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),n.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of D5(o))t.has(a)&&(n.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=Cm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Cm(l.target)===a||l.kind==="shareValue"&&Cm(l.to)===a)||n.get(o.id).includes(l.id)||(n.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:n,successors:r,byId:i}}s(F5,"buildAdjacency");function _0(e){let{refsOf:t}=F5(e),r=Jf(e.map(i=>i.id),i=>(t.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(_0,"detectCycle");function N0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(N0,"escapeRegExp");function Wi(e){return new RegExp(`^${N0(e)}\\[(\\d+)\\]\\.(.+)$`)}s(Wi,"repeatedRowKeyPattern");function qv(e,t){let n=Wi(t),r=0;for(let i of Object.keys(e)){let o=i.match(n);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(qv,"countRepeatedRows");function C0(e,t,n){let r=Wi(t);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==n)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(C0,"repeatedRowHasData");function P0(e){return e.endsWith(".count")?e.slice(0,-6):e}s(P0,"readKeyOf");function Kv(e){return{sections:e,fields:[]}}s(Kv,"hiddenSectionsOnly");function D0(e,t,n){for(let r of e.fields)t.add(r.key);for(let r of e.groups??[])for(let i of r.fields)t.add(i.key);for(let r of e.computed??[])t.add(r.key);for(let r of e.repeated??[])n.add(r.key);for(let r of e.subsections??[])D0(r,t,n)}s(D0,"collectKeys");function F0(e){let t=[],n=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;D0(r,i,o),t.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(Wi)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(F0,"restrictedSectionsOf");function L0(e,t){return t.fieldKeys.has(e)||t.repeatedKeys.has(e)?!0:t.rowKeyPatterns.some(n=>n.test(e))}s(L0,"matchesKey");function L5(e,t){return t.find(n=>L0(e,n))??null}s(L5,"hiddenSectionOfKey");function M5(e,t){for(let n=e;;){if(L0(n,t))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}s(M5,"fieldOwnsKey");function q5(e,t){return t.find(n=>M5(e,n))??null}s(q5,"restrictedFieldOfKey");function K5(e,t){let n=L5(e,t.sections);if(n!==null)return{kind:"section",section:n};let r=q5(e,t.fields);return r===null?null:{kind:"field",field:r}}s(K5,"hiddenOwnerOfKey");function Pm(e,t){return K5(e,t)!==null}s(Pm,"isKeyHidden");function j5(e,t,n,r,i){let o=[];r&&o.push({severity:"error",path:n,code:"section.visibleTo-nested",message:{de:`Abschnitt '${e}' liegt in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) und darf selbst keine tragen.`,en:`Section '${e}' sits inside a section with restricted visibility (visibleTo) and may not carry one itself.`}});let a=s(l=>typeof l!="string"||l.trim()==="","isBlank");if((t.length===0||t.some(a)||new Set(t).size!==t.length)&&o.push({severity:"error",path:n,code:"section.visibleTo-invalid",message:{de:`Abschnitt '${e}': visibleTo braucht mindestens ein Team, ohne leere oder doppelte Eintr\xE4ge.`,en:`Section '${e}': visibleTo needs at least one team, with no blank or repeated entries.`}}),i===void 0)return o;for(let l of t)a(l)||i.has(l)||o.push({severity:"error",path:n,code:"section.visibleTo-unknown",message:{de:`Abschnitt '${e}': '${l}' ist weder ein Team noch eine Rechtegruppe dieser Schule.`,en:`Section '${e}': '${l}' is neither a team nor a permission group of this school.`}});return o}s(j5,"visibleToListIssues");function M0(e,t,n){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...j5(c.id,h,`${u}.visibleTo`,p,n));let w=p||h!==void 0;if(w){let k=[...c.fields,...(c.groups??[]).flatMap(y=>y.fields),...(c.repeated??[]).flatMap(y=>y.itemTemplate)];for(let y of k)y.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${y.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${y.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,y)=>i(k,`${u}.subsections[${y}]`,w))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=F0(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=Kv(p);for(let w of It(c)){let k=P0(w);(Pm(w,h)||Pm(k,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${w}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${w}' from a section with restricted visibility (visibleTo) \u2014 whoever cannot see the section would get a different result here.`}})}},"checkAst"),l=s((c,u,p)=>{a(c.visibleIf,`${u}.visibleIf`,p),a(c.requiredIf,`${u}.requiredIf`,p),a(c.disabledIf,`${u}.disabledIf`,p),a(c.defaultValue,`${u}.defaultValue`,p),c.sameAs!==void 0&&Pm(c.sameAs.source,Kv(p))&&r.push({severity:"error",path:`${u}.sameAs`,code:"section.visibleTo-read-outside",message:{de:`${u} \xFCbernimmt '${c.sameAs.source}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo).`,en:`${u} copies '${c.sameAs.source}' from a section with restricted visibility (visibleTo).`}})},"checkField"),d=s((c,u,p)=>{let h=c.visibleTo!==void 0?c.id:p,w=o.filter(k=>k.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:w),c.fields.forEach((k,y)=>l(k,`${u}.fields[${y}]`,w)),c.groups?.forEach((k,y)=>{a(k.visibleIf,`${u}.groups[${y}].visibleIf`,w),k.fields.forEach((v,A)=>l(v,`${u}.groups[${y}].fields[${A}]`,w))}),c.repeated?.forEach((k,y)=>{a(k.itemVisibleIf,`${u}.repeated[${y}].itemVisibleIf`,w),k.itemTemplate.forEach((v,A)=>l(v,`${u}.repeated[${y}].itemTemplate[${A}]`,w))}),c.computed?.forEach((k,y)=>a(k.expression,`${u}.computed[${y}]`,w)),c.subsections?.forEach((k,y)=>d(k,`${u}.subsections[${y}]`,h))},"visitCompiled");return t.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(M0,"sectionVisibilityIssues");var jr="#";var q0=s(e=>{let t=hk.find(n=>n.systemColumn===e);return t===void 0&&F(`[personName] no system field backs ${e}`),t.key},"keyOfColumn"),vr={firstName:q0("persons.firstName"),lastName:q0("persons.lastName")};function K0(e,t){let n={firstName:[],lastName:[]},r=`$${e}`;for(let i of t)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===vr.firstName?n.firstName.push(o):a===vr.lastName&&n.lastName.push(o);return n}s(K0,"personNameKeys");function j0(e){return[...e.firstName,...e.lastName]}s(j0,"personNameKeyList");function V0(e){return e.firstName.length>0||e.lastName.length>0}s(V0,"hasPersonName");function Aa(e,t=[],n){let r=[];return e.forEach((i,o)=>{let a=[...t,o];r.push({section:i,path:a,parentId:n});for(let l of Aa(i.subsections??[],a,i.id))r.push(l)}),r}s(Aa,"walkSections");function V5(e,t){for(let n of e.fields)if(n.key===t)return n;for(let n of e.groups??[])for(let r of n.fields)if(r.key===t)return r;for(let n of e.repeated??[])for(let r of n.itemTemplate)if(r.key===t)return r;return null}s(V5,"findFieldInSection");function B0(e,t){for(let n of Aa(e.sections)){let r=V5(n.section,t);if(r)return{section:n.section,field:r}}return null}s(B0,"findField");var B5=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],U5=["blue","rose","amber","violet","teal","emerald","slate"];function U0(e){return B5.includes(e)}s(U0,"isBucketIconName");function G0(e){return U5.includes(e)}s(G0,"isBucketColorName");var G5="__clear__";function z0(e){return e===""?"empty":e===G5?"reserved":null}s(z0,"selectOptionValueDefect");var jv=XP.docRef.allowedMime;function Z0(e,t={}){let n=ra(e).compiled,r=[],i=new Set,o=new Map,a=new Set,l=new Set,d=new Set,c=new Map,u=new Map;function p(O,N){if(i.has(O))return;i.add(O);let K=o.get(O.id);K&&K!==O?r.push({severity:"error",path:`sections[${N.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${O.id}' ist mehrfach deklariert.`,en:`Section id '${O.id}' is declared more than once.`}}):o.set(O.id,O);let P=`sections[${N.join(".")}]`;O.fields.forEach((U,se)=>{Ea(a,U.key,`${P}.fields[${se}]`,"duplicate.field-key",r),l.add(U.key),u.set(U.key,U),c.set(U.key,Bv(U)),U.externalFlag&&(U.type!=="boolean"&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${U.key}' muss den Typ 'boolean' haben (ist '${U.type}').`,en:`External flag '${U.key}' must be type 'boolean' (got '${U.type}').`}}),U.reviewRequired!==void 0&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"review.on-flag",message:{de:`Externes Flag '${U.key}' ist als pr\xFCfpflichtig markiert \u2014 ein Flag setzt der Prozess, die Familie reicht nichts ein, was jemand pr\xFCfen k\xF6nnte.`,en:`External flag '${U.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),U.notice!==void 0&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${U.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${U.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),U.defaultValue==null&&r.push({severity:"error",path:`${P}.fields[${se}]`,code:"flag.missing-default",message:{de:`Externes Flag '${U.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${U.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...Y0(U,`${P}.fields[${se}]`)),r.push(...W0(U,`${P}.fields[${se}]`))}),O.groups?.forEach((U,se)=>{U.fields.forEach((le,De)=>{Ea(a,le.key,`${P}.groups[${se}].fields[${De}]`,"duplicate.field-key",r),l.add(le.key),u.set(le.key,le),c.set(le.key,Bv(le)),le.externalFlag&&r.push({severity:"error",path:`${P}.groups[${se}].fields[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${le.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${le.key}' must be a direct section field, not a group field.`}}),r.push(...Y0(le,`${P}.groups[${se}].fields[${De}]`)),r.push(...W0(le,`${P}.groups[${se}].fields[${De}]`))})}),O.repeated?.forEach((U,se)=>{U.itemTemplate.forEach((le,De)=>{Ea(a,le.key,`${P}.repeated[${se}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(le.key,Bv(le)),le.externalFlag&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${le.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${le.key}' must be a direct section field, not a repeated item field.`}}),le.export&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"export.in-repeated",message:{de:`Feld '${le.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${le.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),le.sameAs&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${le.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${le.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),le.reviewRequired!==void 0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"review.in-repeated",message:{de:`Feld '${le.key}' ist in einem itemTemplate einer Wiederholung als pr\xFCfpflichtig markiert \u2014 ein Zeilenfeld hat je Zeile einen Wert, kein Feld der Bewerbung, das man einmal abhaken k\xF6nnte.`,en:`Field '${le.key}' is marked as requiring review inside a repeated itemTemplate \u2014 a row field has one value per row, no field of the application to tick once.`}}),le.notice!==void 0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.notice-in-repeated",message:{de:`Feld '${le.key}' tr\xE4gt einen Hinweis (notice) in einem itemTemplate einer Wiederholung \u2014 dort wird er nicht angezeigt. Den Hinweis an den Abschnitt setzen.`,en:`Field '${le.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),le.type==="docRef"&&le.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${P}.repeated[${se}].itemTemplate[${De}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${le.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${le.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),O.computed?.forEach(U=>{d.add(U.key),Ea(a,U.key,`${P}.computed[${U.key}]`,"duplicate.field-key",r),U.exportType==="consent"&&r.push({severity:"error",path:`${P}.computed[${U.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${U.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${U.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),U.export===!0&&U.exportType===void 0&&r.push({severity:"error",path:`${P}.computed[${U.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${U.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${U.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),O.subsections?.forEach((U,se)=>p(U,[...N,se]))}s(p,"visitRawSection"),e.sections.forEach((O,N)=>p(O,[N]));let h=new Set;n.effects.forEach((O,N)=>{Ea(h,O.id,`effects[${N}]`,"duplicate.effect-id",r)});let w=new Set;n.outcomes.forEach((O,N)=>{Ea(w,O.id,`outcomes[${N}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach((O,N)=>{O.output.effectRefs?.forEach((K,P)=>{h.has(K.effect)||r.push({severity:"error",path:`outcomes[${N}].output.effectRefs[${P}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${O.id}' verweist auf den unbekannten Effekt '${K.effect}'.`,en:`Outcome '${O.id}' references unknown effect '${K.effect}'.`}})})}),n.outcomes.forEach((O,N)=>{O.output.fields?.forEach((K,P)=>{B0(n,K.path)||r.push({severity:"error",path:`outcomes[${N}].output.fields[${P}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${O.id}' verweist auf das unbekannte Feld '${K.path}'.`,en:`Outcome '${O.id}' references unknown field '${K.path}'.`}})})});let k=new Set;for(let O of Aa(n.sections))for(let N of O.section.repeated??[])k.add(`${N.key}.count`);for(let O of k)(a.has(O)||d.has(O))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${O}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${O}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let y={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:t.stageKeys};r.push(...pN(e)),r.push(...M0(e,n,t.visibleToKeys)),r.push(...YN(e)),r.push(...cN(e,t.stageKeys));for(let O of Aa(n.sections)){let N=O.section,K=`sections[${O.path.join(".")}]`;N.visibleIf&&(xr(N.visibleIf,`${K}.visibleIf`,y,!1,r),Ta(N.visibleIf,`${K}.visibleIf`,c,r)),N.fields.forEach((P,U)=>Vv(P,`${K}.fields[${U}]`,y,!1,c,r)),N.groups?.forEach((P,U)=>{P.visibleIf&&(xr(P.visibleIf,`${K}.groups[${U}].visibleIf`,y,!1,r),Ta(P.visibleIf,`${K}.groups[${U}].visibleIf`,c,r)),P.fields.forEach((se,le)=>Vv(se,`${K}.groups[${U}].fields[${le}]`,y,!1,c,r))}),N.repeated?.forEach((P,U)=>{P.itemVisibleIf&&(xr(P.itemVisibleIf,`${K}.repeated[${U}].itemVisibleIf`,y,!0,r),Ta(P.itemVisibleIf,`${K}.repeated[${U}].itemVisibleIf`,c,r)),P.itemTemplate.forEach((se,le)=>Vv(se,`${K}.repeated[${U}].itemTemplate[${le}]`,y,!0,c,r)),P.effects?.forEach((se,le)=>{se.when&&xr(se.when,`${K}.repeated[${U}].effects[${le}].when`,y,!0,r)})}),N.computed?.forEach((P,U)=>xr(P.expression,`${K}.computed[${U}].expression`,y,!1,r))}n.effects.forEach((O,N)=>{O.when&&xr(O.when,`effects[${N}].when`,y,!1,r)}),n.outcomes.forEach((O,N)=>{xr(O.when,`outcomes[${N}].when`,y,!1,r)});let v=new Set(n.outcomes.map(O=>O.id));function A(O,N){O.requiredFor&&O.requiredFor.forEach((K,P)=>{v.has(K)||r.push({severity:"error",path:`${N}.requiredFor[${P}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${O.key}": requiredFor verweist auf das unbekannte Ergebnis "${K}"`,en:`field "${O.key}": requiredFor references unknown outcome "${K}"`}})})}s(A,"checkRequiredFor");for(let O of Aa(n.sections)){let N=O.section,K=`sections[${O.path.join(".")}]`;N.fields.forEach((P,U)=>A(P,`${K}.fields[${U}]`)),N.groups?.forEach((P,U)=>{P.fields.forEach((se,le)=>A(se,`${K}.groups[${U}].fields[${le}]`))}),N.repeated?.forEach((P,U)=>{P.itemTemplate.forEach((se,le)=>A(se,`${K}.repeated[${U}].itemTemplate[${le}]`))})}function E(O,N){let K=s((P,U)=>{let se=(P.type==="docRef"?P.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!jv.includes(Ee));se.length>0&&r.push({severity:"error",path:U,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${P.key}' erlaubt ${se.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${jv.join(", ")}).`,en:`Field '${P.key}' allows ${se.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${jv.join(", ")}).`}});let le=P.type==="docRef"?P.docRefConstraints?.minFiles:void 0;if(le!==void 0){let Ee=P.docRefConstraints?.multiple===!0,ft=typeof le=="number"&&Number.isInteger(le)&&le>=2;(!Ee||!ft)&&r.push({severity:"error",path:U,code:"config.docref-min-files",message:Ee?{de:`Feld '${P.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(le)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${P.key}' sets docRefConstraints.minFiles to ${JSON.stringify(le)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${P.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${P.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}P.multiple===!0&&P.type!=="enum"&&r.push({severity:"error",path:U,code:"config.multiple-non-enum",message:{de:`Feld '${P.key}' setzt multiple: true, hat aber den Typ '${P.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(P.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${P.key}' sets multiple: true but is type '${P.type}' \u2014 only 'enum' supports multi-select.`+(P.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),P.presentation==="yesNo"&&P.type!=="boolean"&&r.push({severity:"error",path:U,code:"config.yesno-non-boolean",message:{de:`Feld '${P.key}' setzt presentation: 'yesNo', hat aber den Typ '${P.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${P.key}' sets presentation: 'yesNo' but is type '${P.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),P.presentation==="yesNo"&&P.defaultValue!=null&&r.push({severity:"error",path:U,code:"config.yesno-default",message:{de:`Feld '${P.key}' ist eine Ja | Nein-Frage (presentation: 'yesNo') mit einem defaultValue \u2014 die Familie muss die Antwort selbst w\xE4hlen. Den defaultValue entfernen.`,en:`Field '${P.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...W5(P,U)),typeof P.minSelections=="number"&&typeof P.maxSelections=="number"&&P.minSelections>P.maxSelections&&r.push({severity:"error",path:U,code:"config.min-gt-max-selections",message:{de:`Feld '${P.key}' hat minSelections (${P.minSelections}) > maxSelections (${P.maxSelections}).`,en:`Field '${P.key}' has minSelections (${P.minSelections}) > maxSelections (${P.maxSelections}).`}}),r.push(...Y5(P,U));let De=P.enumRef;De!==void 0&&r.push({severity:"error",path:`${U}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${P.key}' nennt den entfernten Options-Katalog (enumRef '${String(De)}'). Die Optionen im Formular angeben (enumOptions + enumOptionLabels) oder eine Liste des Mandanten binden (enumListKey).`,en:`Field '${P.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(P.enumOptions??[]).forEach((Ee,ft)=>{let He=z0(Ee);He!==null&&r.push({severity:"error",path:`${U}.enumOptions[${ft}]`,code:"config.enum-option-value",message:{de:He==="empty"?`Feld '${P.key}' hat einen leeren Enum-Optionswert \u2014 das Steuerelement kann ihn nicht tragen. Der Option einen Wert geben oder sie streichen: Ein Feld, das unbeantwortet bleiben darf, bietet bereits eine eigene Zeile zum Leeren.`:`Feld '${P.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:He==="empty"?`Field '${P.key}' has an empty enum option value \u2014 the control cannot carry it. Give the option a value, or drop it: a field that may be left unanswered already offers its own clear row.`:`Field '${P.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(P.attachments??[]).forEach((Ee,ft)=>{if("storageId"in Ee){r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${P.key}' tr\xE4gt eine rohe 'storageId' \u2014 Anh\xE4nge nennen eine Bibliotheksdatei jetzt per 'fileKey' (plexus-cli files put, dann field attach --file-key).`,en:`Field '${P.key}' attachment carries a raw 'storageId' \u2014 attachments name a library file by 'fileKey' now (plexus-cli files put, then field attach --file-key).`}});return}let He=Ee.fileKey!==void 0&&Ee.fileKey!=="",vt=Ee.url!==void 0&&Ee.url!=="";He===vt&&r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${P.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${He&&vt?"beide":"keines"}).`,en:`Field '${P.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${He&&vt?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${U}.attachments[${ft}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${P.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${P.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");O.fields.forEach((P,U)=>K(P,`${N}.fields[${U}]`)),O.groups?.forEach((P,U)=>{P.fields.forEach((se,le)=>K(se,`${N}.groups[${U}].fields[${le}]`))}),O.repeated?.forEach((P,U)=>{P.itemTemplate.forEach((se,le)=>{let De=`${N}.repeated[${U}].itemTemplate[${le}]`;K(se,De),se.type==="consent"&&r.push({severity:"error",path:De,code:"config.consent-in-repeated",message:{de:`Feld '${se.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${se.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),O.subsections?.forEach((P,U)=>E(P,`${N}.subsections[${U}]`))}s(E,"visitFieldConfig"),e.sections.forEach((O,N)=>E(O,`sections[${N}]`)),e.effects.forEach((O,N)=>{if(O.kind==="person"){r.push(...Q0(O,e.effects,`effects[${N}]`,K=>l.has(K)));return}O.kind==="organization"&&O.nameFrom?.forEach((K,P)=>{l.has(K)||r.push({severity:"error",path:`effects[${N}].nameFrom[${P}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${O.id}': nameFrom verweist auf das unbekannte Feld '${K}'.`,en:`Effect '${O.id}' nameFrom references unknown field '${K}'.`}})})});let I=s((O,N)=>{if(O.kind!=="person"&&O.kind!=="organization")return;let K=O.display;if(!K){r.push({severity:"error",path:`${N}.display`,code:"display.missing",message:{de:`Effekt '${O.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${O.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}U0(K.icon)||r.push({severity:"error",path:`${N}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${O.id}': display.icon '${K.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${O.id}' display.icon '${K.icon}' is not a known bucket icon.`}}),G0(K.color)||r.push({severity:"error",path:`${N}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${O.id}': display.color '${K.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${O.id}' display.color '${K.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((O,N)=>I(O,`effects[${N}]`));let C=new Set,$=s(O=>{O.kind==="person"?C.add(O.bucket):O.kind==="organization"&&C.add(O.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach($);let b=new Set,R=s(O=>{for(let N of O)N.repeated?.forEach(K=>K.effects?.forEach(P=>$(P))),R(N.subsections??[])},"collectRepeatedBuckets");R(e.sections);let q=s((O,N)=>{C.size!==0&&O.forEach((K,P)=>{K.bucket===void 0||C.has(K.bucket)||r.push({severity:"error",path:`${N}[${P}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${K.key}' geh\xF6rt zum Bucket '${K.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${K.key}' belongs to bucket '${K.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),_=s((O,N)=>{if(b.has(O))return;b.add(O);let K=`sections[${N.join(".")}]`;q(O.fields,`${K}.fields`),O.groups?.forEach((P,U)=>q(P.fields,`${K}.groups[${U}].fields`)),O.repeated?.forEach((P,U)=>q(P.itemTemplate,`${K}.repeated[${U}].itemTemplate`)),O.subsections?.forEach((P,U)=>_(P,[...N,U]))},"visitBucketSection");e.sections.forEach((O,N)=>_(O,[N]));let J=e.effects.flatMap((O,N)=>O.kind==="person"&&O.subject===!0?[{e:O,i:N}]:[]);J.length>1&&J.slice(1).forEach(({e:O,i:N})=>{r.push({severity:"error",path:`effects[${N}].subject`,code:"subject.duplicate",message:{de:`Effekt '${O.id}' deklariert subject:true, aber '${J[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${O.id}' declares subject:true, but '${J[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((O,N)=>{if(!(O.kind!=="person"||O.nationalityFrom===void 0)){if(O.subject!==!0){r.push({severity:"error",path:`effects[${N}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${O.id}' deklariert nationalityFrom, ist aber nicht das Subjekt der Bewerbung \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`,en:`Effect '${O.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(O.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${N}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${O.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${O.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}O.nationalityFrom.forEach((K,P)=>{l.has(K)||r.push({severity:"error",path:`effects[${N}].nationalityFrom[${P}]`,code:"nationality.unknown-field",message:{de:`Effekt '${O.id}': nationalityFrom verweist auf das unbekannte Feld '${K}'.`,en:`Effect '${O.id}' nationalityFrom references unknown field '${K}'.`}})})}});let Y=e.effects.flatMap((O,N)=>O.kind==="person"&&O.contractParty!==void 0?[{e:O,i:N,decl:O.contractParty}]:[]);if(Y.length>0){let O=new Map;Y.forEach(({e:K,i:P})=>{let U=O.get(K.bucket);if(U===void 0){O.set(K.bucket,K.id);return}r.push({severity:"error",path:`effects[${P}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${K.id}' deklariert eine Vertragspartei auf Bucket '${K.bucket}', aber '${U}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${K.id}' declares a contract party on bucket '${K.bucket}', but '${U}' already does. A bucket is at most one contract party.`}})});let N=Y.filter(({decl:K})=>K.role==="beneficiary");N.slice(1).forEach(({e:K,i:P})=>{r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${K.id}' deklariert contractParty.role 'beneficiary', aber '${N[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${K.id}' declares contractParty.role 'beneficiary', but '${N[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),N.forEach(({e:K,i:P})=>{K.subject!==!0&&r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${K.id}' ist der Leistungsempf\xE4nger des Vertrags, aber nicht das Subjekt der Bewerbung. Leistungsempf\xE4nger und Subjekt der Bewerbung sind dieselbe Person \u2014 subject:true auf '${K.id}' setzen.`,en:`Effect '${K.id}' is the contract beneficiary but not the application subject. The beneficiary and the application subject are the same person \u2014 set subject:true on '${K.id}'.`}})}),J.forEach(({e:K,i:P})=>{let U=K.contractParty?.role;U!==void 0&&U!=="beneficiary"&&r.push({severity:"error",path:`effects[${P}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${K.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${U}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${K.id}' is the application subject but declares contractParty.role '${U}'. The application subject is the contract beneficiary.`}})}),Y.some(({decl:K})=>K.signs===!0)||r.push({severity:"error",path:"effects",code:"contractParty.no-signer",message:{de:"Das Formular deklariert Vertragsparteien, aber keine unterschreibt (contractParty.signs). Ein Vertrag ohne Unterzeichner kann nicht erzeugt werden.",en:"The form declares contract parties, but none signs (contractParty.signs). A contract without a signatory cannot be generated."}})}e.effects.forEach((O,N)=>{O.kind==="fieldMap"&&O.mappings.forEach((K,P)=>{a.has(K.from)||r.push({severity:"error",path:`effects[${N}].mappings[${P}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${O.id}': fieldMap from '${K.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${O.id}' fieldMap from '${K.from}' references unknown field.`}})})});for(let[O,N]of u){if(!N.sameAs)continue;let K=`fields[${O}].sameAs`,P=u.get(N.sameAs.source);P===void 0||N.sameAs.source===O?r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:N.sameAs.source===O?`Feld '${O}': sameAs.source verweist auf sich selbst.`:`Feld '${O}': sameAs.source verweist auf das unbekannte Feld '${N.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:N.sameAs.source===O?`Field '${O}' sameAs.source references itself.`:`Field '${O}' sameAs.source references unknown field '${N.sameAs.source}' (must be a top-level or group field).`}}):P.type!==N.type?r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}' (${N.type}): sameAs.source '${N.sameAs.source}' hat einen anderen Typ (${P.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${O}' (${N.type}) sameAs.source '${N.sameAs.source}' has a different type (${P.type}) \u2014 the mirror must be shape-identical.`}}):P.sameAs&&r.push({severity:"error",path:`${K}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${O}': sameAs.source '${N.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${O}' sameAs.source '${N.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let U=u.get(N.sameAs.toggle);(U===void 0||U.type!=="boolean")&&r.push({severity:"error",path:`${K}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:U===void 0?`Feld '${O}': sameAs.toggle verweist auf das unbekannte Feld '${N.sameAs.toggle}'.`:`Feld '${O}': sameAs.toggle '${N.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${U.type}').`,en:U===void 0?`Field '${O}' sameAs.toggle references unknown field '${N.sameAs.toggle}'.`:`Field '${O}' sameAs.toggle '${N.sameAs.toggle}' must be type 'boolean' (got '${U.type}').`}}),N.required===!0&&r.push({severity:"error",path:`fields[${O}].required`,code:"config.sameas-static-required",message:{de:`Feld '${O}' deklariert sameAs, ist aber statisch Pflicht \u2014 solange es gespiegelt ist, hat es keinen eigenen Wert, die Slice-Validierung beim Commit w\xFCrde immer scheitern. required: false + requiredIf: "${N.sameAs.toggle} != true" verwenden.`,en:`Field '${O}' declares sameAs but is statically required \u2014 while mirrored it holds no own value, so commit-time slice validation would always fail. Use required: false + requiredIf: "${N.sameAs.toggle} != true".`}})}{let O=new Map;e.effects.forEach(N=>O.set(N.id,N.kind)),e.effects.forEach((N,K)=>{if(N.kind!=="shareValue")return;[["from",N.from],["to",N.to]].forEach(([se,le])=>{let De=O.get(le.slice(1));De!==void 0&&De!=="person"&&De!=="organization"&&r.push({severity:"error",path:`effects[${K}].${se}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${N.id}': shareValue ${se} '${le}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${De}').`,en:`Effect '${N.id}' shareValue ${se} '${le}' must reference a person/organization effect (got '${De}').`}})});let P=N.from.slice(1);e.effects.some(se=>se.kind==="fieldMap"&&se.target.slice(1)===P&&se.mappings.some(le=>le.to===N.field)||se.kind==="shareValue"&&se.id!==N.id&&se.to.slice(1)===P&&se.field===N.field)||r.push({severity:"error",path:`effects[${K}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${N.id}' teilt das Feld '${N.field}' aus '${N.from}', aber kein fieldMap mit Ziel '${N.from}' bildet auf '${N.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${N.id}' shares field '${N.field}' from '${N.from}', but no fieldMap targeting '${N.from}' maps to '${N.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((O,N)=>{O.kind==="person"&&O.bucket.includes(jr)&&r.push({severity:"error",path:`effects[${N}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': bucket '${O.bucket}' darf '${jr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' bucket '${O.bucket}' must not contain '${jr}' (reserved for the per-row namespace).`}}),O.kind==="organization"&&O.orgKind.includes(jr)&&r.push({severity:"error",path:`effects[${N}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${O.id}': orgKind '${O.orgKind}' darf '${jr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${O.id}' orgKind '${O.orgKind}' must not contain '${jr}' (reserved for the per-row namespace).`}})});let ue=new Set;function Q(O,N){O.repeated?.forEach((K,P)=>{let U=K.effects??[];if(U.length>0){let se=`${N}.repeated[${P}]`,le=new Set(U.map(oe=>oe.id)),De=new Set(K.itemTemplate.map(oe=>oe.key)),Ee=(K.uniqueBy?.length??0)>0,ft=s(oe=>oe.startsWith("$item.")?De.has(oe.slice(6)):l.has(oe),"resolvesName"),He=s(oe=>oe.startsWith("$item.")?De.has(oe.slice(6)):a.has(oe),"resolvesFrom"),vt=s(oe=>{let Mt=oe.slice(1);return le.has(Mt)||h.has(Mt)},"resolvesRef");U.forEach((oe,Mt)=>{let pt=`${se}.effects[${Mt}]`;if(h.has(oe.id)||ue.has(oe.id)?r.push({severity:"error",path:pt,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${oe.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${oe.id}' is declared more than once.`}}):ue.add(oe.id),oe.kind==="person"||oe.kind==="organization"){I(oe,pt),oe.kind==="person"&&oe.subject===!0&&r.push({severity:"error",path:`${pt}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert subject:true \u2014 eine Zeile gilt je Zeile, das Subjekt der Bewerbung je Bewerbung. Das Subjekt an einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${oe.id}' declares subject:true \u2014 a repeated row is per-row, the application subject is per-application. Declare the subject on a top-level effect.`}}),oe.kind==="person"&&oe.nationalityFrom!==void 0&&r.push({severity:"error",path:`${pt}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${oe.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),oe.kind==="person"&&oe.contractParty!==void 0&&r.push({severity:"error",path:`${pt}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung deklariert contractParty \u2014 wer unterschreibt, wird einmal je Bewerbung deklariert, nicht je Zeile. An einem Effekt der obersten Ebene deklarieren.`,en:`Repeated effect '${oe.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ee||r.push({severity:"error",path:se,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${K.key}' hat einen Parteien erzeugenden Effekt '${oe.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${K.key}' has a party-creating effect '${oe.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Fe=oe.kind==="person"?oe.bucket:oe.orgKind;Fe.includes(jr)&&r.push({severity:"error",path:`${pt}.${oe.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${oe.id}' der Wiederholung: ${oe.kind==="person"?"bucket":"orgKind"} '${Fe}' darf '${jr}' nicht enthalten.`,en:`Repeated effect '${oe.id}' ${oe.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${jr}'.`}}),oe.kind==="person"&&r.push(...Q0(oe,U,pt,ft)),oe.kind==="organization"&&oe.nameFrom?.forEach((Be,In)=>{ft(Be)||r.push({severity:"error",path:`${pt}.nameFrom[${In}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${oe.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${oe.id}' nameFrom references unknown field '${Be}'.`}})}),oe.identity?.strategy==="keyed"&&oe.identity.keyFrom.forEach((Be,In)=>{He(Be)||r.push({severity:"error",path:`${pt}.identity.keyFrom[${In}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${oe.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${oe.id}' identity.keyFrom references unknown field '${Be}'.`}})})}else if(oe.kind==="relationship"){if([["from",oe.from],["to",oe.to]].forEach(([Fe,Be])=>{vt(Be)||r.push({severity:"error",path:`${pt}.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${oe.id}' der Wiederholung: ${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${oe.id}' ${Fe} references unknown effect '${Be}'.`}})}),oe.meta)for(let[Fe,Be]of Object.entries(oe.meta))typeof Be=="string"&&Be.startsWith("$")&&!vt(Be)&&r.push({severity:"error",path:`${pt}.meta.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${oe.id}' der Wiederholung: meta.${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${oe.id}' meta.${Fe} references unknown effect '${Be}'.`}})}else oe.kind==="fieldMap"?(vt(oe.target)||r.push({severity:"error",path:`${pt}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${oe.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${oe.target}'.`,en:`Repeated fieldMap '${oe.id}' target references unknown effect '${oe.target}'.`}}),oe.mappings.forEach((Fe,Be)=>{He(Fe.from)||r.push({severity:"error",path:`${pt}.mappings[${Be}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${oe.id}' der Wiederholung: from '${Fe.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${oe.id}' from '${Fe.from}' references unknown field.`}})})):oe.kind==="shareValue"&&r.push({severity:"error",path:pt,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${oe.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${oe.id}': shareValue is not supported inside repeated row effects.`}})})}}),O.subsections?.forEach((K,P)=>Q(K,`${N}.subsections[${P}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((O,N)=>Q(O,`sections[${N}]`));let re=_0(n.effects);return re.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${re.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${re.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...z5(e)),r}s(Z0,"validateForm");function z5(e){let t={...e,effects:e.effects.map(X0),sections:e.sections.map(eM),testScenarios:e.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return np(t,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:vw(n)}))}s(z5,"missingTranslationIssues");function X0(e){if(!("subject"in e))return e;let{subject:t,...n}=e;return n}s(X0,"withoutSubjectFlag");function eM(e){return{...e,repeated:e.repeated?.map(t=>({...t,effects:t.effects?.map(X0)})),subsections:e.subsections?.map(eM)}}s(eM,"withoutRowSubjectFlags");function W0(e,t){let n=e.reviewRequired;return n===void 0||n===!0?[]:[{severity:"error",path:t,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(n)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(n)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(W0,"reviewRequiredShapeIssues");function Y0(e,t){if(!e.export)return[];let n=[];return e.type==="docRef"&&n.push({severity:"error",path:t,code:"export.invalid-type",message:{de:`Feld '${e.key}' (docRef) kann nicht exportiert werden \u2014 ein Speicher-Handle ist kein bindbarer Dokumentwert.`,en:`Field '${e.key}' (docRef) cannot be exported \u2014 a storage handle is not a bindable document value.`}}),e.multiple===!0&&n.push({severity:"error",path:t,code:"export.multiple-enum",message:{de:`Feld '${e.key}' ist eine Mehrfachauswahl \u2014 N gew\xE4hlte Optionen sind kein einzelnes zusammengesetztes Blatt, deshalb nicht exportierbar.`,en:`Field '${e.key}' is a multi-select \u2014 N picked options are not one compound leaf, so it cannot be exported.`}}),n}s(Y0,"exportGateIssues");function Ea(e,t,n,r,i){e.has(t)?i.push({severity:"error",path:n,code:r,message:{de:`Mehrfach vergeben: ${H0(r,"de")} '${t}'`,en:`Duplicate ${H0(r,"en")}: '${t}'`}}):e.add(t)}s(Ea,"reportIfDup");function H0(e,t){let n=s((r,i)=>t==="de"?r:i,"label");switch(e){case"duplicate.section-id":return n("Abschnitts-ID","section id");case"duplicate.field-key":return n("Feldschl\xFCssel","field key");case"duplicate.effect-id":return n("Effekt-ID","effect id");case"duplicate.outcome-id":return n("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return n("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s(H0,"labelForCode");function Vv(e,t,n,r,i,o){e.visibleIf&&(xr(e.visibleIf,`${t}.visibleIf`,n,r,o),Ta(e.visibleIf,`${t}.visibleIf`,i,o)),e.requiredIf&&(xr(e.requiredIf,`${t}.requiredIf`,n,r,o),Ta(e.requiredIf,`${t}.requiredIf`,i,o)),e.disabledIf&&(xr(e.disabledIf,`${t}.disabledIf`,n,r,o),Ta(e.disabledIf,`${t}.disabledIf`,i,o)),e.defaultValue&&xr(e.defaultValue,`${t}.defaultValue`,n,r,o)}s(Vv,"checkFieldAsts");function Bv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Bv,"gatingMeta");function Ta(e,t,n,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(J0(o.left,o.right,o.op,t,n,r),J0(o.right,o.left,o.op,t,n,r)),i(o.left),i(o.right);return}case"unary":i(o.operand);return;case"if":i(o.cond),i(o.then),i(o.else);return;case"call":o.args.forEach(i);return;case"arr":o.items.forEach(i);return;default:return}}s(i,"walk"),i(e)}s(Ta,"checkGatingExpr");function J0(e,t,n,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&t.kind==="bool"&&t.value===!1){o.push({severity:"error",path:r,code:"expr.consent-compare-false",message:{de:`Gating-Ausdruck vergleicht die Zustimmung '${e.path}' mit false \u2014 eine Zustimmung ist true oder leer, nie false. '${e.path} != true' verwenden.`,en:`Gating expression compares the consent '${e.path}' to false \u2014 a consent is true or empty, never false. Use '${e.path} != true'.`}});return}a.isBoolean&&(a.hasDefault||t.kind!=="null"&&t.kind==="bool"&&(a.isYesNo&&n==="=="||o.push({severity:"error",path:r,code:"expr.gating-compare-undefaulted-field",message:{de:`Gating-Ausdruck vergleicht das Boolean-Feld '${e.path}' ohne Standardwert per '${n}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${n} ${t.value}' ${n==="=="?"false":"true"} \u2014 das Gate greift stillschweigend bei ungesetzten Werten. Dem Feld '${e.path}' einen 'defaultValue' geben (oder den Ausdruck umschreiben \u2014 z. B. '${e.path} != null' als ausdr\xFCckliche Gesetzt-Pr\xFCfung).`,en:`Gating expression compares undefaulted boolean field '${e.path}' to a bool literal via '${n}'. In three-valued logic, 'undefined ${n} ${t.value}' is ${n==="=="?"false":"true"} \u2014 the gate fires silently for unset values. Add a 'defaultValue' to field '${e.path}' (or rewrite the expression \u2014 e.g. '${e.path} != null' for an explicit set-check).`}})))}}s(J0,"inspectEqualityOperand");function xr(e,t,n,r,i){i.push(...fN(e,n.declaredContext,t)),i.push(...Zf(e,n.stageKeys,t));for(let o of It(e))n.known.has(o)||yw(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:t,code:"ref.unknown-ident",message:{de:o.startsWith("$")?`Bezeichner '${o}' ist kein Geltungsbereich, den ein Formular liest \u2014 Umgebungsvariablen sind '$env.<key>.<field>', Wiederholungszeilen '$item.*'.`:`Bezeichner '${o}' ist weder als Feld, berechneter Schl\xFCssel noch als $item-Slot deklariert.`,en:o.startsWith("$")?`Identifier '${o}' is no scope a form reads \u2014 environment variables are '$env.<key>.<field>', repeated rows '$item.*'.`:`Identifier '${o}' is not declared as a field, computed key, or $item slot.`}})}s(xr,"checkAst");function Q0(e,t,n,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${n}.nameFrom`,code:"person.name-from-removed",message:{de:`Effekt '${e.id}': eine Person hat kein nameFrom mehr \u2014 ihr Name ist die Feldzuordnung (fieldMap) auf ${vr.firstName} / ${vr.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${vr.firstName} / ${vr.lastName}. Remove nameFrom.`}});let o=K0(e.id,t);V0(o)||i.push({severity:"error",path:n,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${vr.firstName} oder ${vr.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${vr.firstName} or ${vr.lastName} \u2014 the person would get no name.`}});for(let a of j0(o))r(a)||i.push({severity:"error",path:n,code:"ref.unknown-name-field",message:{de:`Effekt '${e.id}': der Name wird aus '${a}' gelesen, das kein eingegebenes Feld ist.`,en:`Effect '${e.id}': its name is read from '${a}', which is not an entered field.`}});return i}s(Q0,"personNameIssues");function W5(e,t){let n=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&n.push({severity:"error",path:t,code:"config.consent-default",message:{de:`Feld '${e.key}' ist eine Zustimmung mit einem defaultValue \u2014 zustimmen muss die Familie selbst. Den defaultValue entfernen.`,en:`Field '${e.key}' is a consent with a defaultValue \u2014 the family must give it themselves. Remove the defaultValue.`}}),e.sameAs!==void 0&&n.push({severity:"error",path:t,code:"config.consent-computed",message:{de:`Feld '${e.key}' ist eine Zustimmung, die ein anderes Feld spiegelt (sameAs) \u2014 zustimmen muss die Familie selbst. sameAs entfernen.`,en:`Field '${e.key}' is a consent mirroring another field (sameAs) \u2014 the family must give it themselves. Remove sameAs.`}}),r||n.push({severity:"error",path:t,code:"config.consent-not-required",message:{de:`Feld '${e.key}' ist eine Zustimmung, die nie verlangt wird \u2014 required: true oder requiredIf setzen, sonst Typ 'boolean' verwenden.`,en:`Field '${e.key}' is a consent nobody is asked to give \u2014 set required: true or requiredIf, or use type 'boolean'.`}})),e.type==="boolean"&&r&&e.defaultValue?.trim()==="false"&&n.push({severity:"warning",path:t,code:"config.boolean-required-default-false",message:{de:`Feld '${e.key}' ist ein Ja/Nein-Pflichtfeld, vorbelegt mit Nein \u2014 es gilt von Anfang an als ausgef\xFCllt. Ist es eine Zustimmung, Typ 'consent' verwenden.`,en:`Field '${e.key}' is a required yes/no preset to No \u2014 it counts as answered from the start. If it is a consent, use type 'consent'.`}}),n}s(W5,"consentConfigIssues");function Y5(e,t){let n=e.exclusiveOptions;if(n===void 0)return[];let r=s((a,l)=>[{severity:"error",path:t,code:"config.exclusive-options",message:{de:a,en:l}}],"refuse");if(e.type!=="enum"||e.multiple!==!0)return r(`Feld '${e.key}' setzt exclusiveOptions ohne Mehrfachauswahl \u2014 exklusive Optionen gibt es nur bei type: 'enum' mit multiple: true.`,`Field '${e.key}' sets exclusiveOptions without a multi-select \u2014 exclusive options exist only on type: 'enum' with multiple: true.`);if(e.enumListKey!==void 0)return r(`Feld '${e.key}' setzt exclusiveOptions auf einer Liste des Mandanten (enumListKey) \u2014 exklusive Optionen brauchen eigene enumOptions.`,`Field '${e.key}' sets exclusiveOptions on a tenant list (enumListKey) \u2014 exclusive options need inline enumOptions.`);if(!Array.isArray(n)||n.length===0||n.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(n)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(n)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=n.filter(a=>!i.includes(a));return o.length>0?r(`Feld '${e.key}' nennt in exclusiveOptions ${o.map(a=>`'${a}'`).join(", ")} \u2014 keine Option des Feldes.`,`Field '${e.key}' names ${o.map(a=>`'${a}'`).join(", ")} in exclusiveOptions \u2014 not an option of the field.`):new Set(n).size!==n.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(Y5,"exclusiveOptionIssues");var H5="blocked";function tM(e,t){let n={values:t};for(let r of e.outcomes){let i;try{i=gt(r.when,n)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(J5(i))return r.id===H5?null:r.id}return null}s(tM,"resolveActiveOutcome");function J5(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(J5,"truthy");function nM(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(nM,"isScalar");function Q5(e,t,n){for(let[r,i]of Object.entries(e))if(i!==void 0){if(nM(i)){t[r]=i;continue}if(Array.isArray(i)){t[r]=i;continue}for(let[o,a]of Object.entries(i))nM(a)&&(t[`${r}.${o}`]=a)}Z5(e,t,n)}s(Q5,"mergeRecord");function Z5(e,t,n){let r=new Set(n);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);Wi(a).test(i)&&r.add(a)}for(let i of r){let o=qv(e,i),a=0;for(let l=0;l<o;l++)C0(e,i,l)&&a++;t[`${i}.count`]=a}}s(Z5,"mergeRepeatedCounts");function rM(e,t,n){let r={...n};return Q5(e,r,t),r}s(rM,"flattenValues");function Uv(e,t,n){return{code:e,fieldKey:t,text:n}}s(Uv,"submitIssue");function iM(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(iM,"truthyEval");function oM(e){if(e==null)return!0;if(typeof e=="string")return e.trim()==="";if(Array.isArray(e))return e.length===0;if(typeof e=="object"){let t=e;if("storageId"in t)return!(typeof t.storageId=="string"&&t.storageId.trim()!=="");let n=t;return!n.street?.trim()||!n.hausnr?.trim()||!n.plz?.trim()||!n.ort?.trim()||!n.land?.trim()}return!1}s(oM,"isEmptyValue");function X5(e,t,n){let r=!!e.required;if(!r&&e.requiredIf)try{r=iM(gt(e.requiredIf,{values:t}))}catch{r=!1}return r?e.requiredFor?n===null?!1:e.requiredFor.includes(n):!0:!1}s(X5,"fieldIsLiveRequired");function eQ(e,t,n){return sM(e,t,n).evalCtx}s(eQ,"buildSubmitEvalContext");function sM(e,t,n){let r=tQ(e),i=Object.keys(t).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[w,k]of Object.entries(t))(r(w)===null||o.has(w))&&(l[w]=k);let d=aM(e,l,n),c=new Set,u=new Set;dM(e,d,w=>c.add(w.key),w=>u.add(w.key));let p=new Set(i.filter(w=>{let k=r(w);return k.kind==="field"?c.has(w):u.has(k.repeatedKey)}));if(p.size===o.size&&[...p].every(w=>o.has(w))){let w={};for(let k of i)o.has(k)||(w[k]=t[k]);return{visible:l,hidden:w,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let w=i.filter(k=>p.has(k)!==o.has(k));F(`[smartForm] visibility of ${w.join(", ")} does not settle \u2014 each depends on whether the other's value counts. The form's visibleIf conditions are contradictory.`)}a.add(h),o=p}}s(sM,"splitWithContext");function tQ(e){let t=new Map,n=[];for(let r of Fm(e.sections)){for(let i of r.fields)t.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)t.set(o.key,o);for(let i of r.repeated??[])n.push({key:i.key,pattern:Wi(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=t.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of n){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(tQ,"fieldOwnership");function aM(e,t,n){let r=[];for(let o of Fm(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=rM(t,r,n);for(let o of Fm(e.sections))for(let a of o.computed??[])try{i[a.key]=gt(a.expression,{values:i})}catch{}return i}s(aM,"rawEvalContext");function lM(e,t,n){let{values:r,defaulted:i}=nQ(e,t,n),o=sM(e,r,n),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(lM,"splitDraftValues");function nQ(e,t,n,r){let i={...t},o=new Set,a=null;for(let l of Fm(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||t[d.key]!=null||r?.(d.key))continue;a??=aM(e,t,n);let c;try{c=gt(d.defaultValue,{values:a})}catch(u){F(`[smartForm] defaultValue of '${d.key}' does not evaluate: ${u instanceof Error?u.message:String(u)}`)}c!=null&&(i[d.key]=c,o.add(d.key))}return{values:i,defaulted:o}}s(nQ,"applyFieldDefaults");function Fm(e){let t=[],n=s(r=>{t.push(r);for(let i of r.subsections??[])n(i)},"walk");for(let r of e)n(r);return t}s(Fm,"walkSectionsDeep");function rQ(e,t,n,r=!1){if(oM(t))return null;let i=n.fields[e.type];i||F(`[fieldFormatIssue] no field provider registered for type "${e.type}" (field "${e.key}"). Register it in the domain form registry.`);let o=i.validate(e,t,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(rQ,"fieldFormatIssue");function iQ(e,t){return oM(t)||e.type==="consent"&&t!==!0}s(iQ,"isUnanswered");function Dm(e,t){if(!e)return!0;try{return iM(gt(e,{values:t}))}catch{return!1}}s(Dm,"isVisibleUnder");function dM(e,t,n,r){let i=s(o=>{if(Dm(o.visibleIf,t)){for(let a of o.fields)Dm(a.visibleIf,t)&&n(a);for(let a of o.groups??[])if(Dm(a.visibleIf,t))for(let l of a.fields)Dm(l.visibleIf,t)&&n(l);if(r!==void 0)for(let a of o.repeated??[])r(a);for(let a of o.subsections??[])i(a)}},"walk");for(let o of e.sections)i(o)}s(dM,"forEachVisibleField");function cM(e,t,n,r={}){let i=eQ(e,t,n),o=[],a=tM(e,i);a===null&&r.requireOutcome!==!1&&o.push(Uv("no-outcome",null,{de:"Die Angaben ergeben keinen g\xFCltigen Abschluss \u2014 bitte pr\xFCfen Sie das Formular.",en:"The answers do not lead to a valid outcome \u2014 please check the form."}));let l=new Set(r.exemptFromRequired??[]);return dM(e,i,d=>{let c=t[d.key];if(iQ(d,c)){!l.has(d.type)&&X5(d,i,a)&&o.push(Uv("required",d.key,hl([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=rQ(d,c,r.registry,r.testMode===!0);u!==null&&o.push(Uv("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(cM,"checkSubmittable");function uM(e){let t=e.testScenarios??[];if(t.length===0)return[];let{compiled:n}=ra(e),r=[];for(let i of t){let o=i.prefill??{};if(!aN(e,i.env))continue;let a=dN(e,i.env),{visible:l}=lM(n,o,a),d=cM(n,l,a,{exemptFromRequired:["docRef"]});for(let c of d.issues){if(c.code==="no-outcome"){r.push({severity:"error",path:`scenario:${i.id}`,code:"scenario.no-outcome",message:{de:`Szenario "${i.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`,en:`Scenario "${i.label.en}" reaches no valid outcome \u2013 the test case cannot be submitted.`}});continue}if(c.code==="required"){r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.required-field-unfilled",message:{de:`Szenario "${i.label.de}" l\xE4sst das Pflichtfeld ${c.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`,en:`Scenario "${i.label.en}" leaves the required field ${c.fieldKey} empty \u2013 no valid outcome.`}});continue}r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.invalid-value",message:hl([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(uM,"validateScenarios");function Lm(e){return e.filter(t=>(t.severity??"error")==="error")}s(Lm,"blockingIssues");function Mm(e,t={}){return[...Z0(e,t),...uM(e)]}s(Mm,"runFormValidators");function qm(e){return Lm(e)}s(qm,"blockingFormErrors");function fM(e,t,n){return vC(e,t,n)}s(fM,"runWorkflowValidators");function pM(e){return Lm(e)}s(pM,"blockingWorkflowErrors");var oQ=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],mM={join:{required:[],optional:[]},end:{required:[],optional:[]},eventTrigger:{required:[],optional:[]},form:{required:[],optional:["adoptForm","formExports"]},roleAssign:{required:[],optional:[]},setFlag:{required:[],optional:[]},if:{required:["condition"],optional:[]},countersign:{required:["contract"],optional:["signing","titles"]},engagePush:{required:["form"],optional:["contract","engage","payment"]},decision:{required:[],optional:["commentRequired","decisionAsTask","formView","reads","requiresOneOf"]},review:{required:[],optional:["commentRequired","decisionAsTask","form"]},waitlist:{required:[],optional:[]},completenessCheck:{required:["deadline","requires"],optional:[]},collectPayment:{required:[],optional:[]},governedDocument:{required:["approval","production","responseStrategy"],optional:["confirmBeforeIssue","confirmContractTerms","contractTermsQuestionText","form","generatorStamp","reads","responseLabels","templateStamp","titles"]}},fn={id:m.string(),label:Bi,actionTeams:m.optional(m.any()),artifacts:m.optional(m.any()),assign:m.optional(m.any()),inputs:m.optional(m.any()),library:m.optional(m.any()),next:m.optional(m.any()),notifications:m.optional(m.any()),optionalActions:m.optional(m.any()),outcomes:m.optional(m.any()),outputLabels:m.optional(m.any()),sublabel:m.optional(m.any()),tasks:m.optional(m.any())},sQ=m.object({...fn,type:m.literal("join")}),aQ=m.object({...fn,type:m.literal("end")}),lQ=m.object({...fn,type:m.literal("eventTrigger")}),dQ=m.object({...fn,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),cQ=m.object({...fn,type:m.literal("roleAssign")}),uQ=m.object({...fn,type:m.literal("setFlag")}),fQ=m.object({...fn,type:m.literal("if"),condition:m.optional(m.any())}),pQ=m.object({...fn,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),mQ=m.object({...fn,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),hQ=m.object({...fn,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),formView:m.optional(m.any())}),gQ=m.object({...fn,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),yQ=m.object({...fn,type:m.literal("waitlist")}),wQ=m.object({...fn,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),kQ=m.object({...fn,type:m.literal("collectPayment")}),bQ=m.object({...fn,type:m.literal("governedDocument"),approval:m.optional(m.any()),confirmBeforeIssue:m.optional(m.any()),confirmContractTerms:m.optional(m.any()),contractTermsQuestionText:m.optional(m.any()),form:m.optional(m.any()),generatorStamp:m.optional(m.any()),production:m.optional(m.any()),reads:m.optional(m.any()),responseLabels:m.optional(m.any()),responseStrategy:m.optional(m.any()),templateStamp:m.optional(m.any()),titles:m.optional(m.any())}),aLe=m.union(sQ,aQ,lQ,dQ,cQ,uQ,fQ,pQ,mQ,hQ,gQ,yQ,wQ,kQ,bQ);function hM(e){let t=[];return e.forEach((n,r)=>{if(n===null||typeof n!="object"||Array.isArray(n)){t.push(`graph.nodes[${r}]: a node must be an object`);return}let i=n,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&t.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in mM)){t.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=mM[a],d=new Set(["id","type","label",...oQ,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||t.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),t}s(hM,"workflowNodeEnvelopeIssues");function gM(e,t){return e.enumOptionLabels?.[t]??{de:t,en:t}}s(gM,"inlineEnumOptionLabel");var wM={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function kM(e){return wM[e]!==void 0}s(kM,"isExportableFieldType");function vQ(e){return e.exportType===void 0&&F(`formExports: computed '${e.key}' is exported without an exportType \u2014 the publish validator should have refused this form.`),{key:e.key,type:e.exportType,label:e.label??{de:e.key,en:e.key}}}s(vQ,"leafForComputed");function yM(e){let t=wM[e.type];return t===void 0&&F(`formExports: field '${e.key}' has type '${e.type}', which is not exportable \u2014 the publish validator should have refused this form.`),{key:e.key,type:t,label:e.label,...e.enumOptions!==void 0?{enumOptions:e.enumOptions.map(n=>({value:n,label:gM(e,n)}))}:{}}}s(yM,"leafFor");function Gv(e){let t=[],n=s(r=>{for(let i of r.fields)i.export===!0&&t.push(yM(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&t.push(yM(o));for(let i of r.computed??[])i.export===!0&&t.push(vQ(i));for(let i of r.subsections??[])n(i)},"visit");for(let r of e.sections)n(r);return t}s(Gv,"exportedFormLeaves");var bM=s(e=>e,"asEffectId"),Yi=s(e=>e,"asOutcomeId"),$a=s(e=>e,"asSectionId"),tn=s(e=>e,"asFieldKey");var Sr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Cd=["person","organization","relationship","fieldMap"],Hi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],Ra=["fresh","keyed","manual"];function Qo(e,t,n,r){if(e===void 0||e===""){if(t!==void 0&&t!=="")throw new Error(`${n}: ${r}-en needs ${r} too`);return}return st(e,t,n,r)}s(Qo,"optionalLocalizedText");function zt(e,t){if(!(e===void 0||e===""))try{Rt(e)}catch(n){throw new Error(`offer form: ${t} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}s(zt,"assertExpression");function Pd(e){return Object.keys(e.smartforms??{})}s(Pd,"carriedFormSlugs");function zv(e){let n=e.workflow?.graph?.nodes??[],r=[];for(let i of n){if(i.type!=="form")continue;let o=i.inputs?.smartForm;o?.kind==="literal"&&typeof o.value=="string"&&o.value&&r.push(o.value)}return r}s(zv,"boundFormSlugs");function Km(e,t){let n=Pd(e);if(t){if(!n.includes(t))throw new Error(`offer form: no smartform "${t}" in this bundle (have: ${n.join(", ")||"none"})`);return t}if(n.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new Error(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}s(Km,"resolveFormSlug");function jm(e,t){let n=e.smartforms?.[t];if(!n)throw new Error(`offer form: smartform "${t}" not found in bundle`);return n}s(jm,"getForm");function jn(e){let t=[],n=s(r=>{t.push(r),r.subsections?.forEach(i=>n(i))},"visit");return e.sections.forEach(n),t}s(jn,"walkSections");function or(e,t){return jn(e).find(n=>n.id===t)}s(or,"findSection");function Zo(e,t){for(let n of jn(e)){let r=n.fields.findIndex(i=>i.key===t);if(r>=0)return{section:n,field:n.fields[r],index:r}}}s(Zo,"findField");function Xo(e){let t=new Set;for(let n of jn(e))n.fields.forEach(r=>t.add(r.key)),n.groups?.forEach(r=>r.fields.forEach(i=>t.add(i.key))),n.repeated?.forEach(r=>r.itemTemplate.forEach(i=>t.add(i.key))),n.computed?.forEach(r=>t.add(r.key));return t}s(Xo,"allFieldKeys");function xQ(e){let t=st(e.label,e.labelEn,"offer form add"),n={id:$a("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Yi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:t,sections:[n],effects:[],outcomes:[r]}}s(xQ,"buildSkeletonSmartForm");function Vm(e,t){let{key:n,label:r}=t;if(Pd(e).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=xQ({key:n,label:r,...t.labelEn?{labelEn:t.labelEn}:{}});e.smartforms={...e.smartforms??{},[n]:i},e.index.smartforms={...e.index.smartforms??{},[n]:{}}}s(Vm,"addForm");function vM(e,t){if(!Pd(e).includes(t))throw new Error(`offer form rm: smartform "${t}" not found in bundle`);if(zv(e).includes(t))throw new Error(`offer form rm: smartform "${t}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[t],e.index.smartforms&&delete e.index.smartforms[t],t}s(vM,"removeForm");function xM(e,t){let n=jm(e,t.slug);if(t.label===void 0&&t.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(t.label==="")throw new Error("offer form set: --label cannot be empty");wt(n,"label",{de:t.label,en:t.labelEn},"offer form set")}s(xM,"setForm");function SM(e,t){let n=e.workflow?.graph?.nodes;if(!Array.isArray(n))throw new Error(`${t}: the bundle carries no workflow graph (workflow.json)`);return n}s(SM,"nodesOf");function AM(e,t,n){let r=SM(e,n),i=r.find(o=>o.id===t);if(i===void 0)throw new Error(`${n}: no node "${t}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(AM,"nodeOf");function EM(e){return e.flatMap(t=>{if(t.type!=="form"||kn(t))return[];let n=t.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?[{node:t,slug:n.value}]:[]})}s(EM,"creatingFormNodes");function TM(e){return qm(Mm(e)).map(t=>`[${t.code??"form"}] ${t.path?`${t.path}: `:""}${t.message.de}`)}s(TM,"formErrors");function Bm(e){let t="offer workflow restamp-exports",n=SM(e,t),r=[];for(let{node:i,slug:o}of EM(n)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${t}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=TM(l);if(d.length>0)throw new Error(`${t}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
|
|
11292
11292
|
${d.join(`
|
|
11293
11293
|
`)}`);let c=Gv(l),u=Array.isArray(i.formExports)?i.formExports.map(h=>h.key):null,p=i.formExports===void 0||Ne(i.formExports)!==Ne(c);i.formExports=c,r.push({node:i.id,form:o,before:u,after:c.map(h=>h.key),changed:p})}for(let i of n)if(i.type==="form"&&kn(i)&&"formExports"in i){let o=i.formExports?.map(a=>a.key)??null;delete i.formExports,r.push({node:i.id,form:"(adoptForm)",before:o,after:[],changed:!0})}return r}s(Bm,"restampFormExports");function $M(e){let t=e.workflow?.graph?.nodes??[];return EM(t).flatMap(({node:n,slug:r})=>{if(n.formExports===void 0)return[];let i=e.smartforms?.[r];if(i===void 0)return[];let o=i;return TM(o).length>0?[]:Ne(n.formExports)===Ne(Gv(o))?[]:[{node:n.id,form:r}]})}s($M,"staleFormExports");var Wv=["string","number","boolean","date"];function RM(e,t){let n="offer form field export";for(let r of jn(e)){let i=[...r.fields,...(r.groups??[]).flatMap(a=>a.fields)].find(a=>a.key===t.key);if(i!==void 0){if(t.type!==void 0)throw new Error(`${n}: --type is for a computed field; "${t.key}" is an entered ${i.type} field and exports as its own type`);if(t.on&&!kM(i.type))throw new Error(`${n}: "${t.key}" is a ${i.type} field \u2014 that type has no exported value (export.invalid-type)`);if(t.on&&i.multiple===!0)throw new Error(`${n}: "${t.key}" is a multi-select \u2014 N picked options are no single leaf (export.multiple-enum)`);let a=i.export===!0,l=i;return t.on?l.export=!0:delete l.export,{kind:"field",before:a,after:t.on}}let o=(r.computed??[]).find(a=>a.key===t.key);if(o!==void 0){let a=o.export===!0,l=o;if(!t.on){if(t.type!==void 0)throw new Error(`${n}: --type goes with an export, not with --off`);return delete l.export,delete l.exportType,{kind:"computed",before:a,after:!1}}let d=t.type??o.exportType;if(d===void 0)throw new Error(`${n}: "${t.key}" is a computed field \u2014 name its type with --type (${Wv.join("|")}); an expression has none to infer`);if(!Wv.includes(d))throw new Error(`${n}: --type "${d}" is no computed export type (${Wv.join("|")})`);return l.export=!0,l.exportType=d,{kind:"computed",before:a,after:!0}}if((r.repeated??[]).some(a=>a.itemTemplate.some(l=>l.key===t.key)))throw new Error(`${n}: "${t.key}" sits in a repeated block \u2014 a row value is no per-application leaf (export.in-repeated)`)}throw new Error(`${n}: the form has no field "${t.key}"`)}s(RM,"setFieldExport");function IM(e,t,n){let r="offer workflow node set-generator",i=AM(e,t,r);if(Om(i)!=="resolver")throw new Error(`${r}: "${t}" generates no contract from a generator (${i.type==="governedDocument"?`production ${String(i.production)}`:String(i.type)}) \u2014 a pin belongs on a governedDocument with production resolver`);let a=n.key.trim();if(a==="")throw new Error(`${r}: the ${n.kind} key is empty`);let l=Jr(i),d=l!==null&&l.key===a&&l.kind===n.kind&&l.revision===void 0,c=!d&&"generatorStamp"in i;c&&delete i.generatorStamp,i.inputs={...i.inputs??{},[jt]:{kind:"literal",value:{kind:n.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(p=>p!==jt&&p!==Pn);return{before:l,after:{key:a,kind:n.kind},droppedStamp:c,keptParameterCells:u}}s(IM,"setGeneratorPin");function OM(e,t,n){let r="offer workflow node set-cockpit-fields",i=AM(e,t,r),o=Om(i);if(o!=="resolver"&&o!=="template")throw new Error(`${r}: "${t}" fills no document from a generator or a Word template (${i.type==="governedDocument"?`production ${String(i.production)}`:String(i.type)})`);if(!(o==="resolver"?Jr(i)!==null:hr(i)!==null))throw new Error(o==="resolver"?`${r}: "${t}" names no generator yet \u2014 name one first (offer workflow node set-generator)`:`${r}: "${t}" names no Word template yet \u2014 name one first (inputs.documentTemplate)`);let l=new Set;for(let p of n){if(l.has(p))throw new Error(`${r}: --fields names "${p}" twice`);l.add(p)}let d={...i.inputs??{}},c=Object.keys(d).filter(p=>d[p]?.kind==="cockpit"),u=n.flatMap(p=>{let h=d[p];return h===void 0||h.kind==="cockpit"||h.kind==="unset"?[]:[{field:p,cell:h}]});for(let p of c)l.has(p)||delete d[p];for(let p of n)d[p]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...n],replaced:u}}s(OM,"setCockpitFields");var SQ=new Set(["graph","progressLayout","progressWiring"]);function _M(e){let{label:t,...n}=e;return n}s(_M,"definitionOf");function AQ(e){let t=[];for(let o of Object.keys(e))SQ.has(o)||t.push(`workflow.json: unknown key \`${o}\` \u2014 the file carries only graph, progressLayout, progressWiring. Delete the line.`);let n=e.graph;if(n===null||typeof n!="object"||Array.isArray(n))return t.push("workflow.json: `graph` must be an object."),t;for(let o of Object.keys(n)){if(cI.has(o))continue;let a=o==="id"||o==="label"?" (the title is the offer's, bundle.yaml `label`)":o==="dataFlow"?" (publish derives it)":"";t.push(`workflow.json: \`graph.${o}\` is no longer part of the workflow graph${a}. Delete the line.`)}let r=n;Array.isArray(r.nodes)?t.push(...hM(r.nodes).map(o=>`workflow.json: ${o}`)):t.push("workflow.json: `graph.nodes` must be a list."),r.assignmentRules===void 0&&t.push("workflow.json: `graph.assignmentRules` is required (who becomes responsible).");let i=e.progressWiring;return i!=null&&typeof i=="object"&&"layoutId"in i&&t.push("workflow.json: `progressWiring.layoutId` is no longer part of the wiring (the layout is the workflow's own). Delete the line."),t}s(AQ,"workflowShapeIssues");function NM(e){let t=e.nodes??[],n=new Map;for(let r of t){let i=XI(r);i!==void 0&&n.set(r.id,i)}return n}s(NM,"formNodeSlugById");function EQ(e,t){let n=e.smartforms??{},r=new Map;for(let[i,o]of NM(t)){let a=n[o];if(a===void 0)return;r.set(i,_M(a))}return kN(r)}s(EQ,"readinessContext");function TQ(e){return[...NM(e).values()]}s(TQ,"formNodeSlugs");function Um(e){let t=e.code?`[${e.code}] `:"",n=e.path?`${e.path}: `:"",r=e.reason??e.message;return`${t}${n}${r===void 0?JSON.stringify(e):r.de}`}s(Um,"describe");function Tn(e){let t=[];for(let l of cf(e.manifest))t.push({severity:"error",area:"manifest",message:l});let n=$t(e.index.label);(n==="not-localized"||n.length>0)&&t.push({severity:"error",area:"manifest",message:`[i18n/missingTranslation] bundle.yaml label fehlt in: ${n==="not-localized"?"de, en":n.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let{manifest:r,workflow:i}=e.index.slugs;i!==void 0&&i!==r&&t.push({severity:"error",area:"workflow",message:`slugs.workflow '${i}' must equal slugs.manifest '${r}' \u2014 the workflow belongs to the offer family, and export writes the family key`});for(let l of lm(e.index.program?.stages??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of um(e.index.program?.runs??[]))t.push({severity:"error",area:"program",message:l.message.de});for(let l of fm(e.index.program?.runs??[],e.index.program?.stages?.map(d=>d.key)))t.push({severity:"error",area:"program",message:l});if(e.workflow!==void 0){for(let A of AQ(e.workflow))t.push({severity:"error",area:"workflow",message:A});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let A of dI(d))t.push({severity:"error",area:"workflow",message:A});let u=[];for(let{node:A,key:E,kind:I}of _m(e))A.generatorStamp?.schemaDigest===void 0&&(u.push(A.id),t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${A.id}" pinnt ${I}:${E} ohne Stempel \u2014 ob er \u201Econtract\u201C oder \u201Econtracts\u201C liefert und welche Parameter er hat, pr\xFCft erst \`offer plan\` (stempelt den Pin von der Umgebung).`}));for(let A of l.nodes)A.type!=="governedDocument"||A.production!=="template"||A.templateStamp!==void 0||t.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${A.id}" f\xFCllt die Vorlage ${hr(A)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:A,form:E}of $M(e))t.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${A}": der Stempel formExports passt nicht mehr zum Formular "${E}" \u2014 die Adresspr\xFCfung liest den alten Stand; \`offer workflow restamp-exports\` stempelt ihn neu (publish tut es ohnehin).`});let p=e.index.program?.stages?.map(A=>A.key),h={...EQ(e,l),...p===void 0?{}:{stageKeys:new Set(p)}},w=s(A=>{let E=fM(A,{layout:d,wiring:c},h),I=new Set(pM(E));return{issues:E,isError:s(C=>I.has(C)||(C.severity??"error")==="error","isError")}},"blockingOf"),{issues:k,isError:y}=w(l),v=new Set;if(u.length>0){let A=structuredClone(l);for(let $ of A.nodes)u.includes($.id)&&($.generatorStamp={...$.generatorStamp??{},parts:[{partKey:"?"}]});let E=w(A),I=new Set(E.issues.filter(E.isError).map(Um)),C=s($=>u.some(b=>$.includes(`$node.${b}.contract`)),"namesOutput");for(let $ of k){let b=Um($);y($)&&!I.has(b)&&C(b)&&v.add(b)}}for(let A of k){let E=Um(A);if(v.has(E)){t.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${E}`});continue}t.push({severity:y(A)?"error":"warning",area:"workflow",message:E})}}let o=e.index.program?.stages,a=o===void 0?void 0:new Set(o.map(l=>l.key));for(let[l,d]of Object.entries(e.smartforms??{})){let c=$t(d.label);(c==="not-localized"||c.length>0)&&t.push({severity:"error",area:"smartform",message:`${l}: [i18n/missingTranslation] \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`});let u=_M(d);for(let k of uI(u,`smartforms/${l}.json`))t.push({severity:"error",area:"smartform",message:k.de});let p=u,h=Mm(p,{stageKeys:a}),w=new Set(qm(h));for(let k of h)t.push({severity:w.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${Um(k)}`});for(let k of[...O0(p),...I0(p)])t.push({severity:"error",area:"smartform",message:`${l}: [${k.code}] ${k.path}: ${k.message}`})}if(e.workflow!==void 0){let l=e.workflow.graph,d=new Set(TQ(l)),c=new Set(Object.keys(e.smartforms??{}));for(let u of d)c.has(u)||t.push({severity:"error",area:"consistency",message:`form node binds smartForm "${u}" but the bundle carries no smartforms/${u}.json`});for(let u of c)d.has(u)||t.push({severity:"warning",area:"consistency",message:`smartform "${u}" is carried but no form node binds it`})}return t}s(Tn,"validateBundle");async function Yv(e,t,n){let r=_m(n);if(r.length===0)return{rows:[],issues:[]};let i=[...new Map(r.map(({key:c,kind:u,revision:p})=>[`${u}:${c}:${p??"current"}`,{key:c,kind:u,...p===void 0?{}:{revision:p}}])).values()],o=await e.query(x.workflow.getResolverPinStamps,{client:t,unitKey:n.index.links?.unitKey??null,pins:i}).catch(c=>{throw c instanceof Error&&c.message.includes("Could not find public function")?new Error(`offer: ${e.convexUrl} has no workflow:getResolverPinStamps \u2014 that deployment is older than this CLI; release it first (or use a CLI of its release).`,{cause:c}):c}),a=new Map(o.map(c=>[`${c.kind}:${c.key}:${c.revision??"current"}`,c])),l=[],d=[];for(let{node:c,key:u,kind:p,revision:h}of r){let w=a.get(`${p}:${u}:${h??"current"}`);if(w===void 0)throw new Error(`offer: the environment answered no stamp for ${p}:${u}`);if(w.stamp===null){if(w.refusal===null)throw new Error(`offer: the environment answered neither a stamp nor a refusal for ${p}:${u}`);d.push({severity:"error",area:"workflow",message:`[resolver/pinRefused] Knoten "${c.id}": ${w.refusal.de}`});continue}lI(c,structuredClone(w.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:w.stamp.parts===void 0?`${p}:${u} Dokument`:`${p}:${u} kombiniert (${w.stamp.parts.map(k=>k.partKey).join(", ")})`})}return{rows:l,issues:d}}s(Yv,"stampResolverPins");async function Hv(e,t,n){let r=(n.workflow?.graph?.nodes??[]).filter(d=>d.type==="governedDocument"&&d.production==="template"),i=[...new Set(r.flatMap(d=>{let c=hr(d);return c===null?[]:[c]}))];if(i.length===0)return{rows:[],issues:[]};let o=new Map((await e.query(x.workflow.getTemplateStamps,{client:t,keys:i})).map(d=>[d.key,d])),a=[],l=[];for(let d of r){let c=hr(d);if(c===null)continue;let u=o.get(c);if(u===void 0)throw new Error(`offer: the environment answered nothing for template ${c}`);if(SL(d,u.parameters),u.parameters!==null){a.push({target:`stamp:${String(d.id)}`,detail:`template:${c} (${u.parameters.fields.length} Parameter)`});continue}l.push({severity:"error",area:"workflow",message:u.exists?`[governedDocument/templateWithoutParameters] Knoten "${String(d.id)}": die Vorlage ${c} deklariert keine Parameter (plexus-cli catalog apply, documentTemplates[].parameters).`:`[governedDocument/unknownTemplate] Knoten "${String(d.id)}": eine Vorlage ${c} gibt es in dieser Umgebung nicht.`})}return{rows:a,issues:l}}s(Hv,"stampTemplatePins");async function CM(e,t,n){let r=qe(n),i=await Yv(e,t,r),o=await Hv(e,t,r),a=[...i.rows,...o.rows],l=[...i.issues,...o.issues];if(l.length>0)return{rows:a,refused:l,open:[]};if(a.length===0)throw new Error("offer workflow restamp-pins: the bundle pins no contract generator or package (offer workflow node set-generator) and fills no Word template");An(r);let d=a.map(p=>p.target.slice(6)),c=s(p=>d.some(h=>p.includes(`nodes.${h}.`)||p.includes(`node.${h}.`)||p.includes(`"${h}"`)),"onStamped"),u=Tn(r).filter(p=>p.severity==="error"&&c(p.message));return{rows:a,refused:[],open:u}}s(CM,"restampPinsOnDisk");var $Q=z.join("contract","resolver-setup.json"),pi="resolver setup",Ia=s((e,t)=>Ct(e,t,pi),"record"),Ji=s((e,t)=>Ue(e,t,pi),"text");function RQ(e,t){let n=Ia(e,"Datei"),r=Ia(n.contractTemplate,"contractTemplate"),i=Ia(n.resolver,"resolver");return{dir:t,contractTemplate:{key:Ji(r.key,"contractTemplate.key"),name:un(r.name,"contractTemplate.name",pi,"Vorlagennamen"),file:Ji(r.file,"contractTemplate.file"),role:Ji(r.role,"contractTemplate.role")},revenueAccounts:Op(n.revenueAccounts,pi),billingItems:_p(n.billingItems,pi),resolver:{key:Ji(i.key,"resolver.key"),name:un(i.name,"resolver.name",pi,"Generatornamen"),description:i.description===void 0?null:un(i.description,"resolver.description",pi,"Beschreibungen"),legalText:i.legalText??{},source:Ji(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Dn(i.feeGroups,"resolver.feeGroups",pi)).map((o,a)=>{let l=Ia(o,`resolver.feeGroups[${a}]`);return{key:Ji(l.key,"feeGroup.key"),name:un(l.name,"feeGroup.name",pi,"Geb\xFChrengruppen"),billingItemKeys:Jv(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:Jv(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:Jv(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:IQ(i.scenarios??[]),config:Ia(i.config,"resolver.config")}}}s(RQ,"parseResolverSetup");function Jv(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||n.trim()==="")||new Set(e).size!==e.length)throw new Error(`generator setup: ${t} must be a list of unique keys.`);return e}s(Jv,"stringList");function IQ(e){if(!Array.isArray(e)||e.length>20)throw new Error("generator setup: scenarios must be a list of at most 20 reviewed examples.");return e.map(t=>{let n=Ia(t,"scenario");if(!("input"in n)||!("expected"in n))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Ji(n.key,"scenario.key"),input:n.input,expected:n.expected}})}s(IQ,"parseScenarios");function Gm(e){let t=z.resolve(e);return RQ(JSON.parse(he(t,"utf8")),z.dirname(t))}s(Gm,"readResolverSetup");function OQ(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!(r in n))throw new Error(`resolver setup: resolver.config.${t} existiert nicht.`);n=n[r]}return n}s(OQ,"configValue");function PM(e){let t=s(()=>Ji(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),n=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...Qv(e.resolver.config),...e.resolver.billingItemKeys])].filter(r=>!n.has(r)),billingItems:e.billingItems.map(r=>{if(r.programs!==void 0)throw new Error(`resolver setup: Artikel ${r.key}: "programs" verwaltet nur die Katalog-Datei (plexus-cli catalog), nicht resolver-setup.json.`);if("tree"in r.price)throw new Error(`resolver setup: Artikel ${r.key}: Tarife werden im Katalog verwaltet.`);let i=r.price.amount,o=typeof i=="object"&&i!==null&&typeof i.$config=="string"?OQ(e.resolver.config,i.$config):i;if(typeof o!="number"||!Number.isFinite(o))throw new Error(`resolver setup: Artikel ${r.key}: Preis ist keine Zahl (${JSON.stringify(i)}).`);return{key:r.key,name:r.name,itemType:r.itemType,revenueAccountCode:r.revenueAccount,taxTreatment:r.taxTreatment,config:r.config,price:{amount:o,currency:r.price.currency,effectiveFrom:t(),period:r.price.period}}})}}s(PM,"billingSetupPayload");function DM(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=Object.entries(e);if(t.length!==1||t[0][0]!=="$billingItem")return;let n=t[0][1];if(typeof n!="string")throw new Error(`resolver setup: $billingItem ${JSON.stringify(n)} ist kein Schl\xFCssel.`);return n}s(DM,"billingItemRef");function Qv(e){if(Array.isArray(e))return e.flatMap(Qv);if(typeof e!="object"||e===null)return[];let t=DM(e);return t!==void 0?[t]:Object.values(e).flatMap(Qv)}s(Qv,"billingItemRefs");function Zv(e,t,n={}){let r=s(i=>{if(Array.isArray(i))return i.map(r);if(typeof i=="object"&&i!==null){let o=Object.entries(i);if(o.length===1&&o[0][0]==="$grantTemplate"){let l=o[0][1];if(typeof l!="string"||n[l]===void 0)throw new Error(`generator setup: grant template ${String(l)} is not declared.`);return n[l]}let a=DM(i);if(a!==void 0){if(!(a in t))throw new Error(`resolver setup: $billingItem "${a}" ist weder in billingItems deklariert noch ein Katalogartikel.`);return t[a]}return Object.fromEntries(Object.entries(i).map(([l,d])=>[l,r(d)]))}return i},"walk");return r(e)}s(Zv,"renderResolverConfig");function _Q(e,t){let n=Array.isArray(e.documentPlaceholderKeys)?e.documentPlaceholderKeys:[],r=new Set(t.placeholders),i=new Set(n.map(String)),o=[...r].filter(l=>!i.has(l)),a=[...i].filter(l=>!r.has(l));if(o.length>0||a.length>0)throw new Error("resolver setup: resolver.config.documentPlaceholderKeys weicht vom DOCX ab"+(o.length>0?` \u2014 fehlt: ${o.join(", ")}`:"")+(a.length>0?` \u2014 nicht im DOCX: ${a.join(", ")}`:"")+". Liste aus dem DOCX \xFCbernehmen.")}s(_Q,"assertPlaceholderParity");function NQ(e,t){let n=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.versionNumber-r.versionNumber)[0];if(n!==void 0)return n.coverLetter===void 0&&n.source===t.source&&n.pinnedDocumentTemplateId===t.documentTemplateId&&Ne(n.config)===Ne(t.config)&&Ne(n.legalText)===Ne(t.legalText)&&Ne([...n.billingItemDefinitionIds].sort())===Ne([...t.billingItemDefinitionIds].sort())&&Ne([...n.grantTemplateIds].sort())===Ne([...t.grantTemplateIds].sort())&&Ne(n.feeGroups)===Ne(t.feeGroups)?n:void 0}s(NQ,"matchingSealedRevision");async function Dd(e,t,n){if(n.resolver.source===null)throw new Error("generator setup requires a self-contained source file.");let r=he(z.join(n.dir,n.resolver.source),"utf8"),i=await Wl(z.join(n.dir,n.contractTemplate.file));_Q(n.resolver.config,i);let o=await e.query(x.contractSetup.planBillingSetup,{client:t,...PM(n)}),a=await e.query(x.contractSetup.wordTemplateState,{client:t,configKey:n.contractTemplate.key}),l=a===null||a.sha256!==i.sha256,d=await e.query(x.contractConfig.model,{client:t}),c={};for(let E of n.resolver.grantTemplateKeys){let I=d.grantTemplates.find(C=>C.configKey===E);if(I===void 0)throw new Error(`Unknown grant template ${E}`);c[E]=I.id}let u=Zv(n.resolver.config,o.billingItemIds,c),h=(await e.query(x.contractGeneratorVersions.model,{client:t})).find(E=>E.definition.key===n.resolver.key),w=h?.currentRevisionId?await e.query(x.contractGeneratorVersions.detail,{client:t,id:h.currentRevisionId}):null,k=h?.revisions.find(E=>E.status==="draft"),y=k?await e.query(x.contractGeneratorVersions.detail,{client:t,id:k.id}):null,v=l||w===null?void 0:NQ([w],{source:r,config:u,legalText:n.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:n.resolver.billingItemKeys.map(E=>o.billingItemIds[E]??`not-created:${E}`),grantTemplateIds:Object.values(c),feeGroups:n.resolver.feeGroups.map(E=>({key:E.key,name:E.name,billingItemDefinitionIds:E.billingItemKeys.map(I=>o.billingItemIds[I]??`not-created:${I}`)}))}),A=o.rows.map(E=>({step:E.kind,target:E.key,action:E.action,detail:E.detail}));return A.push({step:"wordTemplate",target:n.contractTemplate.key,action:l?"create":"same",detail:z.basename(i.file)}),A.push({step:"generatorVersion",target:n.resolver.key,action:v?"same":"create",detail:v?`Current sealed revision ${v.versionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:A,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:h,current:w,draft:y,match:v,template:{documentTemplateId:a?.id??null,upload:l}}}s(Dd,"planResolverSetup");async function FM(e,t,n){let r=await Dd(e,t,n);if(r.rows.every(p=>p.action==="same"))return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};if(!r.match&&n.resolver.scenarios.length===0)throw new Error("A new generator revision requires reviewed scenarios.");let i=await e.mutation(x.contractSetup.applyBillingSetup,{client:t,...PM(n)});if(r.match)return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}};let o=r.template.upload?await Ip(e,t,r.docx,{name:n.contractTemplate.name,role:n.contractTemplate.role,configKey:n.contractTemplate.key}):r.template.documentTemplateId,a=r.draft?._id;if(a===void 0)if(r.head===void 0)a=(await e.mutation(x.contractGeneratorVersions.create,{client:t,key:n.resolver.key,name:n.resolver.name,description:n.resolver.description??{de:"",en:""}})).revisionId;else{if(r.current===null)throw new Error("Generator has neither draft nor sealed revision.");a=await e.mutation(x.contractGeneratorVersions.cloneDraft,{client:t,id:r.current._id})}let l=await e.query(x.contractGeneratorVersions.detail,{client:t,id:a}),d=await e.mutation(x.contractGeneratorVersions.save,{client:t,id:a,expectedSourceRevision:l.sourceRevision,config:Zv(n.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:n.resolver.legalText,documentTemplateId:o}),c=await e.action(x.contractGeneratorVersionActions.saveSource,{client:t,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:n.resolver.billingItemKeys.map(p=>i.billingItemIds[p]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:n.resolver.feeGroups.map(p=>({key:p.key,name:p.name,billingItemDefinitionIds:p.billingItemKeys.map(h=>i.billingItemIds[h])}))});if(c.diagnostics.length||c.sourceRevision===null||c.artifactHash===null)throw new Error(c.diagnostics.join(`
|
|
11294
11294
|
`));if(d=c.sourceRevision,await e.mutation(x.contractGeneratorVersions.approveScenarios,{client:t,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:Zv({scenarios:n.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(x.contractGeneratorVersions.seal,{client:t,id:a,expectedSourceRevision:d}),(await Dd(e,t,n)).match===void 0)throw new Error("The sealed revision does not match the declarative setup.");return{rows:r.rows,pin:{key:n.resolver.key,kind:"generator"}}}s(FM,"applyResolverSetup");async function Xv(e,t,n){let r=z.join(n.dir,$Q);if(!Ae(r)||n.workflow===void 0)return[];let i=Gm(r);if((await Dd(e,t,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(Xv,"pinSetupRevisions");function CQ(e){if(e.label===void 0)return;let t=e.label;if(typeof t!="object"||t===null||typeof t.de!="string"||typeof t.en!="string")throw new Error(`node "${e.id}": label ${JSON.stringify(e.label)} is not a { de, en } text`);return{de:t.de,en:t.en}}s(CQ,"nodeText");function Fd(e,t){let n=[],r=[],i=[],o={},a=t.progressEvents??[],l=CQ(e);for(let d of a){let c=`${e.id}.${d}`,u=t.progressDefaults?.[d];if(u===void 0)throw new Error(`node "${e.id}" (${e.type}) emits progress-event "${d}", but its node spec declares no progress default for it`);let p=e.type==="decision"&&d==="released"&&l!==void 0,h=p?l:u.label,w=u.tone,k={id:c,label:h,tone:w,external:u.external};u.terminal&&(k.terminal=!0),n.push(k),r.push({match:{nodeId:e.id},event:d,bus:"process",state:c});let y=u.phase,v=PQ(y,e.id),A=i.find(E=>E.id===v);if(A)A.states=[...A.states,c];else{let E={id:v,label:p?h:y.label,tone:w,states:[c]};y.track&&(E.track=y.track),y.defaultCollapsed&&(E.defaultCollapsed=!0),y.waitlist&&(E.waitlist=!0),i.push(E)}u.terminal&&(o[c]=u.terminal)}return{states:n,mappings:r,columns:i,terminalSemantics:o}}s(Fd,"deriveProgressEntriesForNode");function zm(e){return Object.entries(e).filter(([,t])=>t.outcome==="approved").map(([t])=>t)}s(zm,"seatedTerminalStates");function PQ(e,t){return e.scope==="global"?`col.${e.key}`:`${t}.${e.key}`}s(PQ,"columnIdFor");function LM(e,t){let n=s(i=>(i.states??[]).some(o=>t.terminalStateIds.has(o)),"isTerminal"),r=s(i=>{let o=t.columnNodeId(i);return(o!==void 0?t.nodeOrder.get(o):void 0)??Number.POSITIVE_INFINITY},"topoOf");return e.map((i,o)=>({c:i,idx:o,term:n(i)?1:0,topo:r(i)})).sort((i,o)=>i.term-o.term||i.topo-o.topo||i.idx-o.idx).map(i=>i.c)}s(LM,"orderProcessColumns");var sr=s((e,t)=>({de:e,en:t}),"lt"),tx=Ss("start",[]),Wm=Ss("form",[tx]),ex=Ss("end",[tx,Wm]);function DQ(e){let t=[Fd({id:Wm,type:"form",label:sr("Formular","Form")},Jo.form),Fd({id:ex,type:"end",label:sr("Ende","End")},Jo.end)],n=[],r=[],i=[],o={};for(let c of t){n.push(...c.states),i.push(...c.mappings),o={...o,...c.terminalSemantics};for(let u of c.columns){let p=r.find(h=>h.id===u.id);p?p.states=[...new Set([...p.states,...u.states])]:r.push(u)}}let a=zm(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:n,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:sr("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(DQ,"buildStarterProgress");function MM(e){let{slug:t,title:n,tenant:r,unit:i,responsible:o}=e,a=t,l=`${t}-form`,d=`${t}-flow`,c=[{id:tx,type:"eventTrigger",label:sr("Start","Start"),sublabel:sr("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:Wm}}},{id:Wm,type:"form",label:n,sublabel:sr("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:sr("Standard","Standard")}],next:{standard:{to:ex}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:ex,type:"end",label:sr("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:J_(Z_([{slot:"responsible",rules:[{when:ji,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Hf({nodes:c})))},{layout:p,wiring:h}=DQ(d),w={id:$a("section.applicant"),label:sr("Antragsteller","Applicant"),fields:[{key:tn("applicant.vorname"),label:sr("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:tn("applicant.nachname"),label:sr("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:Yi("standard"),label:sr("Standard","Standard"),when:"true",output:{fields:[{path:tn("applicant.vorname")},{path:tn("applicant.nachname")}],includeForm:!0}}],y={sections:[w],effects:[],outcomes:k},v={};return{index:{module:"admission",tenant:r,label:n,slugs:{manifest:a,workflow:a},smartforms:{[l]:{}},...i?{links:{unitKey:i}}:{}},manifest:v,smartforms:{[l]:{label:n,...y}},workflow:{graph:u,progressLayout:p,progressWiring:h}}}s(MM,"buildSkeletonBundle");var es={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function Pt(e,t,n){let i=(await e.query(x.workflow.listManifests,{client:t})).find(o=>o.offerKey===n);if(!i)throw new Error(`offer: no offer "${n}" in tenant "${t}"`);return i}s(Pt,"findOfferHandle");function nn(e,t,n){return e.query(x.programAdmin.getAngebotConfig,{client:t,offerKey:n,includeArchived:!0})}s(nn,"loadConfig");function nx(e,t){let n=e.units.find(r=>r.key===t);if(!n)throw new Error(`offer: unit "${t}" not found. Available keys: ${e.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return n.unitId}s(nx,"resolveUnitId");function Oa(e,t){let n=qM(e),r=e.runs.find(i=>i.key===fi(n,t));if(!r)throw new Error(`offer: run "${t}" not found. Available keys: ${e.runs.map(i=>CF(n,i.key)).join(", ")||"(none)"}`);return r.runId}s(Oa,"resolveRunId");function _a(e,t){let n=qM(e),r=e.stages.find(i=>i.key===Hb(n,t));if(!r)throw new Error(`offer: level "${t}" not found. Available keys: ${e.stages.map(i=>Kr(n,i.key)).join(", ")||"(none)"}`);return r.stageId}s(_a,"resolveStageId");function qM(e){if(e.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(qM,"requireProgramKey");async function rx(e,t,n,r){await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:t,unitId:r}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:t,offerKey:n,unitId:r})}s(rx,"linkUnit");function ts(e,t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<0)throw new Error(`offer: --${e} must be a non-negative integer`);return n}s(ts,"parsePositiveInt");var Na=s((e="Offer slug (required)")=>f.String("--offer",{description:e}),"offerOption"),ix=s(()=>f.String("--slug",{hidden:!0}),"retiredSlugOption");function ox(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new kt(`--offer "${e.offer}" and --slug "${e.retiredSlug}" name different offers \u2014 pass only --offer.`);return ot(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new kt("Missing --offer <slug>.");return e.offer}s(ox,"requireOffer");var Xe=class extends D{static{s(this,"OfferCommand")}offer=Na();retiredSlug=ix();#e;get offerSlug(){return this.#e??=ox(this),this.#e}};var Ld=class extends Xe{static{s(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=T.Usage({category:"Offer",description:"Pull an offer's published generation (manifest + smartforms + workflow + program) into a bundle; --draft pulls the draft"});offer=Na("Manifest slug to export (required)");out=f.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=yt();draft=f.Boolean("--draft",!1,{description:"Export the editable draft instead of the published generation (the live head, else the staged candidate)"});async execute(){let t=ek(this.out,this.force),n=await this.caller(),r=this.requireTenant(n),{bundle:i,generation:o,revision:a}=await y0(n,r,this.offerSlug,this.draft?"draft":"published");return An({...i,dir:t}),this.print({exported:`${r}/${this.offerSlug}`,generation:o,revision:a,dir:t},l=>[{key:"exported",value:l.exported},{key:"generation",value:`${l.generation} (revision ${l.revision})`},{key:"dir",value:l.dir}]),0}},Md=class extends ve{static{s(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=T.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});offer=Na("New offer slug (identity key) (required)");retiredSlug=ix();title=f.String("--title",{required:!0,description:"Bare offer title in German (= program/form label), e.g. 'Grundschule'. Do NOT include the run/year or levels \u2014 those are separate entities (program_runs.name / program_stages) shown alongside the offer, never composed into the label."});titleEn=f.String("--title-en",{required:!0,description:"The same title in English, e.g. 'Primary School' (every name a reader sees has both)"});tenant=f.String("--tenant",{required:!0,description:"Tenant slug (stamped on bundle.yaml)"});unit=f.String("--unit",{description:"Pedagogic unit (school) the portal resolves the offer through \u2014 its config key"});responsible=f.String("--responsible",{required:!0,description:"configKey of the staff member a self-service application goes to (the process slot\u2019s \u201Esonst\u201C row); a staff start goes to its creator"});template=f.String("--template","basic",{description:"Scaffold template (only 'basic')"});out=f.String("--out",{description:"Output directory (default: offers/<tenant>/<slug>; refused when not empty, unless --force)"});force=yt();async execute(){let t=ox(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let n=ek(this.out??z.join("offers",this.tenant,t),this.force),r=MM({slug:t,title:Gt({de:this.title,en:this.titleEn},"offer init",{de:"--title",en:"--title-en"}),tenant:this.tenant,responsible:this.responsible,template:"basic",...this.unit?{unit:this.unit}:{}});return An({...r,dir:n}),this.print({created:`${this.tenant}/${t}`,dir:n},i=>[{key:"created",value:i.created},{key:"dir",value:i.dir},{key:"next",value:`plexus offer validate --dir ${i.dir}`}]),0}},qd=class extends ve{static{s(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=T.Usage({category:"Offer",description:"Run the publish-gate validators locally against a bundle (no deployment)"});dir=f.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=qe(this.dir),n=Tn(t);return this.print(n,r=>r.length===0?[{severity:"ok",area:"-",message:"local validation clean"}]:r.map(i=>({severity:i.severity,area:i.area,message:i.message}))),n.some(r=>r.severity==="error")?1:0}},Kd=class extends D{static{s(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=T.Usage({category:"Offer",description:"Read-only: local validation (resolver pins stamped from the environment, as publish would) + remote\u2194local diff (create/change/same)"});dir=f.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=qe(this.dir),n=await this.caller(),{pins:r,stamps:i,issues:o}=await KM(n,t),a=await Lv(n,t);return this.print({validation:o,resolverPins:r,resolverStamps:i.rows,diff:a},()=>[...o.map(l=>({kind:`local:${l.severity}`,target:l.area,detail:l.message})),...r.map(l=>({kind:"=",target:l.target,detail:l.detail})),...i.rows.map(l=>({kind:"=",target:l.target,detail:l.detail})),{kind:es[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:es[d],target:`smartform:${l}`,detail:d})),{kind:es[a.workflow],target:"workflow",detail:a.workflow},...jM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...VM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...BM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...UM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},jd=class extends D{static{s(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=T.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=f.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let t=qe(this.dir),n=await this.caller(),r=await Xv(n,t.index.tenant,t),i=await Lv(n,t);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:es[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:es[a],target:`smartform:${o}`,status:a})),{icon:es[i.workflow],target:"workflow",status:i.workflow},...jM(i),...VM(i),...BM(i),...UM(i)]),0}};async function KM(e,t){let n=await Xv(e,t.index.tenant,t),r=await Yv(e,t.index.tenant,t),i=await Hv(e,t.index.tenant,t);return{pins:n,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Tn(t)]}}s(KM,"validateOnEnvironment");function jM(e){return e.addresses===null?[]:m0(e.addresses)}s(jM,"addressRows");function VM(e){let t={insert:"+",update:"~",archive:"-"};return e.stages.map(n=>({icon:t[n.op],target:`stage:${n.key}`,status:cm(n)}))}s(VM,"stageRows");function BM(e){return e.capacities.map(t=>({icon:"~",target:`cap:${t.run}\xD7${t.stageKey}`,status:pm(t)}))}s(BM,"capacityRows");function UM(e){if(e.publishPending===null)return[];let t=e.externalHeadRevision===null?"none":`v${e.externalHeadRevision}`;return[{icon:e.publishPending?"!":"=",target:"publish",status:e.publishPending?`pending (draft v${e.draftRevision} ahead of live ${t})`:`up to date (live ${t})`}]}s(UM,"publishPendingRows");var Vd=class extends D{static{s(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=T.Usage({category:"Offer",description:"Idempotent create/update; with --publish, release the draft when it differs from what is live"});dir=f.String("--dir",{required:!0,description:"Bundle directory"});publish=f.Boolean("--publish",!1,{description:"Release the draft when it says something the live generation does not"});stage=f.String("--stage","external",{description:"Publish stage: 'external' (default, goes live) or 'internal' (stage as the testable candidate only)"});async execute(){if(this.stage!=="internal"&&this.stage!=="external")throw new Error(`offer: --stage must be 'internal' or 'external' (got "${this.stage}")`);let t=qe(this.dir),n=await this.caller(),{pins:r,stamps:i,issues:o}=await KM(n,t);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
|
|
@@ -11469,6 +11469,6 @@ ${n.length} unusable ${o}:
|
|
|
11469
11469
|
`),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
|
|
11470
11470
|
`),i.length>0&&this.context.stdout.write(` ${i.length} without any login account \u2014 plexus-cli platform users provision --tenant <slug> --email <email> --name <name>
|
|
11471
11471
|
`)}else this.context.stdout.write(`No unusable identities.
|
|
11472
|
-
`);return n.length>0?1:0}},GE=class extends cr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let n=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function vV(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(vV,"requireOnOff");var xV=[RE,IE,OE,_E,NE,CE,PE,DE,FE,LE,ru,ME,qE,KE,jE,VE,BE,UE,GE];function SV(e){return e.de??e.en??Object.values(e)[0]??""}s(SV,"titleDe");function t9(e){return{id:e._id,kind:e.kind,status:e.status,title:SV(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(t9,"row");var n9=["id","kind","status","title","assignee","group","outcome"],YE=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=f.Boolean("--mine",!1,{description:"Only items assigned to me."});application=f.String("--application",{description:"Filter by application id."});group=f.String("--group",{description:"Filter by team (permission-group) id."});assignee=f.String("--assignee",{description:"Filter by assignee users._id."});openOnly=f.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(t9),n9),0}},HE=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:SV(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},JE=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=f.String("--title",{required:!0,description:"Task title."});description=f.String("--description",{description:"Task description."});application=f.String("--application",{description:"Link to an application id."});group=f.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=f.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},QE=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},ZE=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},AV=[YE,HE,JE,QE,ZE];var iu=[...NR,..._P,...VP,...UD,...BD,...gF,...SF,...xF,...kV,...xV,...wV,...ij,...cj,...hP,...fF,...aV,...OR,...iI,...eP,...TF,...EF,...IF,...OF,...cF,...JD,...AV,...XM,...Vq,...nj,...Bq,...Uj,...Zj,...uj,...bj,...Sj,...$j,...Ij,...tV,...uV,...YR];for(let e of iu){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:XT(e.usage.category,t.join(" "))})}var EV="0.1.156";function TV(){return iu.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=HT[so(n)];return{path:n,effect:ao(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(TV,"plexusCommandCatalog");import os from"node:path";function r9(e){let t=at()?.workspaceRoot??process.cwd(),n=os.resolve(t,e),r=os.relative(t,n);if(os.isAbsolute(e)||r===".."||r.startsWith(`..${os.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(r9,"workspacePath");function i9(e){let{absolute:t,relative:n}=r9(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of Rr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=os.join(o,a.name);if(a.isDirectory()?i(l):r.push(os.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return Ge(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Dt(os.dirname(t),{recursive:!0}),Ge(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return ds(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(i9,"plexusWorkspace");function $V(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=ml[n];if(!o||!Object.hasOwn(ml,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Gg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Gg[i.path],skillHash:Zu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return i9(i)},"executePlexusAgentTool")}s($V,"createPlexusAgentToolExecutor");var Oh=$V({inspectCommand:IV,executeCommand:OV});function _h(){let e=new ps({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:EV});e.register(Qa.HelpCommand),e.register(Qa.VersionCommand);for(let n of iu)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return a9(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(_h,"createPlexusCli");function a9(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&nl[n]===r&&ot(t,n,r),n in nl&&ao(n)==="confirm"&&!rl(e)&&t.write(`plexus-cli: \`${nl[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
|
|
11472
|
+
`);return n.length>0?1:0}},GE=class extends cr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=f.String({required:!0});async execute(){let n=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function vV(e,t){if(e===t)throw new Error("Pass exactly one of --on or --off.");return e}s(vV,"requireOnOff");var xV=[RE,IE,OE,_E,NE,CE,PE,DE,FE,LE,ru,ME,qE,KE,jE,VE,BE,UE,GE];function SV(e){return e.de??e.en??Object.values(e)[0]??""}s(SV,"titleDe");function t9(e){return{id:e._id,kind:e.kind,status:e.status,title:SV(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(t9,"row");var n9=["id","kind","status","title","assignee","group","outcome"],YE=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=f.Boolean("--mine",!1,{description:"Only items assigned to me."});application=f.String("--application",{description:"Filter by application id."});group=f.String("--group",{description:"Filter by team (permission-group) id."});assignee=f.String("--assignee",{description:"Filter by assignee users._id."});openOnly=f.Boolean("--open-only",!1,{description:"Only open items."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(t9),n9),0}},HE=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.query(x.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:SV(i.title)},{field:"assignee",value:i.assigneeUserId??""},{field:"group",value:i.queueGroupId??""},{field:"application",value:i.applicationId??""},{field:"node",value:i.nodeId??""},{field:"outcome",value:i.outcome??""}]),0}},JE=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=f.String("--title",{required:!0,description:"Task title."});description=f.String("--description",{description:"Task description."});application=f.String("--application",{description:"Link to an application id."});group=f.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=f.String("--assignee",{description:"Assignee users._id."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},QE=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=f.String({required:!0,name:"workItemId"});outcome=f.String("--outcome",{description:"Outcome id to record."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},ZE=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=f.String({required:!0,name:"workItemId"});user=f.String("--user",{description:"Assignee users._id (omit to clear)."});async execute(){let t=await this.caller(),n=this.requireTenant(t),r=await t.mutation(x.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},AV=[YE,HE,JE,QE,ZE];var iu=[...NR,..._P,...VP,...UD,...BD,...gF,...SF,...xF,...kV,...xV,...wV,...ij,...cj,...hP,...fF,...aV,...OR,...iI,...eP,...TF,...EF,...IF,...OF,...cF,...JD,...AV,...XM,...Vq,...nj,...Bq,...Uj,...Zj,...uj,...bj,...Sj,...$j,...Ij,...tV,...uV,...YR];for(let e of iu){let t=e.paths?.[0];t===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:XT(e.usage.category,t.join(" "))})}var EV="0.1.157";function TV(){return iu.flatMap(e=>(e.paths??[]).map(t=>{let n=t.join(" "),r=HT[so(n)];return{path:n,effect:ao(n),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,t)=>e.path.localeCompare(t.path))}s(TV,"plexusCommandCatalog");import os from"node:path";function r9(e){let t=at()?.workspaceRoot??process.cwd(),n=os.resolve(t,e),r=os.relative(t,n);if(os.isAbsolute(e)||r===".."||r.startsWith(`..${os.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:n,relative:r}}s(r9,"workspacePath");function i9(e){let{absolute:t,relative:n}=r9(e.path??".");if(e.operation==="list"){if(!Ae(t))return{files:[]};let r=[],i=s(o=>{for(let a of Rr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=os.join(o,a.name);if(a.isDirectory()?i(l):r.push(os.relative(t,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(t),{files:r.sort()}}if(!n)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(t);if(r.length>10*1024*1024)throw new Error("plexus: the workspace file exceeds 10 MB.");let i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(e.operation==="read"){let l=e.offset??0,d=e.maxChars??8e3,c=i.slice(l,l+d);return{path:n,content:c,...l||c.length<i.length?{offset:l,nextOffset:l+c.length<i.length?l+c.length:null,totalCharacters:i.length}:{}}}if(e.operation==="search"){if(!e.query)throw new Error("plexus: search needs a nonempty query.");let l=[],d=e.offset??0;for(;l.length<10;){let c=i.indexOf(e.query,d);if(c<0)break;l.push({offset:c,text:i.slice(Math.max(0,c-160),c+e.query.length+240)}),d=c+e.query.length}return{path:n,matches:l,nextOffset:l.length===10?d:null}}if(!e.oldText||typeof e.content!="string")throw new Error("plexus: edit needs oldText and replacement content.");let o=i.indexOf(e.oldText);if(o<0||o!==i.lastIndexOf(e.oldText))throw new Error("plexus: oldText must match exactly once. Read the current file and choose unique context.");let a=i.slice(0,o)+e.content+i.slice(o+e.oldText.length);if(Buffer.byteLength(a)>10*1024*1024)throw new Error("plexus: the edited file exceeds 10 MB.");return Ge(t,a,"utf8"),{path:n,sizeBytes:Buffer.byteLength(a)}}if(e.operation==="write"){if(typeof e.content!="string"||Buffer.byteLength(e.content)>1e6)throw new Error("plexus: file content is missing or too large.");return Dt(os.dirname(t),{recursive:!0}),Ge(t,e.content,"utf8"),{path:n,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return ds(t),{path:n,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(i9,"plexusWorkspace");function $V(e){return s(async function(n,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=ml[n];if(!o||!Object.hasOwn(ml,n))throw new Error("plexus: unknown agent tool.");if(Object.keys(i).some(a=>!Object.hasOwn(o.inputSchema.properties,a)))throw new Error("plexus: unexpected tool argument.");if(n==="plexus"){if(!Array.isArray(i.argv)||i.argv.some(a=>typeof a!="string")||i.stdin!==void 0&&typeof i.stdin!="string")throw new Error("plexus: invalid command input.");return e.inspectCommand(i.argv),e.executeCommand({argv:i.argv,...i.stdin===void 0?{}:{stdin:i.stdin}})}if(n==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Gg,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Gg[i.path],skillHash:Zu}}if(typeof i.operation!="string"||!["list","read","search","edit","write","remove"].includes(i.operation)||i.path!==void 0&&(typeof i.path!="string"||i.path.length>500)||i.content!==void 0&&(typeof i.content!="string"||i.content.length>1e6)||i.oldText!==void 0&&(typeof i.oldText!="string"||i.oldText.length>1e6)||i.query!==void 0&&(typeof i.query!="string"||!i.query.length||i.query.length>1e3)||i.offset!==void 0&&(typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)||i.maxChars!==void 0&&(typeof i.maxChars!="number"||!Number.isSafeInteger(i.maxChars)||i.maxChars<1||i.maxChars>24e3))throw new Error("plexus: invalid workspace input.");return i9(i)},"executePlexusAgentTool")}s($V,"createPlexusAgentToolExecutor");var Oh=$V({inspectCommand:IV,executeCommand:OV});function _h(){let e=new ps({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:EV});e.register(Qa.HelpCommand),e.register(Qa.VersionCommand);for(let n of iu)e.register(n);async function t(n,r){let i;try{i=e.process(n,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return a9(i,r.stderr??process.stderr),e.run(i,r)}return s(t,"run"),{process(n,r){return e.process(n,r)},run:t,async runExit(n,r){process.exitCode=await t(n,r)}}}s(_h,"createPlexusCli");function a9(e,t){let n=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&n!==r&&nl[n]===r&&ot(t,n,r),n in nl&&ao(n)==="confirm"&&!rl(e)&&t.write(`plexus-cli: \`${nl[n]}\` only prints its plan without --confirm \u2014 nothing was changed.
|
|
11473
11473
|
`)}s(a9,"noteRetiredPath");function IV(e){let t=_h().process(Va(e),{executePlexusAgentTool:Oh}),n=t.path.join(" ");if(n.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=TV().find(l=>l.path===n);if(!r){if(n===""||n==="--help"||n==="--version")return{path:n,writes:!1,host:"shared"};throw new Error(`plexus: command ${n} has no host classification.`)}let i=t,o=r.effect==="callKind"?tm(va(xa),i.fn??"",i.kind):void 0,a=qu(n,{confirm:rl(t),callKind:o});return{...r,writes:a}}s(IV,"inspectPlexusCommand");async function OV(e,t){if(t)return tT(t,()=>OV(e));if(!Array.isArray(e.argv)||e.argv.length===0||e.argv.length>128||e.argv.some(l=>typeof l!="string"||l.length>128e3)||(e.stdin?.length??0)>1e6)throw new Error("plexus: invalid command invocation.");let n="",r="",i=_h();if(at()){let l=IV(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(Va(e.argv),{executePlexusAgentTool:Oh,stdin:s9.from(e.stdin===void 0?[]:[e.stdin]),stdout:new RV({write(l,d,c){n+=String(l),c()}}),stderr:new RV({write(l,d,c){r+=String(l),c()}})}),stdout:n,stderr:r}}s(OV,"executePlexusCommand");sT({source:l9.join(import.meta.dirname,"skill")});_h().runExit(Va(process.argv.slice(2)),{executePlexusAgentTool:Oh});
|
|
11474
11474
|
//# sourceMappingURL=cli.mjs.map
|