@smartkomm/plexus-cli 0.1.224 → 0.1.226

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 CHANGED
@@ -6291,7 +6291,7 @@ plexus-cli --env prod platform notifications list --template account.loginLink -
6291
6291
  | Line | Means |
6292
6292
  | --- | --- |
6293
6293
  | \`abgelehnt: <reason> \u2014 Anmeldeseite\` / \`\u2014 Portal <slug>\` | a sign-in link was asked for and no mail went out, on the login page or that school's portal. \`unknownAddress\`: no account holds the address \u2014 usually a **typo**; look the person's real address up and compare. Login page only: \`platformAdmin\`, \`unprovenAddress\`, \`noSchoolWithOption\`. Portal only: \`noSchoolAccess\` (the account has no active access to that school). The page answered \u201ELink gesendet" every time \u2014 it never says which |
6294
- | \`Brief account.loginLink: sent \u2014 Relay: 250 \u2026 queued as <id>\` | our relay accepted the mail; the queue id finds it in the relay's log |
6294
+ | \`Benachrichtigung account.loginLink: sent \u2014 Relay: 250 \u2026 queued as <id>\` | our relay accepted the mail; the queue id finds it in the relay's log |
6295
6295
  | \`Sitzung von <ip> \u2014 <browser>\` | a sign-in happened. A session seconds after the letter from a foreign network is a **mail scanner** (Exchange Safe Links), not the person |
6296
6296
  | \`Passwort gesetzt (zuletzt)\` | the credential was last changed then \u2014 compare with the failed attempts |
6297
6297
 
@@ -11020,7 +11020,7 @@ plexus-cli --env prod jobs list --status running # nothing unexpectedly in
11020
11020
  ## Related
11021
11021
  - Command reference: \`plexus-cli jobs list --help\`, \`plexus-cli platform workers reap --help\`,
11022
11022
  \`plexus-cli platform imports cleanup-orphaned --help\`.
11023
- `};var bf="ca97e807cff892c009c5aef18aa52afc711b0b6a2645aa0ab2287d1d85d35302",Sy=kI;var Ay=class extends xe{static{s(this,"AgentToolsCommand")}static paths=[["agent","tools"]];static usage=$.Usage({category:"Agents",description:"Show the shared platform/CLI agent tool schemas and skill revision."});async execute(){return this.print({skillHash:bf,tools:$l}),0}},Ey=class extends xe{static{s(this,"AgentInvokeCommand")}static paths=[["agent","invoke"]];static usage=$.Usage({category:"Agents",description:"Invoke a shared agent tool; pipe its JSON input on stdin."});tool=f.String("--tool",{required:!0,description:"plexus|plexus_skill|plexus_workspace"});async execute(){if("isTTY"in this.context.stdin&&this.context.stdin.isTTY===!0)throw new Error("plexus: pipe the tool's JSON input on stdin.");let n=JSON.parse(await xy(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},bI=[Ay,Ey];var Ty=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],Qde=new Set(Ty.map(e=>e.key));var Ye=["de","en"];function Is(e,n){return Ye.every(t=>e[t]===n[t])}s(Is,"sameText");function In(e){if(e===null||typeof e!="object"||Array.isArray(e))return"not-localized";let n=e;return Object.keys(n).some(r=>!Ye.includes(r))?"not-localized":Ye.filter(r=>{let i=n[r];return typeof i!="string"||i.trim()===""})}s(In,"missingLocales");function Ci(e){let n=In(e);return n!=="not-localized"&&n.length===0}s(Ci,"isLocalizedText");function Rl(e,n){let t={};for(let r of Ye){let i=e.map(o=>o[r]);t[r]=i.every(o=>typeof o=="string"&&o.trim()!=="")?n(i,r):""}return t}s(Rl,"composeTexts");function vf(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(vf,"slugify");var vI="tenant";function xI(e){if(e.length===0||vf(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===vI)return`"${vI}" is reserved for the tenant-wide scope`}s(xI,"unitSlugError");var yW=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Qt(e,n){return`${e}-${n}`}s(Qt,"runStorageKey");function SI(e,n){typeof n!="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 t=`${e}-`;return(!n.startsWith(t)||n.length===t.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${n}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${t}<key>\u201C).`,en:`[run/foreignKey] The key "${n}" of the school year is not under the program "${e}" (expected: "${t}<key>").`}),n.slice(t.length)}s(SI,"bareRunKey");function xf(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=In(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?n.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&&n.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===""){n.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"||!yW.test(d)){n.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=t.get(d);if(c!==void 0){n.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}t.set(d,i)}),n}s(xf,"runSpecIssues");var wW="-stufe-",kW=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function $y(e){return`${e}${wW}`}s($y,"stageKeyPrefix");function Os(e,n){return`${$y(e)}${n}`}s(Os,"stageStorageKey");function EI(e,n){let t=$y(e);return n.startsWith(t)&&n.length>t.length}s(EI,"isUnderProgram");function Kr(e,n){let t=$y(e);return EI(e,n)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${n}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${t}<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 "${n}" is not under the program "${e}" (expected: "${t}<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.`}),n.slice(t.length)}s(Kr,"bareStageKey");function Sf(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=In(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?n.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&&n.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===""){n.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"||!kW.test(d)){n.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=t.get(d);if(c!==void 0){n.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}t.set(d,i)}),n}s(Sf,"stageSpecIssues");function AI(e){return{de:e.de.trim(),en:e.en.trim()}}s(AI,"trimmedText");function bW(e,n){let t=[];return e.de!==n.de&&t.push(`"${e.de}" \u2192 "${n.de}"`),e.en!==n.en&&t.push(`en "${e.en}" \u2192 "${n.en}"`),t.join(", ")}s(bW,"describeNameChange");function Af(e,n,t){if(e===null)return n.length>0&&F("planStageReconcile: stages exist but the offer has no program key"),t.map((a,l)=>({op:"insert",key:a.key,name:AI(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(n.map(a=>[a.key,a])),i=new Set,o=[];t.forEach(({name:a,...l},d)=>{let c={...l,name:AI(a)},u=Os(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={};Is(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[...n].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:EI(e,a.key)?Kr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Af,"planStageReconcile");function Ef(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let n=e.occupancy,t=[...n&&n.activeApplications>0?[`REFUSED: ${n.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...n&&n.openLeads>0?[`${n.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${t.length>0?` \u2014 ${t.join("; ")}`:""}`}case"update":{let n=[];if(e.unarchive&&n.push("restored"),e.changes.name&&n.push(bW(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[t,r]=e.changes.gradeLevel;n.push(`grade ${t??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&n.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${n.join(", ")})`}}}s(Ef,"describeStageStep");function Tf(e,n){return n.startsWith(e)&&n.length>e.length?n.slice(e.length):void 0}s(Tf,"bareUnder");function $I(e,n,t,r){let i=e.flatMap(w=>w.angebote).find(w=>w.offerKey===n);if(i===void 0){let w=e.flatMap(k=>k.angebote.map(y=>y.offerKey));throw new We(`applications start-test: no offer "${n}" (offers: ${w.join(", ")||"none"})`)}if(i.programKey===void 0)throw new We("applications start-test: the deployment does not serve the offer's program key \u2014 it runs an older release than the CLI; try again after the next release");let o=i.programKey;if(o===null)throw new We(`applications start-test: ${n} has no program yet \u2014 no level to start on`);let a=Os(o,""),l=Qt(o,""),d=s(w=>Tf(a,w)??"(no bundle key)","stageLabel"),c=s(w=>Tf(l,w)??"(no bundle key)","runLabel"),u=i.stages.find(w=>w.stageKey===Os(o,r)||w.stageId===r);if(u===void 0){let w=i.stages.map(b=>`${d(b.stageKey)} (${b.stageId})`).join(", "),k=Tf(a,r),y=k!==void 0&&i.stages.some(b=>b.stageKey===r)?` \u2014 "${r}" is the stored key; the export names it "${k}"`:"";throw new We(`applications start-test: no level "${r}" in ${n}${y} \u2014 name it by its bundle key or id: ${w}`)}let p=d(u.stageKey),h=u.runs.find(w=>w.runKey===Qt(o,t)||w.runId===t);if(h===void 0){let w=u.runs.map(b=>`${c(b.runKey)} (${b.runId})`).join(", "),k=Tf(l,t),y=k!==void 0&&u.runs.some(b=>b.runKey===t)?` \u2014 "${t}" is the stored key; the export names it "${k}"`:"";throw new We(`applications start-test: no school year "${t}" for level ${p}${y} \u2014 name it by its bundle key or id: ${w}`)}if(!h.isOpen)throw new We(`applications start-test: school year ${c(h.runKey)} is closed for level ${p}`);return{programRunId:h.runId,programStageId:u.stageId}}s($I,"resolveStartTarget");function vW(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(vW,"applicantText");function RI(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:vW(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(RI,"applicationRows");var TI=Ty.map(e=>e.email);function II(e,n,t,r){if(t===void 0&&r===void 0)throw new We("applications start-test: name the applicant \u2014 --party <partyId> or --applicant <email>");if(t!==void 0&&r!==void 0)throw new We("applications start-test: --party or --applicant, not both");if(ky(e,n)&&(r===void 0||!TI.includes(r.trim().toLowerCase())))throw new We(`applications start-test: on prod only for the test account ${TI.join(", ")} (--applicant) \u2014 never a real family's`)}s(II,"assertStartApplicant");function OI(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(OI,"processStoreJson");function xW(e){switch(e.kind){case"form":return`form ${e.formInstanceId} (${e.state})`;case"document":return e.file===null?`document ${e.slotKey} (leer)`:`document ${e.slotKey} \xB7 v${e.file.versionNumber} ${e.file.filename??e.file.artifactId}`;case"contract":return`contract ${e.contractId} \xB7 ${e.revision===null?"keine Fassung":`Fassung ${e.revision.snapshotNumber}`} \xB7 ${e.contractStatus}`;case"contracts":return e.contracts.map(n=>`${n.partKey}: contract ${n.contractId} \xB7 ${n.revision===null?"keine Fassung":`Fassung ${n.revision.snapshotNumber}`} \xB7 ${n.contractStatus}`).join("; ")}}s(xW,"refText");function SW(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?xW(e.ref):JSON.stringify(e.value)}s(SW,"holds");function _I(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:SW(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(_I,"storeRows");function $f(e){let n={},t={};for(let r of e){let i=r.indexOf("=");if(i<=0)throw new Error(`Expected key=value, got '${r}'.`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`'${o}' is given twice.`);let a=r.slice(i+1);t[o]=a;try{n[o]=JSON.parse(a)}catch{n[o]=a}}return{values:n,raw:t}}s($f,"parseKv");var PI="started",Rf="submitted",If="submitted",NI="load-scenario:";var CI="(Bewerbung)";function DI(e){return{nodeId:CI,actions:e.map(n=>({id:n.id,label:{de:`${n.label??n.id}${n.count===void 0?"":` (${n.count})`}`,en:`${n.label??n.id}${n.count===void 0?"":` (${n.count})`}`},...n.disabledReason===void 0?{}:{disabledReason:n.disabledReason}}))}}s(DI,"sharedAsList");function FI(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(FI,"disabledText");function LI(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:FI(r)})))}s(LI,"actionRows");function MI(e,n,t=[]){let r=e.filter(({actions:d})=>d.some(c=>c.id===n));if(r.length===0){let d=[...new Set(e.flatMap(({actions:c})=>c.map(u=>u.id)))];throw new Error(`test-actions run: no current node offers "${n}" (offered: ${d.join(", ")||"nothing"})`)}if(r.length>1)throw new Error(`test-actions run: "${n}" is offered by ${r.map(d=>d.nodeId).join(", ")} \u2014 pass --node`);let{nodeId:i,actions:o}=r[0],a=o.find(d=>d.id===n);if(a.disabledReason!==void 0)throw new Error(`test-actions run: "${n}" on ${i} is disabled: ${FI(a)}`);if(i!==CI)return i;let l=t[0];if(l===void 0)throw new Error(`test-actions run: "${n}" needs a current node \u2014 the application has none`);return l}s(MI,"nodeOfferingAction");function qI(e,n,t){if(e.startsWith(NI)){if(Object.hasOwn(t,"autoSubmit"))throw new Error(`test-actions run: ${e}: a scenario's autoSubmit is set by --auto-submit / --no-auto-submit, not --param`);return{autoSubmit:n,...t}}return Object.keys(t).length===0?void 0:{...t}}s(qI,"runParams");async function AW(e,n){let t=await e.query(x.workflow.getInstance,{applicationId:n});if(t===null)throw new Error(`test-actions: application ${n} has no workflow instance`);return t.instance.currentNodeIds}s(AW,"currentNodeIds");function EW(e,n){switch(n){case"notTestApplication":return`${e} is not a test application`;case"completed":case"aborted":case"deleted":return`${e} is ${n} \u2014 test actions run only on an active application`;case"missingPermission":return"the caller lacks bewerbungsmanagement.testActions.run"}}s(EW,"refusalText");async function Of(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${EW(n,r.reason)}`);let i=[];for(let o of t){let a=await e.query(x.workflow.listTestActions,{applicationId:n,nodeId:o});if(a===null)throw new Error(`test-actions: node "${o}" is not in this application's workflow (or it has no instance)`);i.push({nodeId:o,actions:a})}return[...i,DI(r.actions)]}s(Of,"actionsOf");async function KI(e,n,t){return t!==void 0?[t]:await AW(e,n)}s(KI,"nodesOf");var Ry=class extends C{static{s(this,"TestActionsListCommand")}static paths=[["test-actions","list"]];static usage=$.Usage({category:"Admission",description:"List the test-mode actions of the application's current node(s) (scenarios, auto-fill-files, submit, \u2026) and the application-wide ones"});application=f.String("--application",{required:!0,description:"Application id (a test application)"});node=f.String("--node",{description:"Node id (default: the application's current nodes)"});async execute(){let n=await this.caller(),t=await Of(n,this.application,await KI(n,this.application,this.node));return this.print(t,LI,["node","action","label","disabled"]),0}},Iy=class extends C{static{s(this,"TestActionsRunCommand")}application=f.String("--application",{required:!0,description:"Application id (a test application)"});node=f.String("--node",{description:"Node id (default: the application's current nodes)"});static paths=[["test-actions","run"]];static usage=$.Usage({category:"Admission",description:"Run one test-mode action; a scenario (load-scenario:<id>) also submits unless --no-auto-submit"});action=f.String("--action",{required:!0,description:"Action id, e.g. load-scenario:standard, auto-fill-files, submit-form"});autoSubmit=f.Boolean("--auto-submit",!0,{description:"Scenario only: stub the file fields and submit after loading (default on; --no-auto-submit only loads)"});param=f.Array("--param",{description:"Action parameter key=value (repeatable; the value is JSON where it parses, else text), e.g. --param confirmed=true for an action that asks a question first (its `confirm` in `test-actions list`)"});async execute(){let n=qI(this.action,this.autoSubmit,$f(this.param??[]).values),t=await this.caller(),r=this.application,i=await KI(t,this.application,this.node),o=MI(await Of(t,r,i),this.action,i);return await t.mutation(x.workflow.runTestAction,{applicationId:r,nodeId:o,actionId:this.action,...n===void 0?{}:{params:n}}),this.print({ran:this.action,on:o},a=>[{key:"ran",value:a.ran},{key:"on",value:a.on},{key:"next",value:"test-actions list \u2014 file fills and the submit after them run asynchronously"}]),0}},jI=[Ry,Iy];var kr=/^[a-z][A-Za-z0-9]*$/;function Oy(e){return typeof e=="string"&&kr.test(e)}s(Oy,"isNodeId");function _s(e,n){Oy(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${kr.source}.`);let t=new Set(n);if(!t.has(e))return e;let r=2;for(;t.has(`${e}${r}`);)r++;return`${e}${r}`}s(_s,"makeNodeId");var Fi="$env";function de(e){if(e.scope==="env")return`${Fi}.${e.key}`;let n=`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(de,"formatAddress");var Di=/^[a-z][a-zA-Z0-9_]*$/,TW=/^[A-Za-z_][A-Za-z0-9_]*$/;function bo(e){return typeof e=="string"&&e.split(".").every(n=>TW.test(n))}s(bo,"isPath");function ti(e){if(!e.startsWith("$"))return null;let n=e.slice(1).split("."),[t,...r]=n;switch(t){case"env":{let i=r.join(".");return r.length>0&&bo(i)?{scope:"env",key:i}:null}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Di.test(o)||(t==="node"?!kr.test(i):!Di.test(i))?null:$W({scope:t,owner:i,key:o},a)}default:return null}}s(ti,"tryParseAddress");function $W(e,n){if(n.length===0)return e;let t=n.join(".");return bo(t)?{...e,path:t}:null}s($W,"withPath");function we(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=n.scope==="env"?["scope","key"]:["scope","owner","key","path"];if(Object.keys(n).some(r=>!t.includes(r))||n.path!==void 0&&!bo(n.path))return!1;switch(n.scope){case"env":return bo(n.key);case"node":return typeof n.owner=="string"&&kr.test(n.owner)&&typeof n.key=="string"&&Di.test(n.key);case"task":return typeof n.owner=="string"&&Di.test(n.owner)&&typeof n.key=="string"&&Di.test(n.key);default:return!1}}s(we,"isAddress");var ri={offer:{key:"string",title:"string"},unit:{key:"string",name:"string"},stage:{key:"string",name:"string",gradeLevel:"number"},run:{key:"string",name:"string",startDate:"date"},applicant:{language:"enum",channel:"enum"}},Ps=Object.keys(ri);function Ns(e){return Object.hasOwn(ri,e)}s(Ns,"isEnvKey");var RW=["self-service","staff"];function VI(e,n){return{kind:"fixed",values:e,labels:n}}s(VI,"fixedSet");var _f={of:"applicant.language",withoutValue:"de"},ii={"offer.key":{valueSet:{kind:"live"},nullable:!1,label:{de:"Angebot",en:"Offer"}},"offer.title":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Titel des Angebots",en:"Offer title"},nameLanguage:_f},"unit.key":{valueSet:{kind:"live"},nullable:!1,label:{de:"Einheit",en:"Unit"}},"unit.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name der Einheit",en:"Unit name"},nameLanguage:_f},"stage.key":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Klassenstufe (Schl\xFCssel)",en:"Grade (key)"},cohortBound:!0},"stage.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name der Klassenstufe",en:"Grade name"},cohortBound:!0,nameLanguage:_f},"stage.gradeLevel":{valueSet:{kind:"open"},nullable:!0,absent:{de:"Die Stufe hat keine Klassenstufe (Kindergarten).",en:"The stage has no grade level (Kindergarten)."},label:{de:"Klassenstufe",en:"Grade level"},cohortBound:!0},"run.key":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Schuljahr",en:"School year"},cohortBound:!0},"run.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name des Schuljahrs",en:"School year name"},cohortBound:!0,nameLanguage:_f},"run.startDate":{valueSet:{kind:"open"},nullable:!0,absent:{de:"F\xFCr das Schuljahr ist kein Beginn erfasst.",en:"The school year has no start date."},label:{de:"Beginn des Schuljahrs",en:"School year start"},cohortBound:!0},"applicant.language":{valueSet:VI(Ye,{de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}}),nullable:!0,absent:{de:"Die Bewerbung hat kein Bewerberkonto (intern angelegt).",en:"The application has no applicant account (started by staff)."},label:{de:"Bewerbersprache",en:"Applicant language"}},"applicant.channel":{valueSet:VI(RW,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},Pf={types:ri,fields:ii},Nf=Ps.flatMap(e=>Object.keys(ri[e]).map(n=>`${e}.${n}`));function Zt(e){return Object.hasOwn(ii,e)}s(Zt,"isEnvLeaf");function Cf(e){return`${Fi}.${e}`}s(Cf,"envIdentifier");function vo(e){let n=ii[e],[t,r]=e.split("."),i=ri[t][r];i===void 0&&F(`[env] leaf "${e}" has no type`);let o=n.valueSet;return{leaf:e,type:i,label:n.label,nullable:n.nullable,...n.absent===void 0?{}:{absent:n.absent},...n.nameLanguage===void 0?{}:{nameLanguage:n.nameLanguage},...n.cohortBound===void 0?{}:{cohortBound:n.cohortBound},...o.kind==="fixed"?{enumOptions:o.values.map(a=>{let l=o.labels[a];return l===void 0&&F(`[env] "${e}" names the value "${a}" without a label`),{value:a,label:l}})}:{}}}s(vo,"envLeaf");var BI="staffInput";var IW=["boolean"],Il=/^[a-z][A-Za-z0-9]*$/;function Df(e){return e.staffInputs??[]}s(Df,"staffInputsOf");function Ff(e){return`${BI}.${e}`}s(Ff,"staffInputLeaf");function UI(e){return`${Fi}.${Ff(e)}`}s(UI,"staffInputIdentifier");function OW(e){let n=`${BI}.`;return e.startsWith(n)?e.slice(n.length):null}s(OW,"staffInputKeyOfLeaf");function Cs(e,n){let t=OW(n);return t===null?void 0:Df(e).find(r=>r.key===t)}s(Cs,"declaredStaffInput");function GI(e){return[...Df(e).map(n=>({leaf:Ff(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...Nf.map(n=>{let t=vo(n);return{leaf:n,type:t.type,label:t.label,valueSet:ii[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(GI,"envLeavesFor");function zI(e){return GI(e).filter(n=>!n.cohortBound)}s(zI,"conditionEnvLeaves");function WI(e){return HI(zI(e))}s(WI,"envConditionSchemaFor");function _W(e){return GI(e).map(n=>n.leaf==="stage.key"?{...n,valueSet:{kind:"open"}}:n)}s(_W,"offerConditionEnvLeaves");function YI(e){return HI(_W(e))}s(YI,"offerConditionSchemaFor");function HI(e){let n={},t={};for(let{leaf:r,type:i,valueSet:o,nullable:a}of e){let[l="",d=""]=r.split(".");n[l]={...n[l]??{},[d]:i},t[r]={valueSet:o,nullable:a}}return{types:n,fields:t}}s(HI,"schemaOfLeaves");function JI(e){let n=e.staffInputs;if(n===void 0)return[];if(!Array.isArray(n))return[{path:"staffInputs",reason:{de:"[staffInput/shape] graph.staffInputs muss eine Liste sein.",en:"[staffInput/shape] graph.staffInputs must be a list."}}];let t=[],r=new Set;return n.forEach((i,o)=>{let a=`staffInputs[${o}]`,l=i;if(l===null||typeof l!="object"||typeof l.key!="string"){t.push({path:a,reason:{de:"[staffInput/shape] Eine interne Angabe braucht key, type und label ({ de, en }).",en:"[staffInput/shape] An internal entry needs key, type and label ({ de, en })."}});return}let d={de:`Interne Angabe "${l.key}"`,en:`Internal entry "${l.key}"`};Il.test(l.key)||t.push({path:`${a}.key`,reason:{de:`[staffInput/keyFormat] ${d.de}: Schl\xFCssel beginnt mit einem Kleinbuchstaben und enth\xE4lt nur Buchstaben und Ziffern.`,en:`[staffInput/keyFormat] ${d.en}: the key starts with a lowercase letter and contains only letters and digits.`}}),r.has(l.key)&&t.push({path:`${a}.key`,reason:{de:`[staffInput/duplicateKey] ${d.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[staffInput/duplicateKey] ${d.en}: the key is used twice.`}}),r.add(l.key),IW.includes(l.type)||t.push({path:`${a}.type`,reason:{de:`[staffInput/unknownType] ${d.de}: Typ "${String(l.type)}" \u2014 erlaubt ist nur "boolean" (K\xE4stchen).`,en:`[staffInput/unknownType] ${d.en}: type "${String(l.type)}" \u2014 only "boolean" (checkbox) is allowed.`}});let c=In(l.label);c==="not-localized"?t.push({path:`${a}.label`,reason:{de:`[staffInput/shape] ${d.de}: label muss { de, en } sein.`,en:`[staffInput/shape] ${d.en}: label must be { de, en }.`}}):c.length>0&&t.push({path:`${a}.label`,reason:{de:`[i18n/missingTranslation] ${d.de}: Beschriftung fehlt in ${c.join(", ")}.`,en:`[i18n/missingTranslation] ${d.en}: label is missing in ${c.join(", ")}.`}})}),t}s(JI,"staffInputIssues");var Ky={required:!0,description:"Offer slug (its offerKey)"},_y=class extends C{static{s(this,"ApplicationsListCommand")}static paths=[["applications","list"]];static usage=$.Usage({category:"Admission",description:"List an offer's applications (id, status, board state, applicant, test)"});offer=f.String("--offer",Ky);testOnly=f.Boolean("--test-only",!1,{description:"Only test applications"});async execute(){let n=await this.caller(),t=await n.query(x.admission.listForAngebot,{client:this.requireTenant(n),offerKey:this.offer}),r=RI(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},Py=class extends C{static{s(this,"ApplicationsCountsCommand")}static paths=[["applications","counts"]];static usage=$.Usage({category:"Admission",description:"Count an offer's applications per list"});offer=f.String("--offer",Ky);async execute(){let n=await this.caller(),t=await n.query(x.admission.getCountsByListForAngebot,{client:this.requireTenant(n),offerKey:this.offer});return this.print(t,r=>[...Object.entries(r.counts).map(([i,o])=>({list:i,count:String(o)})),{list:"total",count:String(r.total)}],["list","count"]),0}},Ny=class extends C{static{s(this,"ApplicationsShowCommand")}static paths=[["applications","show"]];static usage=$.Usage({category:"Admission",description:"One application: status, test flag, offer, current workflow nodes"});application=f.String({required:!0});async execute(){let n=await this.caller(),t=this.application,r=await n.query(x.admission.get,{applicationId:t});if(r===null)throw new We(`applications show: no application ${t} (or not visible to you)`);let i=await n.query(x.workflow.getInstance,{applicationId:t});return this.print({application:r,currentNodes:i?.instance.currentNodeIds??[]},o=>[{key:"id",value:t},{key:"status",value:o.application.status},{key:"test",value:o.application.testMode?"ja":"nein"},{key:"offer",value:o.application.offerId},{key:"current nodes",value:o.currentNodes.join(", ")}]),0}},Cy=class extends C{static{s(this,"ApplicationsStoreCommand")}static paths=[["applications","store"]];static usage=$.Usage({category:"Admission",description:"One application's process store: every address of its pinned graph, resolved (present / pending / absent)",details:"Staff only (applications.manage). --json prints one object keyed by the canonical address ($node\u2026, $task\u2026, $env\u2026). Values are shown whatever their audience \u2014 never hand the output to the family. Recipe: playbooks/applications/inspect-process-store.md."});application=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.processStoreView.get,{applicationId:this.application});return this.print(OI(t),()=>_I(t),["address","state","holds","producer","written"]),0}},Dy=class extends C{static{s(this,"ApplicationsStartTestCommand")}static paths=[["applications","start-test"]];static usage=$.Usage({category:"Admission",description:"Start a TEST application for an applicant (school year and level by key or id) and show what test mode offers next",details:"Always test mode. --applicant names the account by its login address (on prod only the tenant's test account); --party names the applicant party directly. Without --version it runs on the live generation, like the cockpit."});offer=f.String("--offer",Ky);run=f.String("--run",{required:!0,description:"School year: its bundle key as offer export shows it (program.runs[].key) or id \u2014 never its name"});stage=f.String("--stage",{required:!0,description:"Level: its bundle key as offer export shows it (program.stages[].key) or id \u2014 never its name"});party=f.String("--party",{description:"Applicant party id"});applicant=f.String("--applicant",{description:"Applicant account login address (e.g. the test account test@example.com)"});version=f.String("--version",{description:"Offer version id to test (default: the live generation)"});staffInput=f.Array("--staff-input",{description:"A staff input the offer declares, as key=true|false \u2014 repeat it once per input; a staff start must set every one"});proxy=f.Boolean("--proxy",{description:"Start in Stellvertretung (--proxy) or not (--no-proxy); left out, the tenant's default applies, as in the cockpit"});async execute(){let n=await this.caller();II(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=$I(await n.query(x.admission.listAdmissionTree,{client:t}),this.offer,this.run,this.stage),i=this.party;if(this.applicant!==void 0){let d=await n.query(x.applicants.partyByEmail,{client:t,email:this.applicant});if(d===null)throw new We(`applications start-test: no applicant account ${this.applicant} at this school (create it in the cockpit first)`);i=d}let o=await n.mutation(x.admission.staffStartApplicationForParty,{client:t,offerKey:this.offer,partyId:i,programRunId:r.programRunId,programStageId:r.programStageId,...this.proxy===void 0?{}:{startInProxy:this.proxy},staffInputs:ZI(this.staffInput??[]),testMode:!0,...this.version===void 0?{}:{offerVersionId:this.version}}),a,l;try{let d=await n.query(x.workflow.getInstance,{applicationId:o.applicationId});if(d===null)throw new Error("the started application has no workflow instance");a=d.instance.currentNodeIds,l=(await Of(n,o.applicationId,a)).flatMap(c=>c.actions.map(u=>u.id))}catch(d){throw new Error(`applications start-test: started ${o.applicationId}, but reading its state failed: ${d instanceof Error?d.message:String(d)}`,{cause:d})}return this.print({applicationId:o.applicationId,currentNodes:a,testActions:l},d=>[{key:"application",value:d.applicationId},{key:"current nodes",value:d.currentNodes.join(", ")},{key:"test actions",value:d.testActions.join(", ")},{key:"next",value:`test-actions run --application ${d.applicationId} --action <id>`}]),0}},Fy=class extends C{static{s(this,"ApplicationsDiscardTestCommand")}static paths=[["applications","discard-test"]];static usage=$.Usage({category:"Admission",description:"Discard a TEST application (the server refuses a real one), or with --all-test every expired one of the school",details:"With an id: discards that test application. With --all-test --older-than <N>d: lists the school's test applications whose last activity is older than N days (N \u2265 14) and that are not kept as a demo \u2014 a dry run unless --confirm; --confirm discards each expired one the server re-checks, the rest are reported with the reason. Recipe: playbooks/applications/expire-test-applications.md.",examples:[["Dry run","plexus-cli --env prod --tenant <t> applications discard-test --all-test --older-than 14d --dry-run"],["Discard","plexus-cli --env prod --tenant <t> --allow-prod applications discard-test --all-test --older-than 14d --confirm"]]});application=f.String({required:!1});allTest=f.Boolean("--all-test",!1,{description:"Every expired test application of the school instead of one id"});olderThan=f.String("--older-than",{description:"With --all-test: days without activity, as <N>d (N \u2265 14)"});dryRun=f.Boolean("--dry-run",!1,{description:"With --all-test: list only (the default)"});confirm=f.Boolean("--confirm",!1,{description:"With --all-test: discard (else the dry run)"});async execute(){if(!this.allTest){if(this.application===void 0)throw new We("applications discard-test: name an application id, or use --all-test --older-than <N>d");if(this.olderThan!==void 0||this.dryRun||this.confirm)throw new We("applications discard-test: --older-than, --dry-run and --confirm belong to --all-test");return await(await this.caller()).mutation(x.admission.discardTest,{applicationId:this.application}),this.print({discarded:this.application},u=>[{key:"discarded",value:u.discarded}]),0}if(this.application!==void 0)throw new We("applications discard-test: --all-test takes no application id");if(this.olderThan===void 0)throw new We("applications discard-test --all-test: --older-than <N>d is required");if(this.dryRun&&this.confirm)throw new We("applications discard-test: --dry-run and --confirm exclude each other");let n=PW(this.olderThan),t=await this.caller(),r=this.requireTenant(t),i=[],o=null;for(;;){let c=await t.query(x.admission.testTtlPlan,{client:r,olderThanDays:n,cursor:o});if(i.push(...c.rows),c.isDone)break;o=c.continueCursor}let a=i.map(c=>({...c,result:c.verdict!=="expired"?"kept":c.block!==null?"blocked":this.confirm?"pending":"would discard"})),l=i.filter(c=>c.verdict==="expired"&&c.protectedDemo).map(c=>c.applicationId);if(this.confirm&&l.length>0)throw new We(`applications discard-test --all-test: protected demo application(s) in the discard set, nothing discarded: ${l.join(", ")}`);let d=0;if(this.confirm)for(let c of a.filter(u=>u.result==="pending"))try{await t.mutation(x.admission.discardExpiredTest,{applicationId:c.applicationId,olderThanDays:n}),c.result="discarded"}catch(u){d++,c.result=`failed: ${u instanceof Error?u.message:String(u)}`}return this.print({olderThanDays:n,confirm:this.confirm,rows:a},c=>c.rows.map(u=>({id:u.applicationId,lastActivity:new Date(u.lastActivityAt).toISOString().slice(0,10),verdict:u.verdict,block:u.block??"",result:u.result})),["id","lastActivity","verdict","block","result"]),d>0?1:0}};function PW(e){let n=/^(\d+)d$/.exec(e.trim());if(n===null)throw new We(`--older-than "${e}": expected <N>d, e.g. 14d`);return Number(n[1])}s(PW,"parseDays");var Ly=class extends C{static{s(this,"ApplicationsSetKeepDemoCommand")}static paths=[["applications","set-keep-demo"]];static usage=$.Usage({category:"Admission",description:"Mark a TEST application \u201EDemo behalten\u201C (never expires, never discarded), or clear the mark with --off"});application=f.String({required:!0});off=f.Boolean("--off",!1,{description:"Clear the mark"});async execute(){return await(await this.caller()).mutation(x.admission.setKeepAsDemo,{applicationId:this.application,keep:!this.off}),this.print({application:this.application,keepAsDemo:!this.off},t=>[{key:"application",value:t.application},{key:"keep as demo",value:t.keepAsDemo?"ja":"nein"}]),0}},My=class extends C{static{s(this,"ApplicationsStaffInputListCommand")}static paths=[["applications","staff-input","list"]];static usage=$.Usage({category:"Admission",description:"An application's internal inputs (set at the start): value, and why one can no longer be corrected"});application=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.admission.staffInputsOfApplication,{applicationId:this.application});return this.print(t,r=>r.map(i=>({key:i.key,label:i.label.de,value:String(i.value),correctable:i.block===null?"ja":i.block.de})),["key","label","value","correctable"]),0}},qy=class extends C{static{s(this,"ApplicationsStaffInputSetCommand")}static paths=[["applications","staff-input","set"]];static usage=$.Usage({category:"Admission",description:"Correct one internal input of an application, with a reason \u2014 refused once a node that reads it was entered",examples:[["Untick \u201EKind von Mitarbeitenden\u201C",'plexus-cli --env prod --tenant <t> --allow-prod applications staff-input set <id> --input staffApplication=false --reason "falsch angehakt"']]});application=f.String({required:!0});input=f.String("--input",{required:!0,description:"key=true|false"});reason=f.String("--reason",{required:!0,description:"Why \u2014 recorded on the application's activity feed"});async execute(){let n=await this.caller(),[{key:t,value:r}]=ZI([this.input]);return await n.mutation(x.admission.correctStaffInput,{applicationId:this.application,key:t,value:r,reason:this.reason}),this.print({application:this.application,key:t,value:r},i=>[{key:"application",value:i.application},{key:i.key,value:String(i.value)}]),0}},QI=[_y,Py,Ny,Cy,Dy,Fy,Ly,My,qy];function ZI(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!Il.test(t)||r!=="true"&&r!=="false"||i.length>0)throw new We(`--staff-input "${n}": expected key=true or key=false`);return{key:t,value:r==="true"}})}s(ZI,"parseStaffInputs");var Un="contractGenerator",xo="documentTemplate";function Ol(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=Object.keys(n);return(n.kind==="generator"||n.kind==="package")&&typeof n.key=="string"&&n.key.length>0&&(n.revision===void 0||typeof n.revision=="number"&&Number.isInteger(n.revision)&&n.revision>0)&&t.every(r=>r==="kind"||r==="key"||r==="revision")}s(Ol,"isGeneratorRef");function XI(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(XI,"literalOf");function oi(e){let n=XI(e,Un);return Ol(n)?n:null}s(oi,"generatorRefOfNode");function br(e){let n=XI(e,xo);return typeof n=="string"&&n.length>0?n:null}s(br,"documentTemplateKeyOfNode");function eO(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(eO,"generatorRefLabel");var NW=["formExports","generatorStamp"];function nO(e,n,t){let r=e.inputs?.[Un];(r?.kind!=="literal"||!Ol(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Un} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Un]={kind:"literal",value:{...r.value,revision:n.revision}}),e.generatorStamp={inputSchema:n.inputSchema,parties:n.parties,schemaDigest:n.schemaDigest,...n.parts===void 0?{}:{parts:n.parts},...n.coverLetter===void 0?{}:{coverLetter:n.coverLetter}}}s(nO,"applyGeneratorStamp");var CW=["reads"];function Ds(e){if(e===null||typeof e!="object")return e;let n={...e};return Array.isArray(n.nodes)&&(n.nodes=n.nodes.map(t=>{if(t===null||typeof t!="object")return t;let r={...t};for(let i of NW)delete r[i];for(let i of CW)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(Ds,"comparableWorkflowGraph");var _l={id:{de:"die Identit\xE4t ist der Slug des Angebots (bundle.yaml slugs.manifest)",en:"the identity is the offer's slug (bundle.yaml slugs.manifest)"},label:{de:"der Titel steht in bundle.yaml `label`",en:"the title is bundle.yaml `label`"},version:{de:"die Revision z\xE4hlt die Datenbank",en:"the database counts the revision"},applicantMode:{de:"von nichts gelesen",en:"read by nothing"},signatureLevel:{de:"von nichts gelesen",en:"read by nothing"},roleInstances:{de:"die Rollen kommen aus den Formular-Effekten",en:"roles come from the form effects"},leistungen:{de:"von nichts gelesen",en:"read by nothing"},capacity:{de:"die Kapazit\xE4t geh\xF6rt der Kohorte (program.runs[].capacities)",en:"capacity belongs to the cohort (program.runs[].capacities)"},progressLayoutId:{de:"von nichts gelesen",en:"read by nothing"},bewerbungsfenster:{de:"die Kohorte besitzt die \xD6ffnung (isOpen / applicationOpensAt)",en:"the cohort owns opening (isOpen / applicationOpensAt)"},selection:{de:"die Reihenfolge ist der Eingang `waitlistOrder` des Wartelistenknotens (automatisches Nachr\xFCcken gibt es nicht mehr; Freigabe-Strategie und Stichtag las nichts)",en:"the order is the waitlist node's input `waitlistOrder` (automatic promotion is gone; release strategy and deadline were read by nothing)"},progressLayout:{de:"das Fortschrittslayout geh\xF6rt zum Workflow: den Block nach workflow.json `progressLayout` verschieben (ohne Workflow l\xF6schen)",en:"the progress layout belongs to the workflow: move the block to workflow.json `progressLayout` (without a workflow: delete it)"}};function Lf(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=_l[n];return t!==void 0?`manifest: \`${n}\` is no longer part of manifest.json (${t.en}). Delete the line.`:`manifest: unknown key \`${n}\` \u2014 manifest.json carries no key.`})}s(Lf,"manifestIssues");function DW(e){let n=[],t=e.buses;if(!Array.isArray(t))return n;let r=t.find(i=>!!i&&typeof i=="object"&&i.key==="process");if(!r||!Array.isArray(r.states))return n;for(let i of r.states){if(!i||typeof i!="object")continue;let o=i;if(o.terminal!==!0&&(!o.external||typeof o.external!="object")){let a=typeof o.id=="string"?o.id:"?";n.push(`progressLayout: progress state '${a}' is non-terminal but declares no 'external' block (applicant-facing copy) \u2014 resolveStatusPresentation would throw at runtime`)}}return n}s(DW,"validateProgressLayoutExternalCopy");function tO(e){if(e===null||typeof e!="object")return["progressLayout: the full layout object is required"];let n=e.buses;return!Array.isArray(n)||!n.some(t=>!!t&&typeof t=="object"&&t.key==="process")?["progressLayout: the layout must declare the `process` bus"]:DW(e)}s(tO,"progressLayoutIssues");var rO=new Set(["nodes","assignmentRules","channels","processStore","staffInputs"]);var FW=new Set(["sections","effects","outcomes","testScenarios","env","views"]),Mf={id:{de:"der Schl\xFCssel des Formulars ist sein Slug",en:"the form's key is its slug"},label:{de:"der Name steht in der Formularzeile (createSmartForm.label)",en:"the name is the form row's (createSmartForm.label)"},outcomeIds:{de:"die Ergebnisse sind die ids von outcomes[]",en:"the outcomes are the ids of outcomes[]"},schoolSlug:{de:"von nichts gelesen",en:"read by nothing"}};function iO(e,n){if(e===null||typeof e!="object"||Array.isArray(e))return[{de:`${n}: die Formulardefinition muss ein Objekt sein.`,en:`${n}: the form definition must be an object.`}];let t=[];for(let i of Object.keys(e)){if(FW.has(i))continue;let o=Mf[i];t.push(o!==void 0?{de:`${n}: \`${i}\` geh\xF6rt nicht mehr zur Formulardefinition (${o.de}). Die Zeile l\xF6schen.`,en:`${n}: \`${i}\` is no longer part of the form definition (${o.en}). Delete the line.`}:{de:`${n}: unbekannter Schl\xFCssel \`${i}\`.`,en:`${n}: unknown key \`${i}\`.`})}let r=e;for(let i of["sections","effects","outcomes"])Array.isArray(r[i])||t.push({de:`${n}: \`${i}\` muss eine Liste sein.`,en:`${n}: \`${i}\` must be a list.`});return t}s(iO,"smartFormDefinitionShapeIssues");var St=["granted","rejected","waitlisted","other"];function Li(e){return typeof e=="string"&&St.includes(e)}s(Li,"isOutcomeSemantic");var Xt=["arrival","manual"],oO={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function LW(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(LW,"literal");function jy(e){let n=LW(e,"waitlistOrder");return Xt.includes(n)?{waitlistOrder:n}:null}s(jy,"waitlistPolicyOrNull");var yn="responsible",Vy="team:";function qf(e){return`${Vy}${e}`}s(qf,"teamSlot");function Kf(e){return e.startsWith(Vy)?e.slice(Vy.length):null}s(Kf,"teamKeyOfSlot");function sO(e){return e.kind==="responsible"?yn:qf(e.groupKey)}s(sO,"slotIdOf");function jf(e){if(e===yn)return{kind:"responsible"};let n=Kf(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(jf,"slotOfId");var By="review",Uy="checkField",aO="reviewed",lO="reviewing",Vf=["rejected","waitlisted"];function Gy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Gy,"isObject");var MW=new Set(["decision",By]),dO={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function zy(e){return Object.hasOwn(dO,e)?dO[e]:void 0}s(zy,"legacySemanticOfId");function qW(e){return e===By?St.filter(n=>!Vf.includes(n)):St}s(qW,"allowedSemanticsFor");var KW="other";function cO(e){return Gy(e)&&MW.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(cO,"outcomesOf");function uO(e){return(e?.nodes??[]).some(n=>cO(n).some(t=>Gy(t)&&!("semantic"in t)))}s(uO,"needsOutcomeSemantics");function fO(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=cO(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),p=qW(u),h=!1,w=l.map(k=>{if(!Gy(k))return k;let y=String(k.id);if("semantic"in k)return Li(k.semantic)||i.push({nodeId:c,outcomeId:y,value:String(k.semantic)}),k;let b=`${c}.${y}`,E=Object.hasOwn(n,b)?n[b]:void 0;if(E!==void 0)return p.includes(E)?(t.push({nodeId:c,outcomeId:y,semantic:E,source:"answer"}),h=!0,{...k,semantic:E}):(r.push({nodeId:c,nodeType:u,outcomeId:y,allowed:p,answer:E}),k);let T=zy(y),R=T??KW;return p.includes(R)?(t.push({nodeId:c,outcomeId:y,semantic:R,source:T===void 0?"formerDefault":"legacyTable"}),h=!0,{...k,semantic:R}):(r.push({nodeId:c,nodeType:u,outcomeId:y,allowed:p}),k)});return h?{...d,outcomes:w}:a});return t.length===0?{graph:e,written:t,refused:r,invalid:i}:{graph:{...e,nodes:o},written:t,refused:r,invalid:i}}s(fO,"addOutcomeSemantics");var vr="bewerbungOffen";function So(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(So,"isObject");var Wy=["event","effect"];function pO(e){return So(e)&&e.type==="eventTrigger"}s(pO,"isTrigger");function mO(e){let n=So(e.inputs)?e.inputs:{};return"outcomes"in e||Wy.some(t=>t in e||t in n)}s(mO,"oldShape");function hO(e){return(e?.nodes??[]).some(n=>pO(n)&&mO(n))}s(hO,"needsEventTriggerStartMove");function jW(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>So(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===vr))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(So(e.next)?e.next:{});if(!(i.length===1&&i[0]===vr))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=So(e.inputs)?{...e.inputs}:{};for(let l of Wy){let d=o[l];if(So(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of Wy)delete a[l],delete o[l];return So(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(jW,"moveNode");function gO(e){let n=[],t=[],r=e.nodes.map(i=>{if(!pO(i)||!mO(i))return i;let o=jW(i);return"unmoved"in o?(t.push(o.unmoved),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(gO,"moveEventTriggerStart");function Pl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pl,"isObject");var yO={waitlistOrder:"arrival"};function wO(e){return!Pl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(Pl(e.inputs)?e.inputs:{}))}s(wO,"lacksPolicy");function VW(e){return(e?.nodes??[]).some(wO)}s(VW,"needsWaitlistPolicyMove");function Yy(e){return Pl(e)&&Xt.includes(e.waitlistOrder)}s(Yy,"isWaitlistPolicy");function BW(e){if(e===void 0)return{policy:yO,stated:!1};if(!Pl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!Xt.includes(n)?"malformed":{policy:{waitlistOrder:n??yO.waitlistOrder},stated:n!==void 0}}s(BW,"policyOfSelection");function kO(e,n,t={}){let r=[],i=[];if(!VW(e))return{graph:e,moved:r,refused:i};let o=BW(n),a=e.nodes.map(l=>{if(!wO(l))return l;let d=l,c=String(d.id),u=Pl(d.inputs)?{...d.inputs}:{},p=Object.hasOwn(t,c)?t[c]:void 0,h,w;if(p!==void 0)h=p,w="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;h=o.policy,w=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:h.waitlistOrder},r.push({nodeId:c,policy:h,source:w}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(kO,"moveWaitlistPolicyToInputs");function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ao,"isObject");var UW=[Un,xo],GW=["inputSchema","parties","schemaDigest","parts"];function bO(e){return Ao(e)&&e.type==="governedDocument"&&("resolver"in e||Ao(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(bO,"oldShape");function vO(e){return(e?.nodes??[]).some(bO)}s(vO,"needsGeneratorInputMove");function zW(e){let n=Ao(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!Ao(i))return{unmoved:"resolverNotObject"};if(Un in n)return{unmoved:"generatorInputExists"};if(typeof i.key!="string"||i.key.length===0)return{unmoved:"pinWithoutKey"};if(i.kind!=="generator"&&i.kind!=="package")return{unmoved:"pinWithoutKind"};if(i.revision!==void 0&&!(typeof i.revision=="number"&&Number.isInteger(i.revision)&&i.revision>0))return{unmoved:"pinRevisionInvalid"};if((Ao(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>Ao(d)&&UW.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Un]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(GW.filter(d=>d in i).map(d=>[d,i[d]]));Object.keys(l).length>0&&(t.generatorStamp=l),r=i.cockpitFields,delete t.resolver}if(Ao(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(xo in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[xo]={kind:"literal",value:i}}if(o!==void 0){if(r!==void 0)return{unmoved:"cockpitFieldsTwice"};r=o}t.template=a}if(r!==void 0){if("cockpitFields"in e)return{unmoved:"cockpitFieldsExist"};t.cockpitFields=r}return t.inputs=n,{node:t}}s(zW,"moveNode");function xO(e){let n=[],t=[],r=e.nodes.map(i=>{if(!bO(i))return i;let o=zW(i);return"unmoved"in o?(t.push({nodeId:String(i.id),reason:o.unmoved}),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(xO,"moveGeneratorPinsToInputs");var SO=/^\d{4}-\d{2}-\d{2}$/;function xr(e,n){return{de:e,en:n}}s(xr,"issue");function Eo(e){if(typeof e!="object"||e===null)return xr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:xr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return xr(`unbekannte Art ${JSON.stringify(n.kind)}`,`unknown kind ${JSON.stringify(n.kind)}`);let{amount:t,activeFrom:r,activeTo:i}=n;return typeof t!="number"||!Number.isFinite(t)||t<=0?xr("der Betrag muss gr\xF6\xDFer als 0 \u20AC sein","the amount must be greater than \u20AC0"):Number.isInteger(Number((t*100).toFixed(6)))?typeof r!="string"||!SO.test(r)?xr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!SO.test(i)?xr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?xr("das Ende liegt vor dem Beginn","the end is before the start"):n.floorTotal!==void 0&&(typeof n.floorTotal!="number"||!Number.isSafeInteger(n.floorTotal)||n.floorTotal<0)?xr("die Untergrenze muss ein nichtnegativer Centbetrag sein","the floor must be a non-negative amount in cents"):n.pricePeriod!==void 0&&!["month","year","once","unit"].includes(String(n.pricePeriod))?xr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?xr("unbekannte Angaben","unknown details"):null:xr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(Eo,"reductionShapeIssue");function Mi(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.itemKey=="string"&&n.itemKey.length>0&&Array.isArray(n.grantKeys)&&n.grantKeys.every(t=>typeof t=="string"&&t.length>0)&&(n.reduction===void 0||Eo(n.reduction)===null&&n.reduction.kind==="amount")}s(Mi,"isPricedItemValue");var Fs=["freetext","recommendation","choice","pricedItem","record","reduction"],Ls=[...Fs,"appointment"];function EO(e){return typeof e=="string"&&Ls.includes(e)}s(EO,"isTaskResultKind");function Ms(e){return typeof e=="string"&&Fs.includes(e)}s(Ms,"isRecordedTaskResultKind");function qs(e){return Ms(e.kind)}s(qs,"isRecordedTaskResult");var Bf=["number","boolean","enum","text","person","assignment"];function Hy(e){return typeof e=="string"&&Bf.includes(e)}s(Hy,"isRecordFieldType");function TO(e){return e==="number"||e==="boolean"||e==="enum"}s(TO,"isSuggestibleFieldType");var Jy=["form","siblingRank"],Uf=500;function WW(e){switch(e.type){case"number":case"boolean":case"enum":return e.type;case"text":return"string";case"person":return e.multiple===!0?"staffUserList":"staffUser";case"assignment":return"taskAssignment"}}s(WW,"recordFieldValueType");var si={freetext:{choiceValueType:null,valueType:null,textValueType:"string",label:{de:"Freitext",en:"Free text"}},recommendation:{choiceValueType:"enum",valueType:null,textValueType:"string",label:{de:"Empfehlung",en:"Recommendation"}},choice:{choiceValueType:"enum",valueType:"enum",textValueType:"string",label:{de:"Auswahl",en:"Choice"}},pricedItem:{choiceValueType:"enum",valueType:"pricedItem",textValueType:"string",label:{de:"Preisposition",en:"Priced item"}},reduction:{choiceValueType:null,valueType:"reduction",textValueType:"string",label:{de:"Reduktion",en:"Reduction"}},record:{choiceValueType:null,valueType:null,textValueType:"string",label:{de:"Erfassung",en:"Record"}},appointment:{choiceValueType:null,valueType:null,textValueType:null,label:{de:"Termin",en:"Appointment"}}};function Qy(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(Qy,"isProseResult");function Gf(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&Hy(n.type)).map(n=>({key:n.writes,valueType:WW(n),field:n})):YW(e)}s(Gf,"draftResultStoreWrites");function YW(e){let n=si[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(YW,"singleStoreWrite");var AO="team:";function Ks(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(AO)){let n=e.slice(AO.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(Ks,"parseTaskResultChat");var Ue={unknownKind:"[taskResult/unknownKind]",onApproval:"[taskResult/onApproval]",unknownField:"[taskResult/unknownField]",choiceOptions:"[taskResult/choiceOptions]",textRequiredOnFreetext:"[taskResult/textRequiredOnFreetext]",chatMissing:"[taskResult/chatMissing]",chatExternal:"[taskResult/chatExternal]",chatUnknownChannel:"[taskResult/chatUnknownChannel]",appointmentMissingTitle:"[taskResult/appointmentMissingTitle]",pricedItemMissingItem:"[taskResult/pricedItemMissingItem]",pricedItemUnknownItem:"[taskResult/pricedItemUnknownItem]",pricedItemNotInProgram:"[taskResult/pricedItemNotInProgram]",pricedItemOfferWithoutProgram:"[taskResult/pricedItemOfferWithoutProgram]",itemOnNonPricedItem:"[taskResult/itemOnNonPricedItem]",writesOnProse:"[taskResult/writesOnProse]",labelMissing:"[taskResult/labelMissing]",appointmentInvalidDuration:"[taskResult/appointmentInvalidDuration]",recordFields:"[taskResult/recordFields]",fieldsOnNonRecord:"[taskResult/fieldsOnNonRecord]",recordSuggest:"[taskResult/recordSuggest]",recordText:"[taskResult/recordText]",recordPerson:"[taskResult/recordPerson]",recordAssignment:"[taskResult/recordAssignment]",reductionPrices:"[taskResult/reductionPrices]"};var HW=new Set(["if","else","in","true","false","null"]),JW=new Set(["==","!=","<=",">=","&&","||"]);function QW(e){return e>="0"&&e<="9"}s(QW,"isDigit");function ZW(e){return/[a-zA-Z_$]/.test(e)}s(ZW,"isIdentStart");function XW(e){return/[a-zA-Z0-9_.$]/.test(e)}s(XW,"isIdentCont");function e1(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
11023
+ `};var bf="dfa396eefc3da3706f7e3bf5d74f54ecc0268f55d2955511da2aabbec177213c",Sy=kI;var Ay=class extends xe{static{s(this,"AgentToolsCommand")}static paths=[["agent","tools"]];static usage=$.Usage({category:"Agents",description:"Show the shared platform/CLI agent tool schemas and skill revision."});async execute(){return this.print({skillHash:bf,tools:$l}),0}},Ey=class extends xe{static{s(this,"AgentInvokeCommand")}static paths=[["agent","invoke"]];static usage=$.Usage({category:"Agents",description:"Invoke a shared agent tool; pipe its JSON input on stdin."});tool=f.String("--tool",{required:!0,description:"plexus|plexus_skill|plexus_workspace"});async execute(){if("isTTY"in this.context.stdin&&this.context.stdin.isTTY===!0)throw new Error("plexus: pipe the tool's JSON input on stdin.");let n=JSON.parse(await xy(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},bI=[Ay,Ey];var Ty=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],Qde=new Set(Ty.map(e=>e.key));var Ye=["de","en"];function Is(e,n){return Ye.every(t=>e[t]===n[t])}s(Is,"sameText");function In(e){if(e===null||typeof e!="object"||Array.isArray(e))return"not-localized";let n=e;return Object.keys(n).some(r=>!Ye.includes(r))?"not-localized":Ye.filter(r=>{let i=n[r];return typeof i!="string"||i.trim()===""})}s(In,"missingLocales");function Ci(e){let n=In(e);return n!=="not-localized"&&n.length===0}s(Ci,"isLocalizedText");function Rl(e,n){let t={};for(let r of Ye){let i=e.map(o=>o[r]);t[r]=i.every(o=>typeof o=="string"&&o.trim()!=="")?n(i,r):""}return t}s(Rl,"composeTexts");function vf(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(vf,"slugify");var vI="tenant";function xI(e){if(e.length===0||vf(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===vI)return`"${vI}" is reserved for the tenant-wide scope`}s(xI,"unitSlugError");var yW=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Qt(e,n){return`${e}-${n}`}s(Qt,"runStorageKey");function SI(e,n){typeof n!="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 t=`${e}-`;return(!n.startsWith(t)||n.length===t.length)&&ae("CONFLICT",{de:`[run/foreignKey] Der Schl\xFCssel \u201E${n}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${t}<key>\u201C).`,en:`[run/foreignKey] The key "${n}" of the school year is not under the program "${e}" (expected: "${t}<key>").`}),n.slice(t.length)}s(SI,"bareRunKey");function xf(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=In(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?n.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&&n.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===""){n.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"||!yW.test(d)){n.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=t.get(d);if(c!==void 0){n.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}t.set(d,i)}),n}s(xf,"runSpecIssues");var wW="-stufe-",kW=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function $y(e){return`${e}${wW}`}s($y,"stageKeyPrefix");function Os(e,n){return`${$y(e)}${n}`}s(Os,"stageStorageKey");function EI(e,n){let t=$y(e);return n.startsWith(t)&&n.length>t.length}s(EI,"isUnderProgram");function Kr(e,n){let t=$y(e);return EI(e,n)||ae("CONFLICT",{de:`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${n}\u201C liegt nicht unter dem Programm \u201E${e}\u201C (erwartet: \u201E${t}<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 "${n}" is not under the program "${e}" (expected: "${t}<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.`}),n.slice(t.length)}s(Kr,"bareStageKey");function Sf(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=In(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?n.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&&n.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===""){n.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"||!kW.test(d)){n.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=t.get(d);if(c!==void 0){n.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}t.set(d,i)}),n}s(Sf,"stageSpecIssues");function AI(e){return{de:e.de.trim(),en:e.en.trim()}}s(AI,"trimmedText");function bW(e,n){let t=[];return e.de!==n.de&&t.push(`"${e.de}" \u2192 "${n.de}"`),e.en!==n.en&&t.push(`en "${e.en}" \u2192 "${n.en}"`),t.join(", ")}s(bW,"describeNameChange");function Af(e,n,t){if(e===null)return n.length>0&&F("planStageReconcile: stages exist but the offer has no program key"),t.map((a,l)=>({op:"insert",key:a.key,name:AI(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(n.map(a=>[a.key,a])),i=new Set,o=[];t.forEach(({name:a,...l},d)=>{let c={...l,name:AI(a)},u=Os(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={};Is(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[...n].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:EI(e,a.key)?Kr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Af,"planStageReconcile");function Ef(e){switch(e.op){case"insert":return`+stage ${e.key} (${e.name.de})`;case"archive":{let n=e.occupancy,t=[...n&&n.activeApplications>0?[`REFUSED: ${n.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...n&&n.openLeads>0?[`${n.openLeads} open lead(s)`]:[]];return`-stage ${e.key} (${e.name.de})${t.length>0?` \u2014 ${t.join("; ")}`:""}`}case"update":{let n=[];if(e.unarchive&&n.push("restored"),e.changes.name&&n.push(bW(e.changes.name[0],e.changes.name[1])),e.changes.gradeLevel){let[t,r]=e.changes.gradeLevel;n.push(`grade ${t??"\u2013"} \u2192 ${r??"\u2013"}`)}return e.changes.sequence&&n.push(`position ${e.changes.sequence[0]} \u2192 ${e.changes.sequence[1]}`),`~stage ${e.key} (${n.join(", ")})`}}}s(Ef,"describeStageStep");function Tf(e,n){return n.startsWith(e)&&n.length>e.length?n.slice(e.length):void 0}s(Tf,"bareUnder");function $I(e,n,t,r){let i=e.flatMap(w=>w.angebote).find(w=>w.offerKey===n);if(i===void 0){let w=e.flatMap(k=>k.angebote.map(y=>y.offerKey));throw new We(`applications start-test: no offer "${n}" (offers: ${w.join(", ")||"none"})`)}if(i.programKey===void 0)throw new We("applications start-test: the deployment does not serve the offer's program key \u2014 it runs an older release than the CLI; try again after the next release");let o=i.programKey;if(o===null)throw new We(`applications start-test: ${n} has no program yet \u2014 no level to start on`);let a=Os(o,""),l=Qt(o,""),d=s(w=>Tf(a,w)??"(no bundle key)","stageLabel"),c=s(w=>Tf(l,w)??"(no bundle key)","runLabel"),u=i.stages.find(w=>w.stageKey===Os(o,r)||w.stageId===r);if(u===void 0){let w=i.stages.map(b=>`${d(b.stageKey)} (${b.stageId})`).join(", "),k=Tf(a,r),y=k!==void 0&&i.stages.some(b=>b.stageKey===r)?` \u2014 "${r}" is the stored key; the export names it "${k}"`:"";throw new We(`applications start-test: no level "${r}" in ${n}${y} \u2014 name it by its bundle key or id: ${w}`)}let p=d(u.stageKey),h=u.runs.find(w=>w.runKey===Qt(o,t)||w.runId===t);if(h===void 0){let w=u.runs.map(b=>`${c(b.runKey)} (${b.runId})`).join(", "),k=Tf(l,t),y=k!==void 0&&u.runs.some(b=>b.runKey===t)?` \u2014 "${t}" is the stored key; the export names it "${k}"`:"";throw new We(`applications start-test: no school year "${t}" for level ${p}${y} \u2014 name it by its bundle key or id: ${w}`)}if(!h.isOpen)throw new We(`applications start-test: school year ${c(h.runKey)} is closed for level ${p}`);return{programRunId:h.runId,programStageId:u.stageId}}s($I,"resolveStartTarget");function vW(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(vW,"applicantText");function RI(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:vW(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(RI,"applicationRows");var TI=Ty.map(e=>e.email);function II(e,n,t,r){if(t===void 0&&r===void 0)throw new We("applications start-test: name the applicant \u2014 --party <partyId> or --applicant <email>");if(t!==void 0&&r!==void 0)throw new We("applications start-test: --party or --applicant, not both");if(ky(e,n)&&(r===void 0||!TI.includes(r.trim().toLowerCase())))throw new We(`applications start-test: on prod only for the test account ${TI.join(", ")} (--applicant) \u2014 never a real family's`)}s(II,"assertStartApplicant");function OI(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(OI,"processStoreJson");function xW(e){switch(e.kind){case"form":return`form ${e.formInstanceId} (${e.state})`;case"document":return e.file===null?`document ${e.slotKey} (leer)`:`document ${e.slotKey} \xB7 v${e.file.versionNumber} ${e.file.filename??e.file.artifactId}`;case"contract":return`contract ${e.contractId} \xB7 ${e.revision===null?"keine Fassung":`Fassung ${e.revision.snapshotNumber}`} \xB7 ${e.contractStatus}`;case"contracts":return e.contracts.map(n=>`${n.partKey}: contract ${n.contractId} \xB7 ${n.revision===null?"keine Fassung":`Fassung ${n.revision.snapshotNumber}`} \xB7 ${n.contractStatus}`).join("; ")}}s(xW,"refText");function SW(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?xW(e.ref):JSON.stringify(e.value)}s(SW,"holds");function _I(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:SW(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(_I,"storeRows");function $f(e){let n={},t={};for(let r of e){let i=r.indexOf("=");if(i<=0)throw new Error(`Expected key=value, got '${r}'.`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`'${o}' is given twice.`);let a=r.slice(i+1);t[o]=a;try{n[o]=JSON.parse(a)}catch{n[o]=a}}return{values:n,raw:t}}s($f,"parseKv");var PI="started",Rf="submitted",If="submitted",NI="load-scenario:";var CI="(Bewerbung)";function DI(e){return{nodeId:CI,actions:e.map(n=>({id:n.id,label:{de:`${n.label??n.id}${n.count===void 0?"":` (${n.count})`}`,en:`${n.label??n.id}${n.count===void 0?"":` (${n.count})`}`},...n.disabledReason===void 0?{}:{disabledReason:n.disabledReason}}))}}s(DI,"sharedAsList");function FI(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(FI,"disabledText");function LI(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:FI(r)})))}s(LI,"actionRows");function MI(e,n,t=[]){let r=e.filter(({actions:d})=>d.some(c=>c.id===n));if(r.length===0){let d=[...new Set(e.flatMap(({actions:c})=>c.map(u=>u.id)))];throw new Error(`test-actions run: no current node offers "${n}" (offered: ${d.join(", ")||"nothing"})`)}if(r.length>1)throw new Error(`test-actions run: "${n}" is offered by ${r.map(d=>d.nodeId).join(", ")} \u2014 pass --node`);let{nodeId:i,actions:o}=r[0],a=o.find(d=>d.id===n);if(a.disabledReason!==void 0)throw new Error(`test-actions run: "${n}" on ${i} is disabled: ${FI(a)}`);if(i!==CI)return i;let l=t[0];if(l===void 0)throw new Error(`test-actions run: "${n}" needs a current node \u2014 the application has none`);return l}s(MI,"nodeOfferingAction");function qI(e,n,t){if(e.startsWith(NI)){if(Object.hasOwn(t,"autoSubmit"))throw new Error(`test-actions run: ${e}: a scenario's autoSubmit is set by --auto-submit / --no-auto-submit, not --param`);return{autoSubmit:n,...t}}return Object.keys(t).length===0?void 0:{...t}}s(qI,"runParams");async function AW(e,n){let t=await e.query(x.workflow.getInstance,{applicationId:n});if(t===null)throw new Error(`test-actions: application ${n} has no workflow instance`);return t.instance.currentNodeIds}s(AW,"currentNodeIds");function EW(e,n){switch(n){case"notTestApplication":return`${e} is not a test application`;case"completed":case"aborted":case"deleted":return`${e} is ${n} \u2014 test actions run only on an active application`;case"missingPermission":return"the caller lacks bewerbungsmanagement.testActions.run"}}s(EW,"refusalText");async function Of(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${EW(n,r.reason)}`);let i=[];for(let o of t){let a=await e.query(x.workflow.listTestActions,{applicationId:n,nodeId:o});if(a===null)throw new Error(`test-actions: node "${o}" is not in this application's workflow (or it has no instance)`);i.push({nodeId:o,actions:a})}return[...i,DI(r.actions)]}s(Of,"actionsOf");async function KI(e,n,t){return t!==void 0?[t]:await AW(e,n)}s(KI,"nodesOf");var Ry=class extends C{static{s(this,"TestActionsListCommand")}static paths=[["test-actions","list"]];static usage=$.Usage({category:"Admission",description:"List the test-mode actions of the application's current node(s) (scenarios, auto-fill-files, submit, \u2026) and the application-wide ones"});application=f.String("--application",{required:!0,description:"Application id (a test application)"});node=f.String("--node",{description:"Node id (default: the application's current nodes)"});async execute(){let n=await this.caller(),t=await Of(n,this.application,await KI(n,this.application,this.node));return this.print(t,LI,["node","action","label","disabled"]),0}},Iy=class extends C{static{s(this,"TestActionsRunCommand")}application=f.String("--application",{required:!0,description:"Application id (a test application)"});node=f.String("--node",{description:"Node id (default: the application's current nodes)"});static paths=[["test-actions","run"]];static usage=$.Usage({category:"Admission",description:"Run one test-mode action; a scenario (load-scenario:<id>) also submits unless --no-auto-submit"});action=f.String("--action",{required:!0,description:"Action id, e.g. load-scenario:standard, auto-fill-files, submit-form"});autoSubmit=f.Boolean("--auto-submit",!0,{description:"Scenario only: stub the file fields and submit after loading (default on; --no-auto-submit only loads)"});param=f.Array("--param",{description:"Action parameter key=value (repeatable; the value is JSON where it parses, else text), e.g. --param confirmed=true for an action that asks a question first (its `confirm` in `test-actions list`)"});async execute(){let n=qI(this.action,this.autoSubmit,$f(this.param??[]).values),t=await this.caller(),r=this.application,i=await KI(t,this.application,this.node),o=MI(await Of(t,r,i),this.action,i);return await t.mutation(x.workflow.runTestAction,{applicationId:r,nodeId:o,actionId:this.action,...n===void 0?{}:{params:n}}),this.print({ran:this.action,on:o},a=>[{key:"ran",value:a.ran},{key:"on",value:a.on},{key:"next",value:"test-actions list \u2014 file fills and the submit after them run asynchronously"}]),0}},jI=[Ry,Iy];var kr=/^[a-z][A-Za-z0-9]*$/;function Oy(e){return typeof e=="string"&&kr.test(e)}s(Oy,"isNodeId");function _s(e,n){Oy(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${kr.source}.`);let t=new Set(n);if(!t.has(e))return e;let r=2;for(;t.has(`${e}${r}`);)r++;return`${e}${r}`}s(_s,"makeNodeId");var Fi="$env";function de(e){if(e.scope==="env")return`${Fi}.${e.key}`;let n=`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(de,"formatAddress");var Di=/^[a-z][a-zA-Z0-9_]*$/,TW=/^[A-Za-z_][A-Za-z0-9_]*$/;function bo(e){return typeof e=="string"&&e.split(".").every(n=>TW.test(n))}s(bo,"isPath");function ti(e){if(!e.startsWith("$"))return null;let n=e.slice(1).split("."),[t,...r]=n;switch(t){case"env":{let i=r.join(".");return r.length>0&&bo(i)?{scope:"env",key:i}:null}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Di.test(o)||(t==="node"?!kr.test(i):!Di.test(i))?null:$W({scope:t,owner:i,key:o},a)}default:return null}}s(ti,"tryParseAddress");function $W(e,n){if(n.length===0)return e;let t=n.join(".");return bo(t)?{...e,path:t}:null}s($W,"withPath");function we(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=n.scope==="env"?["scope","key"]:["scope","owner","key","path"];if(Object.keys(n).some(r=>!t.includes(r))||n.path!==void 0&&!bo(n.path))return!1;switch(n.scope){case"env":return bo(n.key);case"node":return typeof n.owner=="string"&&kr.test(n.owner)&&typeof n.key=="string"&&Di.test(n.key);case"task":return typeof n.owner=="string"&&Di.test(n.owner)&&typeof n.key=="string"&&Di.test(n.key);default:return!1}}s(we,"isAddress");var ri={offer:{key:"string",title:"string"},unit:{key:"string",name:"string"},stage:{key:"string",name:"string",gradeLevel:"number"},run:{key:"string",name:"string",startDate:"date"},applicant:{language:"enum",channel:"enum"}},Ps=Object.keys(ri);function Ns(e){return Object.hasOwn(ri,e)}s(Ns,"isEnvKey");var RW=["self-service","staff"];function VI(e,n){return{kind:"fixed",values:e,labels:n}}s(VI,"fixedSet");var _f={of:"applicant.language",withoutValue:"de"},ii={"offer.key":{valueSet:{kind:"live"},nullable:!1,label:{de:"Angebot",en:"Offer"}},"offer.title":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Titel des Angebots",en:"Offer title"},nameLanguage:_f},"unit.key":{valueSet:{kind:"live"},nullable:!1,label:{de:"Einheit",en:"Unit"}},"unit.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name der Einheit",en:"Unit name"},nameLanguage:_f},"stage.key":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Klassenstufe (Schl\xFCssel)",en:"Grade (key)"},cohortBound:!0},"stage.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name der Klassenstufe",en:"Grade name"},cohortBound:!0,nameLanguage:_f},"stage.gradeLevel":{valueSet:{kind:"open"},nullable:!0,absent:{de:"Die Stufe hat keine Klassenstufe (Kindergarten).",en:"The stage has no grade level (Kindergarten)."},label:{de:"Klassenstufe",en:"Grade level"},cohortBound:!0},"run.key":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Schuljahr",en:"School year"},cohortBound:!0},"run.name":{valueSet:{kind:"unstable"},nullable:!1,label:{de:"Name des Schuljahrs",en:"School year name"},cohortBound:!0,nameLanguage:_f},"run.startDate":{valueSet:{kind:"open"},nullable:!0,absent:{de:"F\xFCr das Schuljahr ist kein Beginn erfasst.",en:"The school year has no start date."},label:{de:"Beginn des Schuljahrs",en:"School year start"},cohortBound:!0},"applicant.language":{valueSet:VI(Ye,{de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}}),nullable:!0,absent:{de:"Die Bewerbung hat kein Bewerberkonto (intern angelegt).",en:"The application has no applicant account (started by staff)."},label:{de:"Bewerbersprache",en:"Applicant language"}},"applicant.channel":{valueSet:VI(RW,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},Pf={types:ri,fields:ii},Nf=Ps.flatMap(e=>Object.keys(ri[e]).map(n=>`${e}.${n}`));function Zt(e){return Object.hasOwn(ii,e)}s(Zt,"isEnvLeaf");function Cf(e){return`${Fi}.${e}`}s(Cf,"envIdentifier");function vo(e){let n=ii[e],[t,r]=e.split("."),i=ri[t][r];i===void 0&&F(`[env] leaf "${e}" has no type`);let o=n.valueSet;return{leaf:e,type:i,label:n.label,nullable:n.nullable,...n.absent===void 0?{}:{absent:n.absent},...n.nameLanguage===void 0?{}:{nameLanguage:n.nameLanguage},...n.cohortBound===void 0?{}:{cohortBound:n.cohortBound},...o.kind==="fixed"?{enumOptions:o.values.map(a=>{let l=o.labels[a];return l===void 0&&F(`[env] "${e}" names the value "${a}" without a label`),{value:a,label:l}})}:{}}}s(vo,"envLeaf");var BI="staffInput";var IW=["boolean"],Il=/^[a-z][A-Za-z0-9]*$/;function Df(e){return e.staffInputs??[]}s(Df,"staffInputsOf");function Ff(e){return`${BI}.${e}`}s(Ff,"staffInputLeaf");function UI(e){return`${Fi}.${Ff(e)}`}s(UI,"staffInputIdentifier");function OW(e){let n=`${BI}.`;return e.startsWith(n)?e.slice(n.length):null}s(OW,"staffInputKeyOfLeaf");function Cs(e,n){let t=OW(n);return t===null?void 0:Df(e).find(r=>r.key===t)}s(Cs,"declaredStaffInput");function GI(e){return[...Df(e).map(n=>({leaf:Ff(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...Nf.map(n=>{let t=vo(n);return{leaf:n,type:t.type,label:t.label,valueSet:ii[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(GI,"envLeavesFor");function zI(e){return GI(e).filter(n=>!n.cohortBound)}s(zI,"conditionEnvLeaves");function WI(e){return HI(zI(e))}s(WI,"envConditionSchemaFor");function _W(e){return GI(e).map(n=>n.leaf==="stage.key"?{...n,valueSet:{kind:"open"}}:n)}s(_W,"offerConditionEnvLeaves");function YI(e){return HI(_W(e))}s(YI,"offerConditionSchemaFor");function HI(e){let n={},t={};for(let{leaf:r,type:i,valueSet:o,nullable:a}of e){let[l="",d=""]=r.split(".");n[l]={...n[l]??{},[d]:i},t[r]={valueSet:o,nullable:a}}return{types:n,fields:t}}s(HI,"schemaOfLeaves");function JI(e){let n=e.staffInputs;if(n===void 0)return[];if(!Array.isArray(n))return[{path:"staffInputs",reason:{de:"[staffInput/shape] graph.staffInputs muss eine Liste sein.",en:"[staffInput/shape] graph.staffInputs must be a list."}}];let t=[],r=new Set;return n.forEach((i,o)=>{let a=`staffInputs[${o}]`,l=i;if(l===null||typeof l!="object"||typeof l.key!="string"){t.push({path:a,reason:{de:"[staffInput/shape] Eine interne Angabe braucht key, type und label ({ de, en }).",en:"[staffInput/shape] An internal entry needs key, type and label ({ de, en })."}});return}let d={de:`Interne Angabe "${l.key}"`,en:`Internal entry "${l.key}"`};Il.test(l.key)||t.push({path:`${a}.key`,reason:{de:`[staffInput/keyFormat] ${d.de}: Schl\xFCssel beginnt mit einem Kleinbuchstaben und enth\xE4lt nur Buchstaben und Ziffern.`,en:`[staffInput/keyFormat] ${d.en}: the key starts with a lowercase letter and contains only letters and digits.`}}),r.has(l.key)&&t.push({path:`${a}.key`,reason:{de:`[staffInput/duplicateKey] ${d.de}: Schl\xFCssel ist doppelt vergeben.`,en:`[staffInput/duplicateKey] ${d.en}: the key is used twice.`}}),r.add(l.key),IW.includes(l.type)||t.push({path:`${a}.type`,reason:{de:`[staffInput/unknownType] ${d.de}: Typ "${String(l.type)}" \u2014 erlaubt ist nur "boolean" (K\xE4stchen).`,en:`[staffInput/unknownType] ${d.en}: type "${String(l.type)}" \u2014 only "boolean" (checkbox) is allowed.`}});let c=In(l.label);c==="not-localized"?t.push({path:`${a}.label`,reason:{de:`[staffInput/shape] ${d.de}: label muss { de, en } sein.`,en:`[staffInput/shape] ${d.en}: label must be { de, en }.`}}):c.length>0&&t.push({path:`${a}.label`,reason:{de:`[i18n/missingTranslation] ${d.de}: Beschriftung fehlt in ${c.join(", ")}.`,en:`[i18n/missingTranslation] ${d.en}: label is missing in ${c.join(", ")}.`}})}),t}s(JI,"staffInputIssues");var Ky={required:!0,description:"Offer slug (its offerKey)"},_y=class extends C{static{s(this,"ApplicationsListCommand")}static paths=[["applications","list"]];static usage=$.Usage({category:"Admission",description:"List an offer's applications (id, status, board state, applicant, test)"});offer=f.String("--offer",Ky);testOnly=f.Boolean("--test-only",!1,{description:"Only test applications"});async execute(){let n=await this.caller(),t=await n.query(x.admission.listForAngebot,{client:this.requireTenant(n),offerKey:this.offer}),r=RI(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},Py=class extends C{static{s(this,"ApplicationsCountsCommand")}static paths=[["applications","counts"]];static usage=$.Usage({category:"Admission",description:"Count an offer's applications per list"});offer=f.String("--offer",Ky);async execute(){let n=await this.caller(),t=await n.query(x.admission.getCountsByListForAngebot,{client:this.requireTenant(n),offerKey:this.offer});return this.print(t,r=>[...Object.entries(r.counts).map(([i,o])=>({list:i,count:String(o)})),{list:"total",count:String(r.total)}],["list","count"]),0}},Ny=class extends C{static{s(this,"ApplicationsShowCommand")}static paths=[["applications","show"]];static usage=$.Usage({category:"Admission",description:"One application: status, test flag, offer, current workflow nodes"});application=f.String({required:!0});async execute(){let n=await this.caller(),t=this.application,r=await n.query(x.admission.get,{applicationId:t});if(r===null)throw new We(`applications show: no application ${t} (or not visible to you)`);let i=await n.query(x.workflow.getInstance,{applicationId:t});return this.print({application:r,currentNodes:i?.instance.currentNodeIds??[]},o=>[{key:"id",value:t},{key:"status",value:o.application.status},{key:"test",value:o.application.testMode?"ja":"nein"},{key:"offer",value:o.application.offerId},{key:"current nodes",value:o.currentNodes.join(", ")}]),0}},Cy=class extends C{static{s(this,"ApplicationsStoreCommand")}static paths=[["applications","store"]];static usage=$.Usage({category:"Admission",description:"One application's process store: every address of its pinned graph, resolved (present / pending / absent)",details:"Staff only (applications.manage). --json prints one object keyed by the canonical address ($node\u2026, $task\u2026, $env\u2026). Values are shown whatever their audience \u2014 never hand the output to the family. Recipe: playbooks/applications/inspect-process-store.md."});application=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.processStoreView.get,{applicationId:this.application});return this.print(OI(t),()=>_I(t),["address","state","holds","producer","written"]),0}},Dy=class extends C{static{s(this,"ApplicationsStartTestCommand")}static paths=[["applications","start-test"]];static usage=$.Usage({category:"Admission",description:"Start a TEST application for an applicant (school year and level by key or id) and show what test mode offers next",details:"Always test mode. --applicant names the account by its login address (on prod only the tenant's test account); --party names the applicant party directly. Without --version it runs on the live generation, like the cockpit."});offer=f.String("--offer",Ky);run=f.String("--run",{required:!0,description:"School year: its bundle key as offer export shows it (program.runs[].key) or id \u2014 never its name"});stage=f.String("--stage",{required:!0,description:"Level: its bundle key as offer export shows it (program.stages[].key) or id \u2014 never its name"});party=f.String("--party",{description:"Applicant party id"});applicant=f.String("--applicant",{description:"Applicant account login address (e.g. the test account test@example.com)"});version=f.String("--version",{description:"Offer version id to test (default: the live generation)"});staffInput=f.Array("--staff-input",{description:"A staff input the offer declares, as key=true|false \u2014 repeat it once per input; a staff start must set every one"});proxy=f.Boolean("--proxy",{description:"Start in Stellvertretung (--proxy) or not (--no-proxy); left out, the tenant's default applies, as in the cockpit"});async execute(){let n=await this.caller();II(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=$I(await n.query(x.admission.listAdmissionTree,{client:t}),this.offer,this.run,this.stage),i=this.party;if(this.applicant!==void 0){let d=await n.query(x.applicants.partyByEmail,{client:t,email:this.applicant});if(d===null)throw new We(`applications start-test: no applicant account ${this.applicant} at this school (create it in the cockpit first)`);i=d}let o=await n.mutation(x.admission.staffStartApplicationForParty,{client:t,offerKey:this.offer,partyId:i,programRunId:r.programRunId,programStageId:r.programStageId,...this.proxy===void 0?{}:{startInProxy:this.proxy},staffInputs:ZI(this.staffInput??[]),testMode:!0,...this.version===void 0?{}:{offerVersionId:this.version}}),a,l;try{let d=await n.query(x.workflow.getInstance,{applicationId:o.applicationId});if(d===null)throw new Error("the started application has no workflow instance");a=d.instance.currentNodeIds,l=(await Of(n,o.applicationId,a)).flatMap(c=>c.actions.map(u=>u.id))}catch(d){throw new Error(`applications start-test: started ${o.applicationId}, but reading its state failed: ${d instanceof Error?d.message:String(d)}`,{cause:d})}return this.print({applicationId:o.applicationId,currentNodes:a,testActions:l},d=>[{key:"application",value:d.applicationId},{key:"current nodes",value:d.currentNodes.join(", ")},{key:"test actions",value:d.testActions.join(", ")},{key:"next",value:`test-actions run --application ${d.applicationId} --action <id>`}]),0}},Fy=class extends C{static{s(this,"ApplicationsDiscardTestCommand")}static paths=[["applications","discard-test"]];static usage=$.Usage({category:"Admission",description:"Discard a TEST application (the server refuses a real one), or with --all-test every expired one of the school",details:"With an id: discards that test application. With --all-test --older-than <N>d: lists the school's test applications whose last activity is older than N days (N \u2265 14) and that are not kept as a demo \u2014 a dry run unless --confirm; --confirm discards each expired one the server re-checks, the rest are reported with the reason. Recipe: playbooks/applications/expire-test-applications.md.",examples:[["Dry run","plexus-cli --env prod --tenant <t> applications discard-test --all-test --older-than 14d --dry-run"],["Discard","plexus-cli --env prod --tenant <t> --allow-prod applications discard-test --all-test --older-than 14d --confirm"]]});application=f.String({required:!1});allTest=f.Boolean("--all-test",!1,{description:"Every expired test application of the school instead of one id"});olderThan=f.String("--older-than",{description:"With --all-test: days without activity, as <N>d (N \u2265 14)"});dryRun=f.Boolean("--dry-run",!1,{description:"With --all-test: list only (the default)"});confirm=f.Boolean("--confirm",!1,{description:"With --all-test: discard (else the dry run)"});async execute(){if(!this.allTest){if(this.application===void 0)throw new We("applications discard-test: name an application id, or use --all-test --older-than <N>d");if(this.olderThan!==void 0||this.dryRun||this.confirm)throw new We("applications discard-test: --older-than, --dry-run and --confirm belong to --all-test");return await(await this.caller()).mutation(x.admission.discardTest,{applicationId:this.application}),this.print({discarded:this.application},u=>[{key:"discarded",value:u.discarded}]),0}if(this.application!==void 0)throw new We("applications discard-test: --all-test takes no application id");if(this.olderThan===void 0)throw new We("applications discard-test --all-test: --older-than <N>d is required");if(this.dryRun&&this.confirm)throw new We("applications discard-test: --dry-run and --confirm exclude each other");let n=PW(this.olderThan),t=await this.caller(),r=this.requireTenant(t),i=[],o=null;for(;;){let c=await t.query(x.admission.testTtlPlan,{client:r,olderThanDays:n,cursor:o});if(i.push(...c.rows),c.isDone)break;o=c.continueCursor}let a=i.map(c=>({...c,result:c.verdict!=="expired"?"kept":c.block!==null?"blocked":this.confirm?"pending":"would discard"})),l=i.filter(c=>c.verdict==="expired"&&c.protectedDemo).map(c=>c.applicationId);if(this.confirm&&l.length>0)throw new We(`applications discard-test --all-test: protected demo application(s) in the discard set, nothing discarded: ${l.join(", ")}`);let d=0;if(this.confirm)for(let c of a.filter(u=>u.result==="pending"))try{await t.mutation(x.admission.discardExpiredTest,{applicationId:c.applicationId,olderThanDays:n}),c.result="discarded"}catch(u){d++,c.result=`failed: ${u instanceof Error?u.message:String(u)}`}return this.print({olderThanDays:n,confirm:this.confirm,rows:a},c=>c.rows.map(u=>({id:u.applicationId,lastActivity:new Date(u.lastActivityAt).toISOString().slice(0,10),verdict:u.verdict,block:u.block??"",result:u.result})),["id","lastActivity","verdict","block","result"]),d>0?1:0}};function PW(e){let n=/^(\d+)d$/.exec(e.trim());if(n===null)throw new We(`--older-than "${e}": expected <N>d, e.g. 14d`);return Number(n[1])}s(PW,"parseDays");var Ly=class extends C{static{s(this,"ApplicationsSetKeepDemoCommand")}static paths=[["applications","set-keep-demo"]];static usage=$.Usage({category:"Admission",description:"Mark a TEST application \u201EDemo behalten\u201C (never expires, never discarded), or clear the mark with --off"});application=f.String({required:!0});off=f.Boolean("--off",!1,{description:"Clear the mark"});async execute(){return await(await this.caller()).mutation(x.admission.setKeepAsDemo,{applicationId:this.application,keep:!this.off}),this.print({application:this.application,keepAsDemo:!this.off},t=>[{key:"application",value:t.application},{key:"keep as demo",value:t.keepAsDemo?"ja":"nein"}]),0}},My=class extends C{static{s(this,"ApplicationsStaffInputListCommand")}static paths=[["applications","staff-input","list"]];static usage=$.Usage({category:"Admission",description:"An application's internal inputs (set at the start): value, and why one can no longer be corrected"});application=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.admission.staffInputsOfApplication,{applicationId:this.application});return this.print(t,r=>r.map(i=>({key:i.key,label:i.label.de,value:String(i.value),correctable:i.block===null?"ja":i.block.de})),["key","label","value","correctable"]),0}},qy=class extends C{static{s(this,"ApplicationsStaffInputSetCommand")}static paths=[["applications","staff-input","set"]];static usage=$.Usage({category:"Admission",description:"Correct one internal input of an application, with a reason \u2014 refused once a node that reads it was entered",examples:[["Untick \u201EKind von Mitarbeitenden\u201C",'plexus-cli --env prod --tenant <t> --allow-prod applications staff-input set <id> --input staffApplication=false --reason "falsch angehakt"']]});application=f.String({required:!0});input=f.String("--input",{required:!0,description:"key=true|false"});reason=f.String("--reason",{required:!0,description:"Why \u2014 recorded on the application's activity feed"});async execute(){let n=await this.caller(),[{key:t,value:r}]=ZI([this.input]);return await n.mutation(x.admission.correctStaffInput,{applicationId:this.application,key:t,value:r,reason:this.reason}),this.print({application:this.application,key:t,value:r},i=>[{key:"application",value:i.application},{key:i.key,value:String(i.value)}]),0}},QI=[_y,Py,Ny,Cy,Dy,Fy,Ly,My,qy];function ZI(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!Il.test(t)||r!=="true"&&r!=="false"||i.length>0)throw new We(`--staff-input "${n}": expected key=true or key=false`);return{key:t,value:r==="true"}})}s(ZI,"parseStaffInputs");var Un="contractGenerator",xo="documentTemplate";function Ol(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=Object.keys(n);return(n.kind==="generator"||n.kind==="package")&&typeof n.key=="string"&&n.key.length>0&&(n.revision===void 0||typeof n.revision=="number"&&Number.isInteger(n.revision)&&n.revision>0)&&t.every(r=>r==="kind"||r==="key"||r==="revision")}s(Ol,"isGeneratorRef");function XI(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(XI,"literalOf");function oi(e){let n=XI(e,Un);return Ol(n)?n:null}s(oi,"generatorRefOfNode");function br(e){let n=XI(e,xo);return typeof n=="string"&&n.length>0?n:null}s(br,"documentTemplateKeyOfNode");function eO(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(eO,"generatorRefLabel");var NW=["formExports","generatorStamp"];function nO(e,n,t){let r=e.inputs?.[Un];(r?.kind!=="literal"||!Ol(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Un} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Un]={kind:"literal",value:{...r.value,revision:n.revision}}),e.generatorStamp={inputSchema:n.inputSchema,parties:n.parties,schemaDigest:n.schemaDigest,...n.parts===void 0?{}:{parts:n.parts},...n.coverLetter===void 0?{}:{coverLetter:n.coverLetter}}}s(nO,"applyGeneratorStamp");var CW=["reads"];function Ds(e){if(e===null||typeof e!="object")return e;let n={...e};return Array.isArray(n.nodes)&&(n.nodes=n.nodes.map(t=>{if(t===null||typeof t!="object")return t;let r={...t};for(let i of NW)delete r[i];for(let i of CW)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(Ds,"comparableWorkflowGraph");var _l={id:{de:"die Identit\xE4t ist der Slug des Angebots (bundle.yaml slugs.manifest)",en:"the identity is the offer's slug (bundle.yaml slugs.manifest)"},label:{de:"der Titel steht in bundle.yaml `label`",en:"the title is bundle.yaml `label`"},version:{de:"die Revision z\xE4hlt die Datenbank",en:"the database counts the revision"},applicantMode:{de:"von nichts gelesen",en:"read by nothing"},signatureLevel:{de:"von nichts gelesen",en:"read by nothing"},roleInstances:{de:"die Rollen kommen aus den Formular-Effekten",en:"roles come from the form effects"},leistungen:{de:"von nichts gelesen",en:"read by nothing"},capacity:{de:"die Kapazit\xE4t geh\xF6rt der Kohorte (program.runs[].capacities)",en:"capacity belongs to the cohort (program.runs[].capacities)"},progressLayoutId:{de:"von nichts gelesen",en:"read by nothing"},bewerbungsfenster:{de:"die Kohorte besitzt die \xD6ffnung (isOpen / applicationOpensAt)",en:"the cohort owns opening (isOpen / applicationOpensAt)"},selection:{de:"die Reihenfolge ist der Eingang `waitlistOrder` des Wartelistenknotens (automatisches Nachr\xFCcken gibt es nicht mehr; Freigabe-Strategie und Stichtag las nichts)",en:"the order is the waitlist node's input `waitlistOrder` (automatic promotion is gone; release strategy and deadline were read by nothing)"},progressLayout:{de:"das Fortschrittslayout geh\xF6rt zum Workflow: den Block nach workflow.json `progressLayout` verschieben (ohne Workflow l\xF6schen)",en:"the progress layout belongs to the workflow: move the block to workflow.json `progressLayout` (without a workflow: delete it)"}};function Lf(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=_l[n];return t!==void 0?`manifest: \`${n}\` is no longer part of manifest.json (${t.en}). Delete the line.`:`manifest: unknown key \`${n}\` \u2014 manifest.json carries no key.`})}s(Lf,"manifestIssues");function DW(e){let n=[],t=e.buses;if(!Array.isArray(t))return n;let r=t.find(i=>!!i&&typeof i=="object"&&i.key==="process");if(!r||!Array.isArray(r.states))return n;for(let i of r.states){if(!i||typeof i!="object")continue;let o=i;if(o.terminal!==!0&&(!o.external||typeof o.external!="object")){let a=typeof o.id=="string"?o.id:"?";n.push(`progressLayout: progress state '${a}' is non-terminal but declares no 'external' block (applicant-facing copy) \u2014 resolveStatusPresentation would throw at runtime`)}}return n}s(DW,"validateProgressLayoutExternalCopy");function tO(e){if(e===null||typeof e!="object")return["progressLayout: the full layout object is required"];let n=e.buses;return!Array.isArray(n)||!n.some(t=>!!t&&typeof t=="object"&&t.key==="process")?["progressLayout: the layout must declare the `process` bus"]:DW(e)}s(tO,"progressLayoutIssues");var rO=new Set(["nodes","assignmentRules","channels","processStore","staffInputs"]);var FW=new Set(["sections","effects","outcomes","testScenarios","env","views"]),Mf={id:{de:"der Schl\xFCssel des Formulars ist sein Slug",en:"the form's key is its slug"},label:{de:"der Name steht in der Formularzeile (createSmartForm.label)",en:"the name is the form row's (createSmartForm.label)"},outcomeIds:{de:"die Ergebnisse sind die ids von outcomes[]",en:"the outcomes are the ids of outcomes[]"},schoolSlug:{de:"von nichts gelesen",en:"read by nothing"}};function iO(e,n){if(e===null||typeof e!="object"||Array.isArray(e))return[{de:`${n}: die Formulardefinition muss ein Objekt sein.`,en:`${n}: the form definition must be an object.`}];let t=[];for(let i of Object.keys(e)){if(FW.has(i))continue;let o=Mf[i];t.push(o!==void 0?{de:`${n}: \`${i}\` geh\xF6rt nicht mehr zur Formulardefinition (${o.de}). Die Zeile l\xF6schen.`,en:`${n}: \`${i}\` is no longer part of the form definition (${o.en}). Delete the line.`}:{de:`${n}: unbekannter Schl\xFCssel \`${i}\`.`,en:`${n}: unknown key \`${i}\`.`})}let r=e;for(let i of["sections","effects","outcomes"])Array.isArray(r[i])||t.push({de:`${n}: \`${i}\` muss eine Liste sein.`,en:`${n}: \`${i}\` must be a list.`});return t}s(iO,"smartFormDefinitionShapeIssues");var St=["granted","rejected","waitlisted","other"];function Li(e){return typeof e=="string"&&St.includes(e)}s(Li,"isOutcomeSemantic");var Xt=["arrival","manual"],oO={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function LW(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(LW,"literal");function jy(e){let n=LW(e,"waitlistOrder");return Xt.includes(n)?{waitlistOrder:n}:null}s(jy,"waitlistPolicyOrNull");var yn="responsible",Vy="team:";function qf(e){return`${Vy}${e}`}s(qf,"teamSlot");function Kf(e){return e.startsWith(Vy)?e.slice(Vy.length):null}s(Kf,"teamKeyOfSlot");function sO(e){return e.kind==="responsible"?yn:qf(e.groupKey)}s(sO,"slotIdOf");function jf(e){if(e===yn)return{kind:"responsible"};let n=Kf(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(jf,"slotOfId");var By="review",Uy="checkField",aO="reviewed",lO="reviewing",Vf=["rejected","waitlisted"];function Gy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Gy,"isObject");var MW=new Set(["decision",By]),dO={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function zy(e){return Object.hasOwn(dO,e)?dO[e]:void 0}s(zy,"legacySemanticOfId");function qW(e){return e===By?St.filter(n=>!Vf.includes(n)):St}s(qW,"allowedSemanticsFor");var KW="other";function cO(e){return Gy(e)&&MW.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(cO,"outcomesOf");function uO(e){return(e?.nodes??[]).some(n=>cO(n).some(t=>Gy(t)&&!("semantic"in t)))}s(uO,"needsOutcomeSemantics");function fO(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=cO(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),p=qW(u),h=!1,w=l.map(k=>{if(!Gy(k))return k;let y=String(k.id);if("semantic"in k)return Li(k.semantic)||i.push({nodeId:c,outcomeId:y,value:String(k.semantic)}),k;let b=`${c}.${y}`,E=Object.hasOwn(n,b)?n[b]:void 0;if(E!==void 0)return p.includes(E)?(t.push({nodeId:c,outcomeId:y,semantic:E,source:"answer"}),h=!0,{...k,semantic:E}):(r.push({nodeId:c,nodeType:u,outcomeId:y,allowed:p,answer:E}),k);let T=zy(y),R=T??KW;return p.includes(R)?(t.push({nodeId:c,outcomeId:y,semantic:R,source:T===void 0?"formerDefault":"legacyTable"}),h=!0,{...k,semantic:R}):(r.push({nodeId:c,nodeType:u,outcomeId:y,allowed:p}),k)});return h?{...d,outcomes:w}:a});return t.length===0?{graph:e,written:t,refused:r,invalid:i}:{graph:{...e,nodes:o},written:t,refused:r,invalid:i}}s(fO,"addOutcomeSemantics");var vr="bewerbungOffen";function So(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(So,"isObject");var Wy=["event","effect"];function pO(e){return So(e)&&e.type==="eventTrigger"}s(pO,"isTrigger");function mO(e){let n=So(e.inputs)?e.inputs:{};return"outcomes"in e||Wy.some(t=>t in e||t in n)}s(mO,"oldShape");function hO(e){return(e?.nodes??[]).some(n=>pO(n)&&mO(n))}s(hO,"needsEventTriggerStartMove");function jW(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>So(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===vr))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(So(e.next)?e.next:{});if(!(i.length===1&&i[0]===vr))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=So(e.inputs)?{...e.inputs}:{};for(let l of Wy){let d=o[l];if(So(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of Wy)delete a[l],delete o[l];return So(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(jW,"moveNode");function gO(e){let n=[],t=[],r=e.nodes.map(i=>{if(!pO(i)||!mO(i))return i;let o=jW(i);return"unmoved"in o?(t.push(o.unmoved),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(gO,"moveEventTriggerStart");function Pl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pl,"isObject");var yO={waitlistOrder:"arrival"};function wO(e){return!Pl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(Pl(e.inputs)?e.inputs:{}))}s(wO,"lacksPolicy");function VW(e){return(e?.nodes??[]).some(wO)}s(VW,"needsWaitlistPolicyMove");function Yy(e){return Pl(e)&&Xt.includes(e.waitlistOrder)}s(Yy,"isWaitlistPolicy");function BW(e){if(e===void 0)return{policy:yO,stated:!1};if(!Pl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!Xt.includes(n)?"malformed":{policy:{waitlistOrder:n??yO.waitlistOrder},stated:n!==void 0}}s(BW,"policyOfSelection");function kO(e,n,t={}){let r=[],i=[];if(!VW(e))return{graph:e,moved:r,refused:i};let o=BW(n),a=e.nodes.map(l=>{if(!wO(l))return l;let d=l,c=String(d.id),u=Pl(d.inputs)?{...d.inputs}:{},p=Object.hasOwn(t,c)?t[c]:void 0,h,w;if(p!==void 0)h=p,w="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;h=o.policy,w=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:h.waitlistOrder},r.push({nodeId:c,policy:h,source:w}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(kO,"moveWaitlistPolicyToInputs");function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ao,"isObject");var UW=[Un,xo],GW=["inputSchema","parties","schemaDigest","parts"];function bO(e){return Ao(e)&&e.type==="governedDocument"&&("resolver"in e||Ao(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(bO,"oldShape");function vO(e){return(e?.nodes??[]).some(bO)}s(vO,"needsGeneratorInputMove");function zW(e){let n=Ao(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!Ao(i))return{unmoved:"resolverNotObject"};if(Un in n)return{unmoved:"generatorInputExists"};if(typeof i.key!="string"||i.key.length===0)return{unmoved:"pinWithoutKey"};if(i.kind!=="generator"&&i.kind!=="package")return{unmoved:"pinWithoutKind"};if(i.revision!==void 0&&!(typeof i.revision=="number"&&Number.isInteger(i.revision)&&i.revision>0))return{unmoved:"pinRevisionInvalid"};if((Ao(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>Ao(d)&&UW.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Un]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(GW.filter(d=>d in i).map(d=>[d,i[d]]));Object.keys(l).length>0&&(t.generatorStamp=l),r=i.cockpitFields,delete t.resolver}if(Ao(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(xo in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[xo]={kind:"literal",value:i}}if(o!==void 0){if(r!==void 0)return{unmoved:"cockpitFieldsTwice"};r=o}t.template=a}if(r!==void 0){if("cockpitFields"in e)return{unmoved:"cockpitFieldsExist"};t.cockpitFields=r}return t.inputs=n,{node:t}}s(zW,"moveNode");function xO(e){let n=[],t=[],r=e.nodes.map(i=>{if(!bO(i))return i;let o=zW(i);return"unmoved"in o?(t.push({nodeId:String(i.id),reason:o.unmoved}),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(xO,"moveGeneratorPinsToInputs");var SO=/^\d{4}-\d{2}-\d{2}$/;function xr(e,n){return{de:e,en:n}}s(xr,"issue");function Eo(e){if(typeof e!="object"||e===null)return xr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:xr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return xr(`unbekannte Art ${JSON.stringify(n.kind)}`,`unknown kind ${JSON.stringify(n.kind)}`);let{amount:t,activeFrom:r,activeTo:i}=n;return typeof t!="number"||!Number.isFinite(t)||t<=0?xr("der Betrag muss gr\xF6\xDFer als 0 \u20AC sein","the amount must be greater than \u20AC0"):Number.isInteger(Number((t*100).toFixed(6)))?typeof r!="string"||!SO.test(r)?xr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!SO.test(i)?xr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?xr("das Ende liegt vor dem Beginn","the end is before the start"):n.floorTotal!==void 0&&(typeof n.floorTotal!="number"||!Number.isSafeInteger(n.floorTotal)||n.floorTotal<0)?xr("die Untergrenze muss ein nichtnegativer Centbetrag sein","the floor must be a non-negative amount in cents"):n.pricePeriod!==void 0&&!["month","year","once","unit"].includes(String(n.pricePeriod))?xr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?xr("unbekannte Angaben","unknown details"):null:xr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(Eo,"reductionShapeIssue");function Mi(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.itemKey=="string"&&n.itemKey.length>0&&Array.isArray(n.grantKeys)&&n.grantKeys.every(t=>typeof t=="string"&&t.length>0)&&(n.reduction===void 0||Eo(n.reduction)===null&&n.reduction.kind==="amount")}s(Mi,"isPricedItemValue");var Fs=["freetext","recommendation","choice","pricedItem","record","reduction"],Ls=[...Fs,"appointment"];function EO(e){return typeof e=="string"&&Ls.includes(e)}s(EO,"isTaskResultKind");function Ms(e){return typeof e=="string"&&Fs.includes(e)}s(Ms,"isRecordedTaskResultKind");function qs(e){return Ms(e.kind)}s(qs,"isRecordedTaskResult");var Bf=["number","boolean","enum","text","person","assignment"];function Hy(e){return typeof e=="string"&&Bf.includes(e)}s(Hy,"isRecordFieldType");function TO(e){return e==="number"||e==="boolean"||e==="enum"}s(TO,"isSuggestibleFieldType");var Jy=["form","siblingRank"],Uf=500;function WW(e){switch(e.type){case"number":case"boolean":case"enum":return e.type;case"text":return"string";case"person":return e.multiple===!0?"staffUserList":"staffUser";case"assignment":return"taskAssignment"}}s(WW,"recordFieldValueType");var si={freetext:{choiceValueType:null,valueType:null,textValueType:"string",label:{de:"Freitext",en:"Free text"}},recommendation:{choiceValueType:"enum",valueType:null,textValueType:"string",label:{de:"Empfehlung",en:"Recommendation"}},choice:{choiceValueType:"enum",valueType:"enum",textValueType:"string",label:{de:"Auswahl",en:"Choice"}},pricedItem:{choiceValueType:"enum",valueType:"pricedItem",textValueType:"string",label:{de:"Preisposition",en:"Priced item"}},reduction:{choiceValueType:null,valueType:"reduction",textValueType:"string",label:{de:"Reduktion",en:"Reduction"}},record:{choiceValueType:null,valueType:null,textValueType:"string",label:{de:"Erfassung",en:"Record"}},appointment:{choiceValueType:null,valueType:null,textValueType:null,label:{de:"Termin",en:"Appointment"}}};function Qy(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(Qy,"isProseResult");function Gf(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&Hy(n.type)).map(n=>({key:n.writes,valueType:WW(n),field:n})):YW(e)}s(Gf,"draftResultStoreWrites");function YW(e){let n=si[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(YW,"singleStoreWrite");var AO="team:";function Ks(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(AO)){let n=e.slice(AO.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(Ks,"parseTaskResultChat");var Ue={unknownKind:"[taskResult/unknownKind]",onApproval:"[taskResult/onApproval]",unknownField:"[taskResult/unknownField]",choiceOptions:"[taskResult/choiceOptions]",textRequiredOnFreetext:"[taskResult/textRequiredOnFreetext]",chatMissing:"[taskResult/chatMissing]",chatExternal:"[taskResult/chatExternal]",chatUnknownChannel:"[taskResult/chatUnknownChannel]",appointmentMissingTitle:"[taskResult/appointmentMissingTitle]",pricedItemMissingItem:"[taskResult/pricedItemMissingItem]",pricedItemUnknownItem:"[taskResult/pricedItemUnknownItem]",pricedItemNotInProgram:"[taskResult/pricedItemNotInProgram]",pricedItemOfferWithoutProgram:"[taskResult/pricedItemOfferWithoutProgram]",itemOnNonPricedItem:"[taskResult/itemOnNonPricedItem]",writesOnProse:"[taskResult/writesOnProse]",labelMissing:"[taskResult/labelMissing]",appointmentInvalidDuration:"[taskResult/appointmentInvalidDuration]",recordFields:"[taskResult/recordFields]",fieldsOnNonRecord:"[taskResult/fieldsOnNonRecord]",recordSuggest:"[taskResult/recordSuggest]",recordText:"[taskResult/recordText]",recordPerson:"[taskResult/recordPerson]",recordAssignment:"[taskResult/recordAssignment]",reductionPrices:"[taskResult/reductionPrices]"};var HW=new Set(["if","else","in","true","false","null"]),JW=new Set(["==","!=","<=",">=","&&","||"]);function QW(e){return e>="0"&&e<="9"}s(QW,"isDigit");function ZW(e){return/[a-zA-Z_$]/.test(e)}s(ZW,"isIdentStart");function XW(e){return/[a-zA-Z0-9_.$]/.test(e)}s(XW,"isIdentCont");function e1(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
11024
11024
  `||r==="\r"){t++;continue}if(r==="'"){let o=t+1,a="";for(;o<e.length&&e.charAt(o)!=="'";)e.charAt(o)==="\\"&&o+1<e.length?(a+=e.charAt(o+1),o+=2):(a+=e.charAt(o),o++);o>=e.length&&F(`Unterminated string at ${t}`),n.push({t:"str",v:a}),t=o+1;continue}if(QW(r)){let o=t;for(;o<e.length&&/[0-9.]/.test(e.charAt(o));)o++;n.push({t:"num",v:Number(e.slice(t,o))}),t=o;continue}if(ZW(r)){let o=t;for(;o<e.length&&XW(e.charAt(o));)o++;let a=e.slice(t,o);HW.has(a)?n.push({t:"kw",v:a}):n.push({t:"ident",v:a}),t=o;continue}let i=e.slice(t,t+2);if(JW.has(i)){n.push({t:"op",v:i}),t+=2;continue}if("<>!".includes(r)){n.push({t:"op",v:r}),t++;continue}if("()[],".includes(r)){n.push({t:"punct",v:r}),t++;continue}F(`Unexpected char '${r}' at ${t}`)}return n}s(e1,"tokenise");var $O=1e4,RO=128;function js(e){e.depth++,e.depth>RO&&F(`Expression nesting too deep (> ${RO})`)}s(js,"enterDepth");function CO(e){return e.pos<e.tokens.length?e.tokens[e.pos]:null}s(CO,"peek");function Gn(e){let n=e.tokens[e.pos];return n||F(`Unexpected end at ${e.pos}`),e.pos++,n}s(Gn,"take");function zn(e,n,t){let r=CO(e);return!(!r||r.t!==n||t!==void 0&&r.v!==t)}s(zn,"match");function To(e,n,t){return zn(e,n,t)||F(`Expected ${n}${t?`:${t}`:""} at ${e.pos}`),Gn(e)}s(To,"expect");function li(e){js(e);try{return zn(e,"kw","if")?n1(e):t1(e)}finally{e.depth--}}s(li,"parseExpr");function n1(e){To(e,"kw","if"),To(e,"punct","(");let n=li(e);To(e,"punct",")");let t=li(e);To(e,"kw","else");let r=li(e);return{kind:"if",cond:n,then:t,else:r}}s(n1,"parseIf");function t1(e){let n=IO(e),t=0;try{for(;zn(e,"op","||");){Gn(e),js(e),t++;let r=IO(e);n={kind:"binary",op:"||",left:n,right:r}}}finally{e.depth-=t}return n}s(t1,"parseLogicOr");function IO(e){let n=OO(e),t=0;try{for(;zn(e,"op","&&");){Gn(e),js(e),t++;let r=OO(e);n={kind:"binary",op:"&&",left:n,right:r}}}finally{e.depth-=t}return n}s(IO,"parseLogicAnd");function OO(e){let n=_O(e),t=0;try{for(;zn(e,"op","==")||zn(e,"op","!=");){let r=Gn(e).v;js(e),t++;let i=_O(e);n={kind:"binary",op:r,left:n,right:i}}}finally{e.depth-=t}return n}s(OO,"parseEquality");function _O(e){let n=Xy(e),t=0;try{for(;zn(e,"op","<")||zn(e,"op","<=")||zn(e,"op",">")||zn(e,"op",">=")||zn(e,"kw","in");){let r=Gn(e),i=r.t==="kw"?"in":r.v;js(e),t++;let o=Xy(e);n={kind:"binary",op:i,left:n,right:o}}}finally{e.depth-=t}return n}s(_O,"parseCompare");function Xy(e){if(zn(e,"op","!")){Gn(e),js(e);try{return{kind:"unary",op:"!",operand:Xy(e)}}finally{e.depth--}}return r1(e)}s(Xy,"parseUnary");function r1(e){let n=CO(e);if(n||F("Unexpected end"),n.t==="num")return Gn(e),{kind:"num",value:n.v};if(n.t==="str")return Gn(e),{kind:"str",value:n.v};if(n.t==="kw"&&n.v==="true")return Gn(e),{kind:"bool",value:!0};if(n.t==="kw"&&n.v==="false")return Gn(e),{kind:"bool",value:!1};if(n.t==="kw"&&n.v==="null")return Gn(e),{kind:"null"};if(n.t==="punct"&&n.v==="("){Gn(e);let t=li(e);return To(e,"punct",")"),t}if(n.t==="punct"&&n.v==="["){Gn(e);let t=[];if(!zn(e,"punct","]"))for(t.push(li(e));zn(e,"punct",",");)Gn(e),t.push(li(e));return To(e,"punct","]"),{kind:"arr",items:t}}if(n.t==="ident"){let t=n.v;if(Gn(e),zn(e,"punct","(")){Gn(e);let r=[];if(!zn(e,"punct",")"))for(r.push(li(e));zn(e,"punct",",");)Gn(e),r.push(li(e));return To(e,"punct",")"),{kind:"call",name:t,args:r}}return{kind:"ident",path:t}}F(`Unexpected token at ${e.pos}`)}s(r1,"parsePrimary");function On(e){e.length>$O&&F(`Expression too long (${e.length} > ${$O})`);let n={tokens:e1(e),pos:0,depth:0},t=li(n);return n.pos<n.tokens.length&&F(`Unexpected trailing token at ${n.pos}`),t}s(On,"parseExpression");var i1=new Map([["today",()=>new Date().toISOString().slice(0,10)],["years_between",(e,n)=>{if(typeof e!="string"||typeof n!="string")return null;let t=new Date(e),r=new Date(n);if(isNaN(t.getTime())||isNaN(r.getTime()))return null;let i=r.getFullYear()-t.getFullYear(),o=r.getMonth()-t.getMonth();return(o<0||o===0&&r.getDate()<t.getDate())&&i--,i}],["length",e=>typeof e=="string"||Array.isArray(e)?e.length:0]]);function wn(e,n){switch(e.kind){case"num":return e.value;case"str":return e.value;case"bool":return e.value;case"null":return null;case"ident":{let t=Object.hasOwn(n.values,e.path)?n.values[e.path]:void 0;return t===void 0?null:t}case"arr":return e.items.map(t=>wn(t,n));case"unary":{let t=wn(e.operand,n);return!$o(t)}case"call":{let t=n.functions!==void 0&&Object.hasOwn(n.functions,e.name)?n.functions[e.name]:i1.get(e.name);t||F(`Unknown function '${e.name}'`);let r=e.args.map(i=>wn(i,n));return t(...r)}case"binary":return o1(e.op,e.left,e.right,n);case"if":return $o(wn(e.cond,n))?wn(e.then,n):wn(e.else,n)}}s(wn,"evaluate");function o1(e,n,t,r){if(e==="&&"){let a=wn(n,r);return $o(a)?$o(wn(t,r)):!1}if(e==="||"){let a=wn(n,r);return $o(a)?!0:$o(wn(t,r))}let i=wn(n,r),o=wn(t,r);switch(e){case"==":return Zy(i,o);case"!=":return!Zy(i,o);case"<":{let[a,l]=zf(i,o);return a!==null&&l!==null&&a<l}case"<=":{let[a,l]=zf(i,o);return a!==null&&l!==null&&a<=l}case">":{let[a,l]=zf(i,o);return a!==null&&l!==null&&a>l}case">=":{let[a,l]=zf(i,o);return a!==null&&l!==null&&a>=l}case"in":return Array.isArray(o)?o.some(a=>Zy(a,i)):!1}}s(o1,"evalBinary");function zf(e,n){return[PO(e),PO(n)]}s(zf,"orderedOperands");function PO(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"){if(e.trim()==="")return null;let n=Number(e);return Number.isFinite(n)?n:null}return null}s(PO,"numericOperand");function Zy(e,n){return e===n?!0:e==null||n==null?!1:typeof e=="number"&&typeof n=="string"?e===Number(n):typeof e=="string"&&typeof n=="number"?Number(e)===n:!1}s(Zy,"looseEq");function $o(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s($o,"truthy");function _n(e){let n=new Set;return ai(e,n),[...n]}s(_n,"dependencies");function ai(e,n){switch(e.kind){case"ident":n.add(e.path);return;case"call":e.args.forEach(t=>ai(t,n));return;case"arr":e.items.forEach(t=>ai(t,n));return;case"unary":ai(e.operand,n);return;case"binary":ai(e.left,n),ai(e.right,n);return;case"if":ai(e.cond,n),ai(e.then,n),ai(e.else,n);return;default:return}}s(ai,"walk");var NO=new Map;function di(e){let n=NO.get(e);return n||(n=On(e),NO.set(e,n)),n}s(di,"parseCached");function s1(e,n){return wn(di(e),n)}s(s1,"evalExpression");function DO(e,n){return $o(s1(e,n))}s(DO,"evalBoolean");function FO(e,n){n!==null&&(typeof n=="object"||typeof n=="function")&&Object.hasOwn(n,"exports")&&F(`[workflow/registry] node type "${e}": custom spec.exports is unsupported; use artifact-slot exports.`)}s(FO,"assertNoCustomNodeExports");var ew=null;function LO(e){for(let[n,t]of Object.entries(e))FO(n,t);ew=e}s(LO,"setSpecs");function MO(){return ew||F("[workflow/registry] Specs not initialised. Import convex/model/admission/specs before calling specFor()."),ew}s(MO,"requireSpecs");function Je(e){let n=MO(),t=n[e.type];return t===void 0&&ae("INVALID",{de:`[workflow/registry] Unbekannter Knotentyp "${String(e.type)}" (Knoten "${String(e.id)}"). Registrierte Typen: ${Object.keys(n).sort().join(", ")}.`,en:`[workflow/registry] Unknown node type "${String(e.type)}" (node "${String(e.id)}"). Registered types: ${Object.keys(n).sort().join(", ")}.`}),t}s(Je,"specFor");function qO(){return Object.keys(MO()).sort()}s(qO,"registeredNodeTypes");var KO=Nf.filter(e=>ii[e].cohortBound!==!0);function nw(e){return Zt(e)&&ii[e].cohortBound!==!0}s(nw,"isEnvAddressLeaf");function tw(e){return vo(e).type}s(tw,"envType");function rw(e){return vo(e).label}s(rw,"envLabel");function iw(e){if(e.scope==="env"||e.path===void 0)return e;switch(e.scope){case"node":return{scope:"node",owner:e.owner,key:e.key};case"task":return{scope:"task",owner:e.owner,key:e.key}}}s(iw,"addressBase");function Sr(e){return e.scope==="node"&&e.key===Mn&&e.path===void 0}s(Sr,"isInstanceAddress");function un(e){return we(e)&&e.scope==="node"&&e.key===Mn&&e.path!==void 0}s(un,"isFormFieldAddress");function jO(e){return un(e)?{owner:e.owner,path:e.path}:null}s(jO,"formFieldOf");function a1(e){return _n(di(e)).map(n=>{if(!n.startsWith("$"))return{identifier:n,address:null,reason:"bareIdentifier"};let t=ti(n);return t===null?{identifier:n,address:null,reason:"shape"}:{identifier:n,address:t}})}s(a1,"expressionAddresses");var Mn="admission",ow="document",Yf="contract",Hf="contracts",VO="payment",sw=new Set(["adoptForm","setFlagTarget","form","familyRequestFrom"]);var ut={id:"identity",type:"identity",label:"display",sublabel:"display",library:"display",outcomes:"control",outputLabels:"display",inputs:"input",next:"control",tasks:"config",assign:"reference",actionTeams:"reference",optionalActions:"config",artifacts:"config",notifications:"config"},xfe={join:{...ut},end:{...ut},eventTrigger:{...ut},form:{...ut,adoptForm:"address",formExports:"stamp"},roleAssign:{...ut},setFlag:{...ut},if:{...ut,condition:"address"},countersign:{...ut,contract:"address",titles:"display",signing:"config"},engagePush:{...ut,engage:"tenantRef",form:"address",contract:"address",payment:"address"},decision:{...ut,commentRequired:"config",decisionAsTask:"config",reads:"address",view:"config",requiresOneOf:"config"},review:{...ut,form:"address",commentRequired:"config",decisionAsTask:"config"},waitlist:{...ut},completenessCheck:{...ut,requires:"address",deadline:"config"},collectPayment:{...ut},governedDocument:{...ut,production:"config",form:"address",generatorStamp:"stamp",templateStamp:"stamp",approval:"config",confirmBeforeIssue:"config",confirmContractTerms:"config",contractTermsQuestionText:"display",responseStrategy:"config",titles:"display",responseLabels:"display",reads:"address"}};function jr(e){return Array.isArray(e)?e:[]}s(jr,"listOf");function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(ft,"record");function BO(e){switch(e.type){case"countersign":return["contract"];case"engagePush":return["form","contract","payment"];case"governedDocument":return e.production==="resolver"?["form"]:[];case"review":return["form"];default:return[]}}s(BO,"dataSourceFieldsOf");function UO(e){return e.type==="review"?[]:e.type==="engagePush"?["form"]:BO(e)}s(UO,"requiredDataSourceFields");var l1={setFlag:{target:"setFlagTarget"}};function Nl(e,n={}){let t=[],r=e,i=`nodes.${e.id}`,o=s((d,c,u,p={})=>{t.push({kind:d,at:c,nodeId:e.id,value:u,judgedTogether:null,...p})},"field"),a=new Map(n.slotTypes===!1?[]:(Je(e).inputs?.(e)??[]).map(d=>[d.id,d.type])),l=l1[e.type]??{};for(let[d,c]of Object.entries(ft(r.inputs)??{})){let u=ft(c);if(u?.kind!=="binding")continue;let p="address"in u?u.address:u.path,h=l[d];if(h!==void 0){o(h,`${i}.inputs.${d}`,p);continue}let w=a.get(d);o("binding",`${i}.inputs.${d}`,p,w!==void 0?{expectedType:w}:{})}for(let[d,c]of jr(r.reads).entries())o("nodeReads",`${i}.reads.${d}`,c,{judgedTogether:`${i}.reads`});for(let[d,c]of jr(r.requires).entries())o("requires",`${i}.requires.${d}`,c,{judgedTogether:`${i}.requires`});e.type==="form"&&r.adoptForm!==void 0&&o("adoptForm",`${i}.adoptForm`,r.adoptForm);for(let d of BO(e))r[d]!==void 0&&o(d,`${i}.${d}`,r[d]);e.type==="if"&&r.condition!==void 0&&o("condition",`${i}.condition`,r.condition);for(let[d,c]of Object.entries(ft(r.assign)??{}))for(let[u,p]of jr(c).entries()){let h=ft(p)?.when;h!=null&&o("teamWhen",d1(e.id,d,u),h,{expectedType:"boolean"})}for(let[d,c]of jr(r.tasks).entries())t.push(...GO(e.id,c,d));for(let[d,c]of jr(r.optionalActions).entries()){let u=ft(c);u?.when!==void 0&&o("optionalActionWhen",c1(e.id,typeof u.key=="string"?u.key:String(d)),u.when)}return t}s(Nl,"nodeAddressFields");function d1(e,n,t){return`nodes.${e}.assign.${n}.${t}.when`}s(d1,"teamWhenPath");function c1(e,n){return`nodes.${e}.optionalActions.${n}.when`}s(c1,"optionalActionWhenPath");function GO(e,n,t){let r=ft(n);if(r===null)return[];let i=[],o=typeof r.key=="string"?r.key:String(t),a=`nodes.${e}.tasks.${o}`,l=s((p,h,w,k={})=>{i.push({kind:p,at:h,nodeId:e,taskKey:o,value:w,judgedTogether:null,...k})},"field"),d=`${a}.evidence`;r.when!==void 0&&l("taskWhen",`${a}.when`,r.when,{expectedType:"boolean",judgedTogether:d});for(let[p,h]of jr(r.reads).entries())l("taskReads",`${a}.reads.${p}`,h,{judgedTogether:d});for(let[p,h]of jr(r.inputs).entries())l("taskInput",`${a}.inputs.${p}`,h);for(let[p,h]of jr(r.documents).entries()){let w=ft(h);w===null||w.kind!=="field"||l("taskDocument",`${a}.documents.${p}`,w.address)}let c=ft(r.familyRequest);if(c!==null){for(let[p,h]of jr(c.fields).entries())l("familyRequestFields",`${a}.familyRequest.fields.${p}`,h,{judgedTogether:`${a}.familyRequest.fields`});c.from!==void 0&&l("familyRequestFrom",`${a}.familyRequest.from`,c.from)}let u=ft(r.result);if(u?.kind==="record")for(let[p,h]of jr(u.fields).entries()){let w=ft(ft(h)?.suggest);if(w?.kind!=="form")continue;let k=ft(h)?.type;l("suggest",`${a}.result.fields.${p}.suggest`,"address"in w?w.address:w.key,typeof k=="string"?{expectedType:k}:{})}return i}s(GO,"taskAddressFields");function Vs(e){return aw(e)?(lw(e.value)??[]).flatMap(n=>n.address===null?[]:[n.address]):we(e.value)?[e.value]:[]}s(Vs,"addressesInField");function aw(e){return e.kind==="condition"||e.kind==="optionalActionWhen"}s(aw,"isExpressionField");function lw(e){if(typeof e!="string"||e.trim().length===0)return null;try{di(e)}catch{return null}return a1(e)}s(lw,"conditionAddresses");function At(e){return e.type==="form"&&e.adoptForm!==void 0&&e.adoptForm!==!1}s(At,"adoptsForm");function zO(e){if(e.type!=="form"||At({type:e.type,adoptForm:e.adoptForm}))return;let n=e.inputs?.smartForm;return n?.kind==="literal"&&typeof n.value=="string"&&n.value!==""?n.value:void 0}s(zO,"createdSmartFormSlug");function u1(e,n){return e.type!=="governedDocument"||e.production!=="resolver"||n!==ow?n:e.generatorStamp?.parts!==void 0?Hf:Yf}s(u1,"addressKeyOfPort");function WO(e){let n=e.result;return n===void 0||!qs(n)?[]:Gf(n).map(t=>t.key)}s(WO,"storeWritesOf");function dw(e,n){return(Array.isArray(e.processStore)?e.processStore:[]).find(t=>t.key===n)}s(dw,"declaredKey");function Vr(e,n){let t=[];if(!At(n))for(let r of Je(n).outputs?.(n)??[])t.push({address:{scope:"node",owner:n.id,key:u1(n,r.name)},type:r.type,...r.label!==void 0?{label:r.label}:{},nodeId:n.id,nodePort:r});for(let r of Array.isArray(n.tasks)?n.tasks:[])for(let i of WO(r)){let o=dw(e,i);t.push({address:{scope:"task",owner:r.key,key:i},type:o?.type??"unknown",...o!==void 0?{label:o.label}:{},nodeId:n.id})}return t}s(Vr,"producedAddresses");function YO(e,n,t){for(let r of e.nodes)for(let i of Array.isArray(r.tasks)?r.tasks:[])if(i.key===n&&WO(i).includes(t))return{nodeId:r.id,template:i};return null}s(YO,"taskWriter");function ci(e,n,t){return YO(e,n,t)?.nodeId??null}s(ci,"taskOwnerNode");function f1(e){return Nl(e,{slotTypes:!1}).flatMap(n=>Vs(n).map(t=>({address:t,field:n})))}s(f1,"writtenAddressesOf");function Ro(e,n){let t=[],r=new Set,i=s((a,l,d,c)=>{let u=`${de(a)}|${l}|${d.at}|${c===void 0?"":de(c)}`;r.has(u)||(r.add(u),t.push({address:a,origin:l,field:d,...c!==void 0?{via:c}:{}}))},"push"),o=s((a,l)=>{if(a.scope!=="task")return;let d=YO(e,a.owner,a.key);if(d!==null){for(let c of GO(d.nodeId,d.template))if(!(c.kind!=="taskWhen"&&c.kind!=="taskReads"))for(let u of Vs(c))i(u,"evidence",l,a)}},"carried");for(let{address:a,field:l}of f1(n))i(a,"written",l),o(a,l);return t}s(Ro,"addressReadsOf");function Cl(e,n){switch(n.scope){case"env":return Zt(n.key)?tw(n.key):Cs(e,n.key)?.type;case"task":return n.path!==void 0||ci(e,n.owner,n.key)===null?void 0:dw(e,n.key)?.type;case"node":{let t=e.nodes.find(i=>i.id===n.owner);if(t===void 0)return;let r=Vr(e,t).find(i=>i.address.scope==="node"&&i.address.key===n.key);return r===void 0?void 0:n.path===void 0?r.type:r.nodePort?.schema?.find(i=>i.key===n.path)?.type}}}s(Cl,"addressType");function Wf(e,n){let t=ft(e)?.[n];return typeof t=="string"&&t.length>0?t:void 0}s(Wf,"labelText");function _e(e,n,t){let r=e.nodes.find(i=>i.id===n);return Wf(r?.label,t)??n}s(_e,"nodeDisplayName");function Io(e,n,t){for(let r of e.nodes){let i=(Array.isArray(r.tasks)?r.tasks:[]).find(o=>o.key===n);if(i!==void 0)return Wf(i.title,t)??n}return n}s(Io,"taskDisplayName");function je(e,n,t){let r=[];switch(n.scope){case"env":r.push(Zt(n.key)?rw(n.key)[t]:Cs(e,n.key)?.label[t]??n.key);break;case"task":r.push(Io(e,n.owner,t),Wf(dw(e,n.key)?.label,t)??n.key);break;case"node":{r.push(_e(e,n.owner,t));let i=e.nodes.find(a=>a.id===n.owner),o=i===void 0?void 0:Vr(e,i).find(a=>a.address.scope==="node"&&a.address.key===n.key);r.push(Wf(o?.label,t)??n.key);break}}return n.scope!=="env"&&n.path!==void 0&&r.push(n.path),`${r.join(" \u203A ")} (${de(n)})`}s(je,"displayAddress");var Dl=["beneficiary","signers"];function Fl(e){let n=[];for(let[t,r]of Object.entries(ft(e.inputs)??{})){let i=ft(r);i?.kind==="binding"&&we(i.address)&&n.push({slot:t,address:i.address})}return n}s(Fl,"bindingAddresses");function HO(e,n){return Fl(e).find(t=>t.slot===n)?.address??null}s(HO,"bindingAddressAt");function JO(e,n){let t=s(i=>i.scope==="node"&&i.owner===n||i.scope==="task"&&ci(e,i.owner,i.key)===n,"names");return e.nodes.filter(i=>i.id!==n).flatMap(i=>Nl(i,{slotTypes:!1})).flatMap(i=>Vs(i).filter(t).map(o=>({at:i.at,nodeId:i.nodeId,address:o})))}s(JO,"addressesNaming");var Pn={target:"target",flagKey:"flagKey",value:"value"};function p1(e){return HO(e,Pn.target)}s(p1,"setFlagTarget");function QO(e){let n=p1(e);return n!==null&&Sr(n)?n.owner:null}s(QO,"setFlagTargetOwner");function Jf(e){let n=e.inputs?.[Pn.flagKey];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(Jf,"setFlagKey");function ZO(e){let n=e.inputs?.[Pn.value];if(n===void 0||n.kind==="unset")return!0;if(n.kind==="literal"&&typeof n.value=="boolean")return n.value;F(`[setFlag/valueType] setFlag node "${String(e.id)}": \`${Pn.value}\` is no yes/no literal \u2014 publish refuses that`)}s(ZO,"setFlagValue");function XO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(XO,"isObject");var e_=["target","flagKey","value"];function n_(e){return XO(e)&&e.type==="setFlag"&&e_.some(n=>n in e)}s(n_,"oldShape");function t_(e){return(e?.nodes??[]).some(n_)}s(t_,"needsSetFlagInputMove");function m1(e){let n=XO(e.inputs)?{...e.inputs}:{};if(e_.some(a=>a in e&&Pn[a]in n))return{unmoved:"inputExists"};if("target"in e&&!we(e.target))return{unmoved:"targetNotAddress"};if("flagKey"in e&&typeof e.flagKey!="string")return{unmoved:"flagKeyNotString"};if("value"in e&&typeof e.value!="boolean")return{unmoved:"valueNotBoolean"};let{target:t,flagKey:r,value:i,...o}=e;return t!==void 0&&(n[Pn.target]={kind:"binding",address:t}),typeof r=="string"&&r.length>0&&(n[Pn.flagKey]={kind:"literal",value:r}),i!==void 0&&(n[Pn.value]={kind:"literal",value:i}),{node:{...o,inputs:n}}}s(m1,"moveNode");function r_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!n_(i))return i;let o=m1(i);return"unmoved"in o?(t.push({nodeId:String(i.id),reason:o.unmoved}),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(r_,"moveSetFlagConfigToInputs");function i_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(i_,"isObject");var cw={countersign:{dueInDays:"number"},decision:{allowSkipInTest:"boolean"},completenessCheck:{guestRole:"string"},governedDocument:{responseDueInDays:"number"}},uw={review:["allowSkipInTest"]};function o_(e){return cw[String(e)]??{}}s(o_,"movesOf");function s_(e){return uw[String(e)]??[]}s(s_,"deadOf");function a_(e){return i_(e)&&[...Object.keys(o_(e.type)),...s_(e.type)].some(n=>n in e)}s(a_,"oldShape");function l_(e){return(e?.nodes??[]).some(a_)}s(l_,"needsScalarInputMove");function h1(e,n){return n==="number"?typeof e=="number"&&Number.isInteger(e)&&e>=1:typeof e===n}s(h1,"wellTyped");function g1(e){let n=i_(e.inputs)?{...e.inputs}:{},t={...e};for(let[r,i]of Object.entries(o_(e.type))){if(!(r in e))continue;let o=e[r];if(r in n)return{unmoved:{nodeId:String(e.id),key:r,reason:"inputExists"}};if(!(i==="string"&&o==="")&&!h1(o,i))return{unmoved:{nodeId:String(e.id),key:r,reason:"valueWrongType"}};o!==""&&(n[r]={kind:"literal",value:o}),delete t[r]}for(let r of s_(e.type))delete t[r];return t.inputs=n,{node:t}}s(g1,"moveNode");function d_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!a_(i))return i;let o=g1(i);return"unmoved"in o?(t.push(o.unmoved),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(d_,"moveScalarConfigToInputs");var Bs={team:{label:{de:"Team",en:"Team"},optionSource:"tenantTeams",existence:{check:"generic",catalog:"teamKeys"}},roleKey:{label:{de:"Rolle",en:"Role"},optionSource:"tenantRoles",existence:{check:"node",codes:["roleAssign/unknownRoleKey","completenessCheck/unknownRole"]}},article:{label:{de:"Artikel",en:"Article"},optionSource:"programArticles",existence:{check:"node",codes:["collectPayment/unknownArticle"]}},legalEntity:{label:{de:"Tr\xE4ger",en:"Legal entity"},optionSource:"tenantTraeger",existence:{check:"node",codes:["governedDocument/unknownTraeger","collectPayment/unknownPayee"]}},contractGenerator:{label:{de:"Vertragsgenerator",en:"Contract generator"},optionSource:"tenantGenerators",existence:{check:"publish",by:"admittedGeneratorByKey"}},documentTemplate:{label:{de:"Dokumentvorlage",en:"Document template"},optionSource:"tenantDocumentTemplates",existence:{check:"publish",by:"governedDocument/unknownTemplate"}},smartForm:{label:{de:"Formular",en:"Form"},optionSource:"offerSmartForms",existence:{check:"publish",by:"form/unknownSmartForm"}},unit:{label:{de:"Einrichtung",en:"Unit"},optionSource:"tenantUnits",existence:{check:"generic",catalog:"unitKeys"}},formFlag:{label:{de:"Merkmal im Formular",en:"Flag in the form"},optionSource:"targetFormFlags",existence:{check:"node",codes:["setFlag/unknownFlag"]}}};function Qf(e){return typeof e=="string"&&Object.hasOwn(Bs,e)}s(Qf,"isResourceType");var Lfe=Object.keys(Bs).filter(e=>Bs[e].existence.check==="generic");function c_(e){if(typeof e!="object"||e===null)return!1;let n=e;return typeof n.groupKey=="string"&&n.groupKey.length>0&&Array.isArray(n.grantKeys)&&n.grantKeys.every(t=>typeof t=="string"&&t.length>0)&&(n.reduction===void 0||Eo(n.reduction)===null&&n.reduction.kind==="amount")&&Object.keys(n).every(t=>t==="groupKey"||t==="grantKeys"||t==="reduction")}s(c_,"isPricedGroupValue");var fw=["street","hausnr","plz","ort","land"];function u_(e){return fw.includes(e)}s(u_,"isAddressPart");var y1=["municipality","municipalityKey","district","districtKey"],pw=[...fw,...y1],mw={string:"text",email:"text",tel:"text",number:"number",date:"date",boolean:"boolean",consent:"boolean",enum:"option",address:"composite",docRef:"file",party:"edge",personRef:"edge",personList:"edge",roleKey:"roleKey",pricedItem:"pricedItem",pricedGroup:"pricedGroup",reduction:"reduction",article:"article",legalEntity:"legalEntity",contractGenerator:"contractGenerator",documentTemplate:"documentTemplate",localizedText:"localizedText",staffUser:"staffUser",staffUserList:"staffUser",taskAssignment:"taskAssignment"},Us=Object.keys(mw);function qi(e){return typeof e=="string"&&e in mw}s(qi,"isValueType");function rt(e){return e===void 0?void 0:mw[e]}s(rt,"dataTypeOf");function Zf(e,n){let t=rt(e),r=rt(n);return t!==void 0&&t===r}s(Zf,"valueTypesCompatible");function Oo(e){return e===null?"null is not a text in both languages":Ll(e,{type:"localizedText"})}s(Oo,"completeLocalizedTextIssue");function Ll(e,n){if(Qf(n.type)&&!qi(n.type))return typeof e=="string"&&e.length>0?null:`${JSON.stringify(e)} is not a ${n.type} key`;let t=rt(n.type),r=JSON.stringify(e),i=`slot type "${n.type}" takes a binding, not a literal`;if(t===void 0||t==="composite"||t==="file"||t==="edge"||t==="staffUser"||t==="taskAssignment")return i;if(e===null)return null;switch(t){case"text":return typeof e=="string"?null:`${r} is not a text (slot type "${n.type}")`;case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?null:`${r} is not a date YYYY-MM-DD`;case"number":return typeof e=="number"&&Number.isFinite(e)?null:`${r} is not a number`;case"boolean":return typeof e=="boolean"?null:`${r} is not true/false`;case"option":{if(typeof e!="string")return`${r} is not an option value`;let o=(n.enumOptions??[]).map(a=>a.value);return o.length===0||o.includes(e)?null:`${r} is not one of the options ${o.join(", ")}`}case"pricedItem":{let o=e;return typeof o=="object"&&typeof o.itemKey=="string"&&o.itemKey.length>0&&Array.isArray(o.grantKeys)&&o.grantKeys.every(a=>typeof a=="string")?null:`${r} is not a priced item {"itemKey":\u2026,"grantKeys":[\u2026]}`}case"pricedGroup":return c_(e)?null:`${r} is not a priced group {"groupKey":\u2026,"grantKeys":[\u2026]}`;case"article":return typeof e=="string"&&e.length>0?null:`${r} is not an article key`;case"legalEntity":return typeof e=="string"&&e.length>0?null:`${r} is not a legal entity key`;case"contractGenerator":return Ol(e)?null:`${r} is not a contract generator {"kind":"generator"|"package","key":\u2026,"revision"?:n}`;case"documentTemplate":return typeof e=="string"&&e.length>0?null:`${r} is not a document template key`;case"roleKey":return typeof e=="string"&&e.length>0?null:`${r} is not a role key`;case"localizedText":{let o=e,a=s(l=>typeof l=="string"&&l.trim().length>0,"filled");return typeof o=="object"&&Object.keys(o).sort().join(",")==="de,en"&&a(o.de)&&a(o.en)?null:`${r} is not a text in both languages {"de":\u2026,"en":\u2026}`}case"reduction":{let o=Eo(e);return o===null?null:`${r} is not a reduction \u2014 ${o.en}`}}}s(Ll,"literalTypeIssue");function f_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(f_,"isObject");var w1={collectPayment:{reason:"reason"}},k1={governedDocument:["mockAutoProduce"]},p_={collectPayment:{reason:{de:"`reason` gibt es als Knoteneigenschaft nicht mehr \u2014 der Hinweis f\xFCr die Familie ist der Eingang `inputs.reason` (ein fester Text auf Deutsch und Englisch im Parameter-Bereich).",en:"`reason` no longer exists as a node property \u2014 the note for the family is the input `inputs.reason` (a fixed text in German and English among the parameters)."}},governedDocument:{template:{de:"`template` gibt es am Knoten nicht mehr \u2014 die Parameter geh\xF6ren der Vorlage (ihr Datensatz, `plexus-cli catalog` documentTemplates[].parameters) und werden beim Speichern und Ver\xF6ffentlichen als `templateStamp` \xFCbernommen.",en:"`template` no longer exists on the node \u2014 the parameters belong to the template (its record, `plexus-cli catalog` documentTemplates[].parameters) and are stamped as `templateStamp` on save and publish."},cockpitFields:{de:'`cockpitFields` gibt es nicht mehr \u2014 ein Parameter, der im Cockpit erg\xE4nzt wird, ist sein Eingang `{ kind: "cockpit" }` (im Parameter-Bereich \u201Eim Cockpit erg\xE4nzen").',en:'`cockpitFields` no longer exists \u2014 a parameter completed in the cockpit is its input `{ kind: "cockpit" }` ("complete in the cockpit" among the parameters).'},mockAutoProduce:{de:"`mockAutoProduce` gibt es nicht mehr \u2014 das Muster-Dokument, das ein Upload-Knoten beim Eintritt selbst einstellte, ist entfernt; das Dokument kommt aus einem Upload.",en:"`mockAutoProduce` no longer exists \u2014 the sample document an upload node put on its slot by itself on entry is removed; the document comes from an upload."}}};function hw(e){return w1[String(e)]??{}}s(hw,"movesOf");function m_(e){return k1[String(e)]??[]}s(m_,"deadOf");function h_(e){return f_(e)&&[...Object.keys(hw(e.type)),...m_(e.type)].some(n=>n in e)}s(h_,"oldShape");function g_(e){return(e?.nodes??[]).some(h_)}s(g_,"needsNodeConfigInputMove");function b1(e){return Oo(e)===null}s(b1,"isCompleteText");function v1(e){let n=f_(e.inputs)?{...e.inputs}:{},t={...e};for(let[r,i]of Object.entries(hw(e.type)))if(r in e){if(i in n)return{unmoved:{nodeId:String(e.id),key:r,reason:"inputExists"}};if(!b1(e[r]))return{unmoved:{nodeId:String(e.id),key:r,reason:"valueNotLocalized"}};n[i]={kind:"literal",value:e[r]},delete t[r]}for(let r of m_(e.type))delete t[r];return Object.keys(hw(e.type)).some(r=>r in e)&&(t.inputs=n),{node:t}}s(v1,"moveNode");function y_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!h_(i))return i;let o=v1(i);return"unmoved"in o?(t.push(o.unmoved),i):(n.push(String(i.id)),o.node)});return n.length===0?{graph:e,moved:n,unmoved:t}:{graph:{...e,nodes:r},moved:n,unmoved:t}}s(y_,"moveNodeConfigToInputs");var Ml="collectPayment",Gs=["online","manual"];function Xf(e){return Gs.includes(e)}s(Xf,"isCollectPaymentMode");var _o="paid",gw="skipPayment",yw="confirmPayment",Ki="article",it="mode",ji="reason",er="payee",ww=["one_time"];function ep(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(ep,"isObject");function w_(e){if(!ep(e)||e.type!==Ml)return!1;let n=ep(e.inputs)?e.inputs:{},t=n[it];return!ep(t)||t.kind!=="literal"||t.value!=="online"?!1:!(er in n)}s(w_,"isOnlinePaymentWithoutPayee");function k_(e){return(e?.nodes??[]).some(w_)}s(k_,"needsPayee");function b_(e,n={}){let t=[],r=[],i=e.nodes.map(o=>{if(!w_(o))return o;let a=String(o.id),l=Object.hasOwn(n,a)?n[a]:void 0;if(l===void 0||l==="")return r.push(a),o;t.push({nodeId:a,payee:l});let d=ep(o.inputs)?o.inputs:{};return{...o,inputs:{...d,[er]:{kind:"literal",value:l}}}});return t.length===0?{graph:e,set:t,refused:r}:{graph:{...e,nodes:i},set:t,refused:r}}s(b_,"setPayeeOnOnlinePayments");var v_="settlement",x1={online:"online",separate:"manual"};function kw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(kw,"isObject");function x_(e){return kw(e)&&e.type===Ml&&kw(e.inputs)&&v_ in e.inputs}s(x_,"carriesSettlement");function S_(e){return(e?.nodes??[]).some(x_)}s(S_,"needsPaymentModeRename");function A_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!x_(i))return i;let o=String(i.id),{[v_]:a,...l}=i.inputs;if(it in l)return t.push({nodeId:o,reason:"bothCells"}),i;let d=kw(a)&&a.kind==="literal"&&typeof a.value=="string"?x1[a.value]:void 0;return d===void 0?(t.push({nodeId:o,reason:"unknownValue"}),i):(n.push(o),{...i,inputs:{...l,[it]:{...a,value:d}}})});return n.length===0?{graph:e,moved:n,refused:t}:{graph:{...e,nodes:r},moved:n,refused:t}}s(A_,"renameSettlementToMode");var T_="formView";function np(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(np,"isObject");function bw(e){return Array.isArray(e.tasks)?e.tasks:[]}s(bw,"tasksOf");function ql(e){return np(e)&&T_ in e}s(ql,"carriesFormView");function $_(e){return(e?.nodes??[]).some(n=>ql(n)||np(n)&&bw(n).some(ql))}s($_,"needsFormViewMove");function E_(e){let{[T_]:n,...t}=e;return"view"in t?"bothFields":!np(n)||typeof n.form!="string"||typeof n.key!="string"?"malformed":{...t,view:{kind:"form",form:n.form,view:n.key}}}s(E_,"moved");function R_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!np(i))return i;let o=String(i.id),a=i;if(ql(a)){let l=E_(a);typeof l=="string"?t.push({nodeId:o,reason:l}):(a=l,n.push(o))}return bw(a).some(ql)&&(a={...a,tasks:bw(a).map(l=>{if(!ql(l))return l;let d=String(l.key),c=E_(l);return typeof c=="string"?(t.push({nodeId:o,taskKey:d,reason:c}),l):(n.push(`${o}.${d}`),c)})}),a});return n.length===0?{graph:e,moved:n,refused:t}:{graph:{...e,nodes:r},moved:n,refused:t}}s(R_,"moveFormViewToView");function rp(e){if(!Array.isArray(e))return[{code:"shape",index:null,detail:`expected a list of rows, got ${tp(e)}`}];if(e.length===0)return[{code:"shape",index:null,detail:"expected at least the default row, got an empty list"}];let n=[];for(let i=0;i<e.length;i++){let o=A1(e[i]);o!==null&&n.push({code:"shape",index:i,detail:o})}if(n.length>0)return n;let t=e.flatMap((i,o)=>i.when===null?[o]:[]),r=e.length-1;return(t.length!==1||t[0]!==r)&&n.push({code:"defaultLast",index:t.find(i=>i!==r)??null,detail:S1(t,r)}),n}s(rp,"teamRulesShapeIssues");function S1(e,n){return e.length===0?"no default row (`when: null`) \u2014 the last row must be the default":e.length>1?`${e.length} default rows (rows ${e.join(", ")}) \u2014 exactly one, the last`:`the default row is row ${e[0]}, not the last (${n})`}s(S1,"defaultLastDetail");function vw(e,n){let t=rp(e);return t.length>0&&F(`[assign/${t[0].code}] ${n}: ${t.map(r=>r.index===null?r.detail:`row ${r.index}: ${r.detail}`).join("; ")} \u2014 publish refuses such a graph`),e}s(vw,"readTeamRules");function ip(e){return rp(e).length===0?e:null}s(ip,"tryReadTeamRules");function Dt(e){return op([],e)}s(Dt,"fixedTeam");function op(e,n){return vw([...e.map(({when:t,team:r})=>({when:t,team:r})),{when:null,team:n}],"a constructed team position")}s(op,"teamRulesOf");function xw(e,n){return e===void 0?Dt(n):op(e.slice(0,-1),n)}s(xw,"withDefaultTeam");function I_(e){let n=e[e.length-1];return n===void 0&&F("[assign/shape] a team position has at least its default row \u2014 read it through readTeamRules"),n.team}s(I_,"defaultTeamOf");function O_(e){let n=new Map,t=[];return e.forEach((r,i)=>{if(r.when===null)return;let o=de(r.when),a=n.get(o);a===void 0?n.set(o,i):t.push({index:i,first:a})}),t}s(O_,"shadowedRows");function A1(e){if(typeof e!="object"||e===null||Array.isArray(e))return`expected { when, team }, got ${tp(e)}`;let n=e,t=Object.keys(n).filter(r=>r!=="when"&&r!=="team");return t.length>0?`unknown key(s) ${t.map(r=>`"${r}"`).join(", ")} \u2014 a row is { when, team }`:typeof n.team!="string"||n.team.length===0?`"team" must be a team key, got ${tp(n.team)}`:"when"in n?n.when!==null&&!we(n.when)?`"when" must be an address or null, got ${tp(n.when)}`:null:'"when" is missing \u2014 the default row says `when: null`'}s(A1,"rowShapeProblem");function tp(e){if(e===void 0)return"nothing";let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.length>80?`${n.slice(0,77)}...`:n}s(tp,"describe");function __(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(__,"isObject");function P_(e){return __(e)&&__(e.assign)?e.assign:null}s(P_,"assignOf");function N_(e){return(e?.nodes??[]).some(n=>Object.values(P_(n)??{}).some(t=>typeof t=="string"))}s(N_,"needsNodeAssignFold");function C_(e){let n=[],t=[],r=e.nodes.map(i=>{let o=P_(i);if(o===null)return i;let a=String(i.id),l=!1,d={};for(let[c,u]of Object.entries(o))typeof u=="string"&&u.length>0?(d[c]=Dt(u),n.push({nodeId:a,templateKey:c}),l=!0):(!Array.isArray(u)&&u!==void 0&&t.push({nodeId:a,templateKey:c}),d[c]=u);return l?{...i,assign:d}:i});return n.length===0?{graph:e,moved:n,refused:t}:{graph:{...e,nodes:r},moved:n,refused:t}}s(C_,"foldNodeAssignToTeamRules");function Br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Br,"isObject");function Sw(e){return Array.isArray(e.tasks)?e.tasks:[]}s(Sw,"tasksOf");function Kl(e){return Br(e)&&Array.isArray(e.documents)?e.documents:[]}s(Kl,"documentsOf");function jl(e){return Br(e)&&e.kind==="document"}s(jl,"isDocumentRef");function D_(e){return(e?.nodes??[]).some(n=>Br(n)&&Sw(n).some(t=>Kl(t).some(jl)))}s(D_,"needsDocumentRefMove");function E1(e,n){let t=n.address;if(!Br(t)||t.scope!=="node"||typeof t.owner!="string"||t.path!==void 0||t.key!=="document"&&t.key!=="contract"&&t.key!=="contracts")return null;let r=e.find(a=>Br(a)&&a.id===t.owner),i=Br(r)&&Array.isArray(r.artifacts)?r.artifacts:[];if(i.length!==1)return null;let o=Br(i[0])?i[0].key:void 0;return typeof o=="string"&&o.length>0?o:null}s(E1,"slotOf");function F_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!Br(i)||!Sw(i).some(a=>Kl(a).some(jl)))return i;let o=String(i.id);return{...i,tasks:Sw(i).map(a=>{if(!Br(a)||!Kl(a).some(jl))return a;let l=String(a.key),d=Kl(a).map(p=>jl(p)?E1(e.nodes,p):void 0);if(d.includes(null))return t.push({nodeId:o,taskKey:l,reason:"noSlot"}),a;let c=new Set,u=Kl(a).flatMap((p,h)=>{let w=jl(p)?{kind:"artifact",key:d[h]}:p;if(!Br(w)||w.kind!=="artifact")return[w];let k=String(w.key);return c.has(k)?[]:(c.add(k),[w])});return n.push(`${o}.${l}`),{...a,documents:u}})}});return n.length===0?{graph:e,moved:n,refused:t}:{graph:{...e,nodes:r},moved:n,refused:t}}s(F_,"moveDocumentRefsToArtifact");function sp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(sp,"isObject");function Aw(e){return sp(e)&&sp(e.assign)&&"userId"in e.assign}s(Aw,"namesUser");function ap(e){return(e?.nodes??[]).flatMap(n=>sp(n)&&Array.isArray(n.tasks)?n.tasks.filter(Aw).map(t=>({nodeId:String(n.id),taskKey:String(t.key),hasTeam:typeof t.assign.group=="string"&&t.assign.group.length>0})):[])}s(ap,"taskUserAssignments");function L_(e){let n=ap(e);if(n.length===0)return{graph:e,dropped:n};let t=e.nodes.map(r=>{if(!sp(r)||!Array.isArray(r.tasks)||!r.tasks.some(Aw))return r;let i=r.tasks.map(o=>{if(!Aw(o))return o;let{userId:a,...l}=o.assign,{assign:d,...c}=o;return Object.keys(l).length===0?c:{...c,assign:l}});return{...r,tasks:i}});return{graph:{...e,nodes:t},dropped:n}}s(L_,"dropTaskAssignUserIds");function q_(e,n,t){let r=rp(e);return r.length>0?r.map(i=>{let o=i.index===null?n:`${n}.${i.index}`;return i.code==="defaultLast"?M_(o,{de:`[assign/defaultLast] ${t.de}: genau eine Sonst-Zeile (\`when: null\`), und sie steht am Ende \u2014 ${i.detail}.`,en:`[assign/defaultLast] ${t.en}: exactly one default row (\`when: null\`), and it is the last \u2014 ${i.detail}.`}):M_(o,{de:`[assign/shape] ${t.de}${i.index===null?"":`, Zeile ${i.index}`}: ${i.detail}.`,en:`[assign/shape] ${t.en}${i.index===null?"":`, row ${i.index}`}: ${i.detail}.`})}):O_(e).map(({index:i,first:o})=>K_(`${n}.${i}.when`,"warning",{de:`[assign/duplicateRow] ${t.de}: Zeile ${i} hat dieselbe Bedingung wie Zeile ${o} und greift nie.`,en:`[assign/duplicateRow] ${t.en}: row ${i} has the same condition as row ${o} and never applies.`}))}s(q_,"teamRulesIssues");function K_(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:n}}s(K_,"issue");function M_(e,n){return K_(e,"error",n)}s(M_,"error");var zs={"assign{}":{kind:"team",codec:"key",involves:!0,required:!1,what:{de:"Team der Knoten-Aufgabe",en:"team of the node task"},consequence:{de:"beim Betreten des Knotens entsteht die Aufgabe f\xFCr niemanden",en:"entering the node creates the task for nobody"}},"actionTeams{}":{kind:"team",codec:"key",involves:!1,required:!1,what:{de:"Team, das die Knoten-Aktion ausf\xFChren darf",en:"team that may perform the node action"},consequence:{de:"au\xDFer der zust\xE4ndigen Person darf niemand die Aktion ausf\xFChren",en:"nobody but the responsible person may perform the action"}},"tasks[].assign.group":{kind:"team",codec:"key",involves:!0,required:!0,what:{de:"Team der Aufgabe",en:"team of the task"},consequence:{de:"die Aufgabe kann nicht angelegt werden, und der Prozess bleibt stehen",en:"the task cannot be created and the process stops"}},"tasks[].params.revisionGroup":{kind:"team",codec:"key",involves:!0,required:!1,what:{de:"Team der \xDCberarbeitung",en:"revision team"},consequence:{de:"eine Ablehnung findet niemanden, der \xFCberarbeitet",en:"a rejection finds nobody to revise"}},"tasks[].result.chat":{kind:"team",codec:"chatTarget",involves:!1,required:!1,what:{de:"Chat des Ergebnisses",en:"chat of the result"},consequence:{de:"das Ergebnis l\xE4sst sich nicht im Chat ablegen",en:"the result cannot be posted to the chat"}},"tasks[].result.primaryParticipantTeams":{kind:"team",codec:"key",involves:!1,required:!1,list:!0,what:{de:"Team oben in der Teilnehmer-Auswahl",en:"team listed first in the participant picker"},consequence:{de:"die Teilnehmer-Auswahl kann das Team nicht oben zeigen",en:"the participant picker cannot list the team first"}},"optionalActions[].trigger":{kind:"team",codec:"key",involves:!1,required:!1,what:{de:"Team, das die Aktion ausl\xF6sen darf",en:"team that may trigger the action"},consequence:{de:"niemand au\xDFer der Prozessverantwortung kann die Aktion ausl\xF6sen",en:"nobody but the process owner can trigger the action"}}},Ew=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,"record");function lp(e,n){if(typeof n!="string"||n.length===0)return null;if(e==="key")return n;let t=Ks(n);return t?.kind==="team"?t.groupKey:null}s(lp,"decodeKey");var j_={"assign{}":"assign","actionTeams{}":"actionTeams"},T1=s(e=>e in j_,"isMapLeaf");function $1(e){let n=/^(tasks|optionalActions)\[\](?:\.([a-zA-Z]+))?\.([a-zA-Z]+)$/.exec(e);return n===null&&F(`[resource] unreadable reference leaf "${e}"`),{list:n[1],field:n[2]??null,key:n[3]}}s($1,"locate");function dp(e){let n=[],t=e;for(let[r,i]of Object.entries(j_))for(let[o,a]of Object.entries(Ew(t[i])??{})){if(r==="assign{}"){let l=ip(a);if(l===null){n.push({path:`${i}.${o}`,leaf:r,owner:o,key:lp("key",a),missing:typeof a!="string"||a.length===0});continue}l.forEach((d,c)=>{n.push({path:`${i}.${o}.${c}.team`,leaf:r,owner:o,index:c,key:d.team,missing:!1})});continue}n.push({path:`${i}.${o}`,leaf:r,owner:o,key:lp("key",a),missing:typeof a!="string"||a.length===0})}for(let r of Object.keys(zs)){if(T1(r))continue;let i=zs[r],{list:o,field:a,key:l}=$1(r);for(let d of Array.isArray(t[o])?t[o]:[]){let c=Ew(d);if(c===null||typeof c.key!="string")continue;let p=(a===null?c:Ew(c[a]))?.[l];if(p===void 0&&!i.required)continue;let h=`${o}.${c.key}${a===null?"":`.${a}`}.${l}`;if(i.list===!0){if(!Array.isArray(p)){n.push({path:h,leaf:r,owner:c.key,key:null,missing:!0});continue}let k=c.key;p.forEach((y,b)=>{n.push({path:`${h}.${b}`,leaf:r,owner:k,index:b,key:lp(i.codec,y),missing:typeof y!="string"||y.length===0})});continue}let w=typeof p!="string"||p.length===0;n.push({path:`${o}.${c.key}${a===null?"":`.${a}`}.${l}`,leaf:r,owner:c.key,key:lp(i.codec,p),missing:w})}}return n}s(dp,"nodeResourceReferences");var V_=s(e=>(e??[]).map(n=>`\u201E${n}\u201C`).join(", "),"list"),B_=s(e=>(e??[]).map(n=>`"${n}"`).join(", "),"listEn"),R1={"address/shape":{de:s(e=>({problem:`${e.where}: \u201E${e.address}\u201C ist keine g\xFCltige Adresse.`,remedy:"W\xE4hle die Adresse in der Auswahl neu."}),"de"),en:s(e=>({problem:`${e.where}: "${e.address}" is not a valid address.`,remedy:"Choose the address again from the picker."}),"en")},"address/missing":{de:s(e=>({problem:`${e.where}: Hier fehlt die Adresse, ohne die dieser Schritt nicht arbeiten kann.`,remedy:"W\xE4hle sie in der Auswahl."}),"de"),en:s(e=>({problem:`${e.where}: The address this step cannot work without is missing.`,remedy:"Choose it from the picker."}),"en")},"address/bareIdentifier":{de:s(e=>({problem:`${e.where}: \u201E${e.address}\u201C nennt nur einen Schl\xFCssel, nicht, wer ihn erzeugt.`,remedy:"W\xE4hle in der Auswahl die volle Adresse, z. B. das Feld aus dem Formular, das es erfasst."}),"de"),en:s(e=>({problem:`${e.where}: "${e.address}" names a key only, not who produces it.`,remedy:"Choose the full address from the picker, e.g. the field from the form that collects it."}),"en")},"address/unknownOwner":{de:s(e=>({problem:`${e.where}: ${e.address} nennt einen Knoten oder eine Aufgabe, die es im Ablauf nicht gibt.`,remedy:"W\xE4hle eine Adresse aus der Auswahl."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} names a node or task the workflow does not have.`,remedy:"Choose an address from the picker."}),"en")},"address/unknownKey":{de:s(e=>({problem:`${e.where}: ${e.producer??"der Erzeuger"} erzeugt ${e.address} nicht.`,remedy:"W\xE4hle einen Wert, den der Erzeuger tats\xE4chlich liefert."}),"de"),en:s(e=>({problem:`${e.where}: ${e.producer??"the producer"} does not produce ${e.address}.`,remedy:"Choose a value the producer actually delivers."}),"en")},"address/envCohortBound":{de:s(e=>({problem:`${e.where}: ${e.address} \xE4ndert sich, wenn Stufe oder Schuljahr gewechselt werden \u2014 ein Dokument, das den Wert druckt, w\xFCrde das nicht bemerken.`,remedy:"Lies den Wert \xFCber ein Formularfeld, das ihn berechnet (z. B. \u201EKlassenstufe\u201C): ein Wechsel friert es neu ein und h\xE4lt ein gedrucktes Dokument an."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} changes when the application's stage or school year is changed \u2014 a document printing it would not notice.`,remedy:'Read it through a form field that computes it (e.g. "Grade"): a change re-freezes it and holds a printed document.'}),"en")},"address/staffInputConditionOnly":{de:s(e=>({problem:`${e.where}: ${e.address} ist eine interne Angabe beim Anlegen \u2014 sie lenkt eine Weiche (\u201EWenn\u201C-Knoten) oder f\xFCllt einen Parameter eines Knotens.`,remedy:"Lies sie in der Bedingung eines \u201EWenn\u201C-Knotens oder binde einen Parameter des Knotens daran (z. B. im Vertrag); Formulare, Aufgaben und Regeln lesen sie nicht."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} is a staff input set at the start \u2014 it steers a branch (an "If" node) or fills a node's parameter.`,remedy:'Read it in the condition of an "If" node or bind a node parameter to it (e.g. in the contract); forms, tasks and rules do not read it.'}),"en")},"address/ownerNotWriter":{de:s(e=>({problem:`${e.where}: Die Aufgabe \u201E${e.producer}\u201C schreibt ${e.address} nicht.`,remedy:"W\xE4hle den Wert \xFCber seinen Schl\xFCssel; die schreibende Aufgabe folgt daraus."}),"de"),en:s(e=>({problem:`${e.where}: The task "${e.producer}" does not write ${e.address}.`,remedy:"Choose the value by its key; the writing task follows from it."}),"en")},"address/taskOwnerTaken":{de:s(e=>({problem:`${e.where}: Den Aufgaben-Schl\xFCssel gibt es mehrfach (${V_(e.names)}), und eine dieser Aufgaben schreibt Prozesswerte.`,remedy:"Gib der schreibenden Aufgabe einen Schl\xFCssel, den keine andere Aufgabe tr\xE4gt."}),"de"),en:s(e=>({problem:`${e.where}: The task key is used more than once (${B_(e.names)}), and one of these tasks writes process values.`,remedy:"Give the writing task a key no other task carries."}),"en")},"address/notVisible":{de:s(e=>({problem:e.producerNode!==void 0&&e.producerNode!==e.producer?`${e.where}: ${e.address} \u2014 \u201E${e.producer}\u201C h\xE4ngt an \u201E${e.producerNode}\u201C, das nicht auf jedem Weg vor \u201E${e.reader}\u201C liegt.`:`${e.where}: ${e.address} \u2014 \u201E${e.producer}\u201C liegt nicht auf jedem Weg vor \u201E${e.reader}\u201C.`,remedy:`Lies nur, was auf jedem Weg vor \u201E${e.reader}\u201C entsteht, oder ordne die Schritte so, dass der Erzeuger immer vorher l\xE4uft.`}),"de"),en:s(e=>({problem:e.producerNode!==void 0&&e.producerNode!==e.producer?`${e.where}: ${e.address} \u2014 "${e.producer}" hangs on "${e.producerNode}", which does not lie before "${e.reader}" on every path.`:`${e.where}: ${e.address} \u2014 "${e.producer}" does not lie before "${e.reader}" on every path.`,remedy:`Read only what is produced before "${e.reader}" on every path, or order the steps so the producer always runs first.`}),"en")},"address/pathNotInTarget":{de:s(e=>({problem:`${e.where}: ${e.address} \u2014 ${e.producer??"der Erzeuger"} hat dieses Feld nicht.`,remedy:"W\xE4hle ein Feld, das es dort gibt."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} \u2014 ${e.producer??"the producer"} has no such field.`,remedy:"Choose a field that exists there."}),"en")},"address/notExported":{de:s(e=>({problem:`${e.where}: ${e.address} \u2014 das Feld gibt es in ${e.producer??"dem Formular"}, es ist aber nicht exportiert.`,remedy:"Setze am Feld im Formular `export: true` (ein berechnetes Feld braucht dazu `exportType`). Ist es schon exportiert, ist der Stempel des Bundles veraltet: `plexus-cli offer workflow restamp-exports` laufen lassen."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} \u2014 ${e.producer??"the form"} has this field, but it is not exported.`,remedy:"Set `export: true` on the field in the form (a computed field also needs `exportType`). If it is exported already, the bundle's stamp is stale: run `plexus-cli offer workflow restamp-exports`."}),"en")},"address/typeMismatch":{de:s(e=>({problem:`${e.where}: erwartet ${e.expected}, ${e.address} ist ${e.actual}.`,remedy:`W\xE4hle einen Wert vom Typ ${e.expected}.`}),"de"),en:s(e=>({problem:`${e.where}: expects ${e.expected}, ${e.address} is ${e.actual}.`,remedy:`Choose a value of type ${e.expected}.`}),"en")},"address/notFormInstance":{de:s(e=>({problem:`${e.where}: ${e.address} ist kein ganzes Formular.`,remedy:"W\xE4hle das Formular des Knotens, der es anlegt \u2014 ohne Feld, nicht den Knoten, der es \xFCbernimmt."}),"de"),en:s(e=>({problem:`${e.where}: ${e.address} is not a whole form.`,remedy:"Choose the form of the node that creates it \u2014 without a field, not the node that continues it."}),"en")},"address/mixedForms":{de:s(e=>({problem:`${e.where}: Die Liste liest Felder aus mehreren Formularen (${V_(e.names)}), beurteilt wird sie aber an einem Formular.`,remedy:"W\xE4hle alle Felder dieser Liste aus demselben Formular."}),"de"),en:s(e=>({problem:`${e.where}: The list reads fields of several forms (${B_(e.names)}) but is judged on one.`,remedy:"Choose every field of this list from the same form."}),"en")},"workItems/keyFormat":{de:s(e=>({problem:`${e.where}: Der Aufgaben-Schl\xFCssel \u201E${e.address}\u201C hat nicht die Form ^[a-z][a-zA-Z0-9_]*$.`,remedy:"Benenne die Aufgabe in camelCase um, z. B. \u201EgeschwisterRang\u201C."}),"de"),en:s(e=>({problem:`${e.where}: The task key "${e.address}" does not match ^[a-z][a-zA-Z0-9_]*$.`,remedy:'Rename the task in camelCase, e.g. "siblingRank".'}),"en")}};function Ws(e,n,t){let{problem:r,remedy:i}=R1[e][t](n);return`[${e}] ${r} ${i}`}s(Ws,"addressMessage");var U_={type:"enum",dataType:"option"};function G_(e,n){return e.enumOptionLabels?.[n]??{de:n,en:n}}s(G_,"inlineEnumOptionLabel");var W_={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function cp(e){return W_[e]!==void 0}s(cp,"isExportableFieldType");function I1(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(I1,"leafForComputed");function z_(e){let n=W_[e.type];return n===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:n,label:e.label,...e.enumOptions!==void 0?{enumOptions:e.enumOptions.map(t=>({value:t,label:G_(e,t)}))}:{}}}s(z_,"leafFor");function Tw(e){let n=[],t=s(r=>{for(let i of r.fields)i.export===!0&&n.push(z_(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&n.push(z_(o));for(let i of r.computed??[])i.export===!0&&n.push(I1(i));for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(Tw,"exportedFormLeaves");function nr(e){let n=[];for(let t of e){let r=t.next;if(r)for(let[i,o]of Object.entries(r))n.push({id:`${t.id}|${i}`,source:t.id,target:o.to,sourceBranchId:i})}return n}s(nr,"derivedEdges");function $w(e){let n=new Map;for(let t of nr(e.nodes)){let r=n.get(t.source)??[];r.push(t.target),n.set(t.source,r)}return n}s($w,"successorsOf");function Ys(e,n,t){if(n===t)return!0;let r=$w(e),i=new Set([...r.values()].flat()),o=e.nodes.filter(l=>!i.has(l.id)&&l.id!==n).map(l=>l.id),a=new Set(o);for(;o.length>0;){let l=o.shift();if(l===t)return!1;for(let d of r.get(l)??[])d===n||a.has(d)||(a.add(d),o.push(d))}return!0}s(Ys,"dominates");function Y_(e,n,t){if(n===t)return!0;let r=$w(e),i=[n],o=new Set(i);for(;i.length>0;){let a=i.shift();for(let l of r.get(a)??[]){if(l===t)return!0;o.has(l)||(o.add(l),i.push(l))}}return!1}s(Y_,"reaches");function H_(e,n,t,r){let i=new Map(e.nodes.map(d=>[d.id,d])),o=$w(e),a=[n],l=new Set(a);for(;a.length>0;){let d=a.shift();for(let c of o.get(d)??[]){if(l.has(c)||t.has(c))continue;l.add(c);let u=i.get(c);if(u!==void 0&&r(u))return c;a.push(c)}}return null}s(H_,"reachedAvoiding");function Rw(e,n){let t=[],r=s(i=>({address:i.address,type:i.type,...i.label!==void 0?{label:i.label}:{},nodeId:i.nodeId}),"toVisible");for(let i of e.nodes)if(Ys(e,i.id,n))for(let o of Vr(e,i))t.push(r(o));for(let i of KO)t.push({address:{scope:"env",key:i},type:tw(i),label:rw(i),nodeId:null});for(let i of Df(e))t.push({address:{scope:"env",key:Ff(i.key)},type:i.type,label:i.label,nodeId:null});return t}s(Rw,"visibleAddressesAt");function Ur(e,n){let t=e?.readinessFormFieldsByFormNode?.get(n.owner);if(t!==void 0)return t.get(n.path)??null}s(Ur,"formFieldEntryOf");var J_={binding:{de:"Eingang",en:"Input"},condition:{de:"Bedingung",en:"Condition"},nodeReads:{de:"Gelesene Felder",en:"Fields read"},requires:{de:"Geforderte Felder",en:"Required fields"},adoptForm:{de:"\xDCbernommenes Formular",en:"Continued form"},setFlagTarget:{de:"Freizuschaltendes Formular",en:"Form to unlock"},form:{de:"Formular",en:"Form"},contract:{de:"Vertrag",en:"Contract"},payment:{de:"Zahlung",en:"Payment"},taskWhen:{de:"Bedingung",en:"Condition"},optionalActionWhen:{de:"Bedingung der optionalen Aktion",en:"Condition of the optional action"},taskReads:{de:"Gelesene Felder der Aufgabe",en:"Fields the task reads"},taskDocument:{de:"Dokumente",en:"Documents"},familyRequestFields:{de:"Nachforderbare Felder",en:"Requestable fields"},familyRequestFrom:{de:"Nachforderung aus",en:"Request from"},suggest:{de:"Vorschlag",en:"Suggestion"},taskInput:{de:"Vorgaben",en:"Inputs"},teamWhen:{de:"Bedingung des Teams",en:"Condition of the team"}},O1=new Set(["nodeReads","requires","taskReads","taskDocument","familyRequestFields"]);function _1(e,n,t){let r=[];n.taskKey!==void 0&&r.push(`${t==="de"?"Aufgabe":"task"} \u201E${Io(e,n.taskKey,t)}\u201C`);let i=n.kind==="binding"?` \u201E${n.at.split(".").pop()}\u201C`:"";return r.push(`${J_[n.kind][t]}${i}`),r.join(" \u203A ")}s(_1,"addressFieldWhere");function Vl(e,n,t){let r=_1(e,n,t);return`\u201E${_e(e,n.nodeId,t)}\u201C \u203A ${r}`}s(Vl,"whereOf");function Q_(e,n,t){if(n.scope==="node")return _e(e,n.owner,t);if(n.scope==="task")return Io(e,n.owner,t)}s(Q_,"producerName");function Z_(e,n){let t=[],r=new Set,i=s((l,d,c)=>{let u={de:Ws(l,c("de"),"de"),en:Ws(l,c("en"),"en")},p=`${d}|${u.de}`;r.has(p)||(r.add(p),t.push({layer:"GRAPH",kind:"nodeRule",path:d,reason:u,severity:"error"}))},"report"),o=new Map(e.nodes.map(l=>[l.id,l])),a=[...e.nodes.flatMap(l=>Nl(l))];for(let l of a){let d=s(c=>Vl(e,l,c),"where");for(let c of P1(e,l,i))C1(e,l,c,i)&&(F1(e,l,c,n,i),sw.has(l.kind)&&!q1(o,c)&&i("address/notFormInstance",l.at,u=>({where:d(u),address:je(e,c,u)})))}return K1(e,i),j1(e,a,i),G1(e,i),W1(e,i),t}s(Z_,"checkAddresses");function P1(e,n,t){let r=s(i=>Vl(e,n,i),"where");if(aw(n)){let i=lw(n.value)??[];for(let o of i)o.address===null&&t(o.reason==="bareIdentifier"?"address/bareIdentifier":"address/shape",n.at,a=>({where:r(a),address:o.identifier}));return Vs(n)}return typeof n.value=="string"?(t("address/bareIdentifier",n.at,i=>({where:r(i),address:n.value})),[]):we(n.value)?[n.value]:(t("address/shape",n.at,i=>({where:r(i),address:JSON.stringify(n.value)??"undefined"})),[])}s(P1,"checkFieldShape");function X_(e,n,t,r){let i=Q_(e,t,r);return{where:Vl(e,n,r),address:je(e,t,r),...i!==void 0?{producer:i}:{}}}s(X_,"addressParams");function N1(e,n,t){return nw(n)||t==="optionalActionWhen"&&(Cs(e,n)!==void 0||Zt(n))?null:Cs(e,n)!==void 0?t==="condition"||t==="binding"?null:"address/staffInputConditionOnly":Zt(n)?"address/envCohortBound":"address/unknownKey"}s(N1,"envAddressRefusal");function C1(e,n,t,r){let i=s(o=>X_(e,n,t,o),"params");switch(t.scope){case"env":{let o=N1(e,t.key,n.kind);return o===null?!0:(r(o,n.at,i),!1)}case"task":return e.nodes.some(a=>(a.tasks??[]).some(l=>l.key===t.owner))?(e.processStore??[]).some(a=>a.key===t.key)?ci(e,t.owner,t.key)===null?(r("address/ownerNotWriter",n.at,i),!1):!0:(r("address/unknownKey",n.at,i),!1):(r("address/unknownOwner",n.at,i),!1);case"node":{let o=e.nodes.find(a=>a.id===t.owner);return o===void 0?(r("address/unknownOwner",n.at,i),!1):Vr(e,o).some(a=>a.address.scope==="node"&&a.address.key===t.key)?!0:(r(sw.has(n.kind)&&At(o)?"address/notFormInstance":"address/unknownKey",n.at,i),!1)}}}s(C1,"resolves");function D1(e,n){return e===void 0||n===void 0||rt(n)===void 0?!0:rt(e)!==void 0&&Zf(e,n)}s(D1,"addressTypeFits");function F1(e,n,t,r,i){let o=s(l=>X_(e,n,t,l),"params");if(t.scope!=="env"&&t.path!==void 0&&!M1(e,n,t,r)){i(L1(t,r)?"address/notExported":"address/pathNotInTarget",n.at,o);return}if(n.expectedType===void 0)return;let a=Cl(e,t);D1(a,n.expectedType)||i("address/typeMismatch",n.at,l=>({...o(l),expected:n.expectedType,actual:a}))}s(F1,"checkPathAndType");function L1(e,n){if(e.scope!=="node"||e.key!==Mn||e.path===void 0)return!1;let t=Ur(n,{scope:"node",owner:e.owner,key:Mn,path:e.path});return t==null?!1:t.kind==="computed"||!t.repeated&&cp(t.type)}s(L1,"formFieldUnexported");function M1(e,n,t,r){if(t.scope!=="node")return!1;if(Cl(e,t)!==void 0)return!0;if(t.key!==Mn)return!1;if(!O1.has(n.kind))return e.nodes.find(o=>o.id===t.owner)?.formExports===void 0;let i=r?.readinessFormFieldsByFormNode?.get(t.owner);return i===void 0||i.has(t.path)}s(M1,"pathExists");function q1(e,n){if(!Sr(n))return!1;let t=e.get(n.owner);return t!==void 0&&t.type==="form"&&!At(t)}s(q1,"isCreatingFormInstance");function K1(e,n){for(let t of e.nodes){let r=new Set(Nl(t).map(i=>i.kind));for(let i of UO(t))r.has(i)||n("address/missing",`nodes.${t.id}.${i}`,o=>({where:`\u201E${_e(e,t.id,o)}\u201C \u203A ${J_[i][o]}`}))}}s(K1,"checkRequiredFields");function j1(e,n,t){let r=new Map;for(let i of n)if(i.judgedTogether!==null)for(let o of Vs(i)){if(o.scope!=="node"||o.key!==Mn)continue;let a=r.get(i.judgedTogether)??[];a.push({field:i,owner:o.owner}),r.set(i.judgedTogether,a)}for(let[i,o]of r){let a=[...new Set(o.map(l=>l.owner))];a.length<2||t("address/mixedForms",i,l=>({where:Vl(e,o[0].field,l),names:a.map(d=>_e(e,d,l))}))}}s(j1,"checkMixedForms");function V1(e,n){return e.type==="engagePush"&&n.kind==="payment"}s(V1,"readSkipsAbsentProducer");function B1(e,n,t){return n!==t&&Y_(e,n,t)}s(B1,"precedesOnSomePath");function U1(e,n,t,r){let i=iw(t.address);return r.has(de(i))||!z1(e,i)?!0:t.origin==="written"&&i.scope==="node"&&V1(n,t.field)&&B1(e,i.owner,n.id)}s(U1,"readPassesVisibility");function G1(e,n){for(let t of e.nodes){let r=Ro(e,t);if(r.length===0)continue;let i=new Set(Rw(e,t.id).map(o=>de(o.address)));for(let o of r){let a=iw(o.address);if(U1(e,t,o,i))continue;let l=a.scope==="task"?ci(e,a.owner,a.key):a.scope==="node"?a.owner:null;n("address/notVisible",o.field.at,d=>({where:Vl(e,o.field,d),address:je(e,o.address,d),producer:Q_(e,a,d)??je(e,a,d),...l!==null?{producerNode:_e(e,l,d)}:{},reader:_e(e,t.id,d)}))}}}s(G1,"checkVisibility");function z1(e,n){if(n.scope==="env")return nw(n.key);let t=de(n);return e.nodes.some(r=>Vr(e,r).some(i=>de(i.address)===t))}s(z1,"producedSomewhere");function W1(e,n){let t=new Map;for(let r of e.nodes){let i=new Set(Vr(e,r).flatMap(o=>o.address.scope==="task"?[o.address.owner]:[]));for(let[o,a]of(r.tasks??[]).entries()){let l=a.key;if(typeof l!="string"||!Di.test(l)){n("workItems/keyFormat",`nodes.${r.id}.tasks.${o}.key`,c=>({where:`\u201E${_e(e,r.id,c)}\u201C`,address:String(l)}));continue}let d=t.get(l)??[];d.push({nodeId:r.id,writes:i.has(l)}),t.set(l,d)}}for(let[r,i]of t)if(!(i.length<2||!i.some(o=>o.writes)))for(let o of i)n("address/taskOwnerTaken",`nodes.${o.nodeId}.tasks.${r}`,a=>({where:`\u201E${_e(e,o.nodeId,a)}\u201C \u203A ${a==="de"?"Aufgabe":"task"} \u201E${Io(e,r,a)}\u201C`,names:i.map(l=>_e(e,l.nodeId,a))}))}s(W1,"checkTaskKeys");function up(e,n){return e.label[n]??""}s(up,"wordingIn");function Vi(e,n){let t=eP(e,n),r=up(e.qualifier,n);return t===""||r===""&&up(e.qualifier,"de")!==""?"":r===""?t:`${r} \xB7 ${t}`}s(Vi,"fieldLabelIn");function eP(e,n){return up(e,n)}s(eP,"fieldOwnLabelIn");function Hs(e){return{key:e.key,kind:e.kind,type:e.kind==="entered"?e.type:null,repeated:e.kind==="entered"&&e.repeated,reviewRequired:e.kind==="entered"&&e.reviewRequired,name:{de:Vi(e,"de"),en:Vi(e,"en")}}}s(Hs,"catalogField");function Js(e,n){switch(e){case"nodeReads":return n.repeated?"repeated":null;case"requires":return n.repeated?"repeated":n.kind==="computed"?"computed":n.name.en===""?"untranslated":null;case"taskDocument":return n.repeated?"repeated":n.kind==="entered"&&n.type==="docRef"?null:"notDocument";case"taskReads":case"familyRequestFields":return null}}s(Js,"catalogFieldRefusal");function fp(e,n){let t=e.buses.find(r=>r.key===n);return t||F(`[progress] layout '${e.id}' has no bus '${n}'`),t}s(fp,"progressBus");function Bl(e,n){return e.states.some(t=>t.id===n)}s(Bl,"isBusState");function nP(e,n){let t=e.terminalSemantics?.[n];return t||F(`[progress] no terminal semantics for state '${n}' on bus '${e.key}'`),t}s(nP,"terminalSemantics");function pp(e,n){return!!e.terminalSemantics&&Object.prototype.hasOwnProperty.call(e.terminalSemantics,n)}s(pp,"hasTerminalSemantics");function Y1(e,n){return(e.boards??[]).find(t=>t.audience===n||t.audience==="both")??null}s(Y1,"boardForAudience");function tP(e){return Y1(fp(e,"process"),"internal")}s(tP,"internalProcessBoard");function Qs(e,n,t){let r=null;for(let i of e.mappings)if(i.event===t)if("nodeId"in i.match){if(i.match.nodeId===n.id)return{bus:i.bus,state:i.state}}else i.match.nodeType===n.type&&(r=i);return r?{bus:r.bus,state:r.state}:null}s(Qs,"resolveProgressEvent");var Zs={approved:"enrolled",rejected:"declined",withdrawn:"declined",expired:"declined"},ui=Object.keys(Zs);function Po(e){return Object.hasOwn(Zs,e)}s(Po,"isEndNodeOutcome");var Iw={approved:{de:"Angenommen",en:"Admitted"},rejected:{de:"Abgelehnt",en:"Rejected"},withdrawn:{de:"Zur\xFCckgezogen",en:"Withdrawn"},expired:{de:"Abgelaufen",en:"Expired"}};var Bi=["commit","discard"],lme=m.union(...Bi.map(e=>m.literal(e)));function mp(e){return typeof e=="string"&&Bi.includes(e)}s(mp,"isApplicationDataDecision");function qn(e){return Object.keys(e)}s(qn,"progressEventsOf");var te=s((e,n)=>({de:e,en:n}),"lt"),en=s((e,n,t,r,i=null,o=null)=>({chipLabel:e,tone:n,nextAction:i,affordance:o,title:t,body:r}),"ex"),rP={key:"eingeschrieben",label:te("Eingeschrieben","Enrolled"),scope:"global",defaultCollapsed:!0},hp={key:"abgesagt",label:te("Abgesagt","Declined"),scope:"global",track:"exit",defaultCollapsed:!0},iP={key:"abgelehnt",label:te("Abgelehnt","Rejected"),scope:"global",track:"exit",defaultCollapsed:!0};var oP={enrolled:{label:te("Eingeschrieben","Enrolled"),tone:"green",terminal:{lifecycleStatus:"completed",outcome:"approved"},phase:rP,external:en(te("Eingeschrieben","Enrolled"),"green",te("Sie sind eingeschrieben!","You are enrolled!"),te("Ihre Anmeldung ist abgeschlossen und Ihr Platz ist gesichert. Wir freuen uns auf Sie.","Your enrolment is complete and your place is secured. We look forward to welcoming you."))},declined:{label:te("Abgesagt","Declined"),tone:"red",terminal:{lifecycleStatus:"completed",outcome:"rejected"},phase:hp,external:en(te("Abgesagt","Declined"),"red",te("Die Bewerbung wurde beendet","The application has ended"),te("Ihre Bewerbung wurde nicht fortgef\xFChrt.","Your application was not continued."))}},sP={role:"effect",effect:"pure",progressDefaults:oP,progressEvents:qn(oP),inputs:s(()=>[{id:"applicationOutcome",label:{de:"Ergebnis",en:"Outcome"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:ui.map(e=>({value:e,label:Iw[e]}))},{id:"dataDecision",label:{de:"Erfasste Daten",en:"Captured data"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"commit",label:{de:"\xDCbernehmen",en:"Keep"}},{value:"discard",label:{de:"Verwerfen",en:"Discard"}}]}],"inputs"),notificationEvents:s(()=>[{id:"reached",label:{de:"Verfahren abgeschlossen",en:"Process completed"},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"outcome",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>[...H1(e),...J1(e),...Q1(e)],"validate")},Xs=s((e,n,t,r)=>({layer:"GRAPH",kind:"nodeRule",path:`node.${e.id}.inputs.${n}`,reason:{de:t,en:r},severity:"error"}),"nodeIssue");function No(e){let n=e.inputs?.applicationOutcome;return n?.kind==="literal"&&n.value!=null?String(n.value):null}s(No,"literalOutcome");function H1(e){if(e.type!=="end")return[];let n=e.inputs?.applicationOutcome;if(n===void 0||n.kind==="unset")return[];let t=No(e);return t===null?[Xs(e,"applicationOutcome",`[end/applicationOutcome] ${e.label.de}: das Ergebnis ist kein fester Wert \u2014 die Engine kann den Abschluss nicht ableiten`,`[end/applicationOutcome] ${e.label.en}: the application outcome is no fixed value \u2014 the engine cannot derive the terminal`)]:Po(t)?[]:[Xs(e,"applicationOutcome",`[end/applicationOutcome] ${e.label.de}: '${t}' ist kein Ausgang eines Endknotens (${ui.join("|")}) \u2014 die Warteliste endet \xFCber das closed-Outcome ihres Wartelistenknotens`,`[end/applicationOutcome] ${e.label.en}: '${t}' is not an outcome of an end node (${ui.join("|")}) \u2014 the waitlist ends through the closed outcome of its waitlist node`)]}s(H1,"checkEndApplicationOutcome");function J1(e){if(e.type!=="end")return[];let n=e.inputs?.dataDecision;return!n||n.kind!=="literal"||n.value==null?[Xs(e,"dataDecision",`[end/dataDecision] ${e.label.de}: dataDecision fehlt \u2014 der Endknoten muss festlegen, ob die erfassten Daten \xFCbernommen (commit) oder verworfen (discard) werden`,`[end/dataDecision] ${e.label.en}: dataDecision is missing \u2014 the end node must decide whether the collected data is kept (commit) or discarded (discard)`)]:mp(n.value)?[]:[Xs(e,"dataDecision",`[end/dataDecision] ${e.label.de}: dataDecision '${String(n.value)}' ist ung\xFCltig (${Bi.join("|")})`,`[end/dataDecision] ${e.label.en}: dataDecision '${String(n.value)}' is invalid (${Bi.join("|")})`)]}s(J1,"checkEndDataDecision");function Q1(e){if(e.type!=="end")return[];let n=No(e);if(n===null||!Po(n)||n==="approved")return[];let t=e.inputs?.dataDecision;if(t?.kind!=="literal"||t.value!=="commit")return[];let r=Iw[n];return[{...Xs(e,"dataDecision",`[end/commitWithoutApproval] ${e.label.de}: Ende ohne Zusage \xFCbernimmt die erfassten Daten (commit) \u2014 Personen und Beziehungen bleiben nach dem Ergebnis \u201E${r.de}" bestehen. Gewollt? Sonst discard.`,`[end/commitWithoutApproval] ${e.label.en}: end without admission keeps the captured data (commit) \u2014 persons and relationships remain after the outcome "${r.en}". Intended? Otherwise discard.`),severity:"warning"}]}s(Q1,"checkEndCommitWithoutApproval");function aP(e,n){if(!n?.layout||!n.wiring)return[];let t=[];for(let r of e.nodes){if(r.type!=="end")continue;let i=No(r);if(i===null||!Po(i))continue;let o=Zs[i],a=Qs(n.wiring,r,o);if(a===null)continue;let l=n.layout.buses.find(c=>c.key===a.bus);if(l===void 0||!pp(l,a.state))continue;let d=nP(l,a.state).outcome;d!==i&&t.push(Xs(r,"applicationOutcome",`[end/outcomeMismatch] ${r.label.de}: das Ergebnis \u201E${i}" passt nicht zum Endzustand \u201E${a.state}" (Bus ${a.bus}), der \u201E${String(d)}" besiegelt \u2014 Ergebnis oder Verdrahtung angleichen.`,`[end/outcomeMismatch] ${r.label.en}: the outcome "${i}" does not match the final state "${a.state}" (bus ${a.bus}), which seals "${String(d)}" \u2014 align the outcome or the wiring.`))}return t}s(aP,"checkEndOutcomeMatchesTerminal");function ea(e){let n=Je(e);return typeof n.inputs=="function"?n.inputs(e):[]}s(ea,"inputSlots");function Z1(e,n){return ea(e).find(t=>t.id===n)}s(Z1,"findInputSlot");function X1(e,n){let t=Z1(e,n);if(!t)return{source:"missing",spec:{id:n,label:{de:n,en:n},type:"string"},unknownSlot:!0};let r=e.inputs?.[n]??{kind:"unset"};return r.kind==="binding"&&we(r.address)?{source:"binding",spec:t,address:r.address}:r.kind==="literal"?{source:"literal",spec:t,value:r.value}:r.kind==="cockpit"&&t.deferrable===!0?{source:"cockpit",spec:t}:t.defaultValue!==void 0?{source:"default",spec:t,value:t.defaultValue}:t.required?{source:"missing",spec:t}:{source:"optional",spec:t}}s(X1,"resolveInput");function lP(e){return ea(e).filter(n=>X1(e,n.id).source==="missing")}s(lP,"missingRequiredInputs");var e2=["personRef","formRef","documentRef","docRef"];function n2(e){let n=Je(e);return typeof n.inputs!="function"?[]:n.inputs(e).map(t=>({id:t.id,type:t.type}))}s(n2,"listInputs");function dP(e){let n=[];for(let t of e.nodes)for(let r of n2(t))!e2.includes(r.type)||t.inputs?.[r.id]?.kind!=="literal"||n.push({layer:"GRAPH",kind:"modelError",path:`node.${t.id}.param.${r.id}`,reason:{de:`${t.label.de}: Literal f\xFCr referenztypisierten Slot "${r.id}" ist verboten \u2014 der Slot wird an eine Adresse gebunden`,en:`${t.label.en}: A literal for the reference-typed slot "${r.id}" is not allowed \u2014 the slot is bound to an address`},severity:"error"});return n}s(dP,"findParamValueRefSlotErrors");function cP(e){let n=[];for(let t of e.nodes){let r=Je(t);if(typeof r.inputs=="function")for(let i of r.inputs(t)){let o=t.inputs?.[i.id];if(o?.kind==="cockpit"&&i.deferrable!==!0){n.push({layer:"GRAPH",kind:"modelError",path:`nodes.${t.id}.inputs.${i.id}`,reason:{de:`[inputs/notDeferrable] ${t.label.de}: Parameter \u201E${i.label.de}\u201C l\xE4sst sich nicht im Cockpit erg\xE4nzen \u2014 nur Parameter eines Generators oder einer Vorlage.`,en:`[inputs/notDeferrable] ${t.label.en}: Parameter "${i.label.en}" cannot be completed in the cockpit \u2014 only parameters of a generator or a template can.`},severity:"error"});continue}(i.inspector==="literal-only"&&o?.kind==="binding"||i.inspector==="binding-only"&&o?.kind==="literal")&&n.push({layer:"GRAPH",kind:"modelError",path:`nodes.${t.id}.inputs.${i.id}`,reason:i.inspector==="literal-only"?{de:`[inputs/inspectorKind] ${t.label.de}: Parameter \u201E${i.label.de}\u201C ist ein fester Wert \u2014 eine Bindung an eine Adresse ist hier nicht m\xF6glich.`,en:`[inputs/inspectorKind] ${t.label.en}: Parameter "${i.label.en}" is a fixed value \u2014 it cannot be bound to an address.`}:{de:`[inputs/inspectorKind] ${t.label.de}: Parameter \u201E${i.label.de}\u201C wird an eine Adresse gebunden \u2014 ein fester Wert ist hier nicht m\xF6glich.`,en:`[inputs/inspectorKind] ${t.label.en}: Parameter "${i.label.en}" is bound to an address \u2014 a fixed value is not possible here.`},severity:"error"})}}return n}s(cP,"findInspectorKindErrors");function uP(e){let n=[];for(let t of e.nodes)for(let r of lP(t))n.push({layer:"GRAPH",kind:"contractGap",path:`node.${t.id}.input.${r.id}`,reason:{de:`${t.label.de}: Pflicht-Slot "${r.label.de}" nicht gesetzt`,en:`${t.label.en}: Required slot "${r.label.en}" is not set`},severity:"error"});return n}s(uP,"findMissingRequiredInputs");function gp(e){let n=e.processStore;return n===void 0?[]:(Array.isArray(n)||F("graph.processStore must be an array \u2014 the graph validator refuses anything else"),n)}s(gp,"processStoreKeys");function fP(e){let n=[];for(let t of e.tasks??[]){let r=t.result;if(!(r===void 0||!qs(r)))for(let i of Gf(r))n.push({key:i.key,nodeId:e.id,taskKey:t.key,template:t,result:r,valueType:i.valueType,...i.field!==void 0?{fieldKey:i.field.key}:{}})}return n}s(fP,"storeWritersOn");function pP(e){let n=new Map;for(let t of e.nodes)for(let r of fP(t)){let i=n.get(r.key)??[];i.push(r),n.set(r.key,i)}return n}s(pP,"processStoreWriters");function t2(e,n,t){for(let r of e.nodes){let i=fP(r).find(o=>o.taskKey===n&&o.key===t);if(i!==void 0)return i}return null}s(t2,"writerAt");function r2(e,n,t){(n.scope!=="task"||n.path!==void 0)&&F(`[process] ${t}: ${de(n)} is no task value`);let r=t2(e,n.owner,n.key);return r===null&&F(`[address/ownerNotWriter] ${t}: task "${n.owner}" writes no "${n.key}" \u2014 publish refuses that`),{key:n.key,nodeId:r.nodeId,taskKey:r.taskKey,...r.fieldKey!==void 0?{fieldKey:r.fieldKey}:{}}}s(r2,"sourceOfAddress");function mP(e,n){(n.scope!=="task"||n.path!==void 0)&&F(`[process] ${de(n)} is no store address`);let t=gp(e).find(r=>r.key===n.key);return t===void 0&&F(`[address/unknownKey] ${de(n)}: "${n.key}" is not declared in processStore`),{key:t.key,type:t.type,label:t.label,audience:t.audience,source:r2(e,n,de(n))}}s(mP,"processLeafOf");var Ow=new Set(["enum","pricedItem","number","boolean","reduction","string","staffUser","staffUserList","taskAssignment"]),pt={invalidKey:"[process/invalidKey]",unknownKey:"[process/unknownKey]",secondWriter:"[process/secondWriter]",noWriter:"[process/noWriter]",writerTypeMismatch:"[process/writerTypeMismatch]",pricedItemWritesNothing:"[process/pricedItemWritesNothing]",internalInDocument:"[process/internalInDocument]",writerMustBlock:"[process/writerMustBlock]",absentWithoutDefault:"[process/absentWithoutDefault]",defaultItemMismatch:"[process/defaultItemMismatch]"};function mt(e,n,t,r){return{layer:"GRAPH",kind:"contractGap",path:e,reason:{de:`${n} ${t}`,en:`${n} ${r}`},severity:"error"}}s(mt,"err");function gP(e){let n=[],t=gp(e),r=new Map(t.map(l=>[l.key,l])),i=new Set;for(let[l,d]of t.entries()){let c=`processStore[${l}]`;if(typeof d.key!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(d.key)){n.push(mt(c,pt.invalidKey,`Vorgangs-Schl\xFCssel ${JSON.stringify(d.key)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,`Process key ${JSON.stringify(d.key)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`));continue}i.has(d.key)&&n.push(mt(c,pt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}" ist doppelt deklariert.`,`Process key "${d.key}" is declared twice.`)),i.add(d.key),Ow.has(d.type)||n.push(mt(c,pt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}" hat den Typ "${d.type}" \u2014 der Vorgang speichert nur Ergebnisse mit Wert: ${[...Ow].join(", ")}.`,`Process key "${d.key}" has the type "${d.type}" \u2014 the process only stores results with a value: ${[...Ow].join(", ")}.`)),(!d.label?.de?.trim()||!d.label?.en?.trim())&&n.push(mt(c,pt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}" braucht ein Label in beiden Sprachen.`,`Process key "${d.key}" needs a label in both languages.`)),d.audience!=="internal"&&d.audience!=="printable"&&n.push(mt(c,pt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}": audience muss 'internal' oder 'printable' sein.`,`Process key "${d.key}": audience must be 'internal' or 'printable'.`))}let o=pP(e);for(let l of e.nodes)for(let d of l.tasks??[]){let c=d.result;c?.kind==="pricedItem"&&c.writes===void 0&&n.push(mt(`node.${l.id}.tasks.${d.key}.result.writes`,pt.pricedItemWritesNothing,`Aufgabe "${d.key}" (Knoten "${l.id}") bepreist einen Artikel, schreibt das Ergebnis aber in keinen Vorgangs-Schl\xFCssel ('result.writes') \u2014 niemand k\xF6nnte den Preis lesen.`,`Task "${d.key}" (node "${l.id}") prices an article but writes the result to no process key ('result.writes') \u2014 nobody could read the price.`))}for(let[l,d]of o){let c=r.get(l);for(let u of d){let p=u.fieldKey===void 0?`node.${u.nodeId}.tasks.${u.taskKey}.result.writes`:`node.${u.nodeId}.tasks.${u.taskKey}.result.fields.${u.fieldKey}.writes`;if(c===void 0){n.push(mt(p,pt.unknownKey,`${u.fieldKey===void 0?"":`Feld "${u.fieldKey}" der `}Aufgabe "${u.taskKey}" schreibt "${l}", aber der Workflow deklariert keinen solchen Vorgangs-Schl\xFCssel (graph.processStore).`,`${u.fieldKey===void 0?"Task":`Field "${u.fieldKey}" of task`} "${u.taskKey}" writes "${l}", but the workflow declares no such process key (graph.processStore).`));continue}if(u.valueType!==c.type){let h=u.fieldKey===void 0?`Aufgabe "${u.taskKey}"`:`Feld "${u.fieldKey}" der Aufgabe "${u.taskKey}"`,w=u.fieldKey===void 0?`Task "${u.taskKey}"`:`Field "${u.fieldKey}" of task "${u.taskKey}"`;n.push(mt(p,pt.writerTypeMismatch,`${h} liefert ${u.valueType}, der Vorgangs-Schl\xFCssel "${l}" ist aber als ${c.type} deklariert.`,`${w} delivers ${u.valueType}, but the process key "${l}" is declared as ${c.type}.`))}}if(d.length>1){let u=d.map(p=>`${p.nodeId}/${p.taskKey}${p.fieldKey===void 0?"":`.${p.fieldKey}`}`).join(", ");n.push(mt(`processStore.${l}`,pt.secondWriter,`Vorgangs-Schl\xFCssel "${l}" wird ${d.length}-mal geschrieben (${u}) \u2014 genau ein Schreiber je Schl\xFCssel.`,`Process key "${l}" is written ${d.length} times (${u}) \u2014 exactly one writer per key.`))}}for(let l of t)o.has(l.key)||n.push(mt(`processStore.${l.key}`,pt.noWriter,`Vorgangs-Schl\xFCssel "${l.key}" ist deklariert, aber keine Aufgabe schreibt ihn ('result.writes').`,`Process key "${l.key}" is declared, but no task writes it ('result.writes').`));let a=new Map;for(let l of e.nodes){let d=Je(l),c=typeof d.inputs=="function"?d.inputs(l):[];for(let u of c){let p=l.inputs?.[u.id];if(p?.kind!=="binding")continue;let h=i2(e,p.address);if(h===null)continue;let w=`node.${l.id}.input.${u.id}`,k=de(p.address),y=a.get(h.source.key)??new Set;y.add(l.id),a.set(h.source.key,y),h.audience==="internal"&&n.push(mt(w,pt.internalInDocument,`${l.label.de}: "${u.id}" liest den internen Vorgangs-Schl\xFCssel "${h.key}" \u2014 ein Dokument dieses Knotens geht an die Familie; nur 'printable'-Schl\xFCssel d\xFCrfen hinein.`,`${l.label.en}: "${u.id}" reads the internal process key "${h.key}" \u2014 a document of this node goes to the family; only 'printable' keys may go in.`));let b=o2(o,h.source.key,h.source.taskKey);if(b.template.when!==void 0&&u.required===!0&&u.defaultValue===void 0&&n.push(mt(w,pt.absentWithoutDefault,`${l.label.de}: "${u.id}" ist Pflicht und an ${k} gebunden, aber die schreibende Aufgabe entsteht nur unter einer Bedingung (when: ${hP(b.template.when)}) \u2014 ohne Vorgabewert bliebe das Feld dann f\xFCr immer leer.`,`${l.label.en}: "${u.id}" is required and bound to ${k}, but the writing task only exists under a condition (when: ${hP(b.template.when)}) \u2014 without a default value the field would stay empty forever.`)),b.result.kind==="pricedItem"&&u.defaultValue!==void 0){let E=u.defaultValue;(!Mi(E)||E.itemKey!==b.result.item||E.grantKeys.length>0)&&n.push(mt(w,pt.defaultItemMismatch,`${l.label.de}: der Vorgabewert von "${u.id}" muss der Artikel der schreibenden Aufgabe ohne Erm\xE4\xDFigung sein ({ itemKey: '${b.result.item??"?"}', grantKeys: [] }) \u2014 sonst rechnete die Familie ohne Antrag einen anderen Artikel als mit.`,`${l.label.en}: the default value of "${u.id}" must be the article of the writing task without a reduction ({ itemKey: '${b.result.item??"?"}', grantKeys: [] }) \u2014 otherwise the family would be charged a different article without an application than with one.`))}}}for(let[l,d]of a){let c=o.get(l)[0],u=c.template.blocks,p=u===void 0?void 0:u.node??c.nodeId,h=p!==void 0&&(()=>{let k=e.nodes.find(y=>y.id===p);return k!==void 0&&Je(k).processHoldTemplate?.(k)===u.templateKey})(),w=`node.${c.nodeId}.tasks.${c.taskKey}.blocks`;if(!h){let k=[...d][0],y=e.nodes.find(E=>E.id===k),b=Je(y).processHoldTemplate?.(y)??"?";n.push(mt(w,pt.writerMustBlock,`Die Aufgabe "${c.taskKey}" schreibt "${l}", h\xE4lt aber keinen der lesenden Knoten (${[...d].join(", ")}) zur\xFCck \u2014 sie muss den ersten blockieren, z. B. blocks: { ${k===c.nodeId?"":`node: '${k}', `}templateKey: '${b}' }, sonst arbeitet er, bevor der Wert existiert.`,`The task "${c.taskKey}" writes "${l}" but holds back none of the reading nodes (${[...d].join(", ")}) \u2014 it must block the first one, e.g. blocks: { ${k===c.nodeId?"":`node: '${k}', `}templateKey: '${b}' }, otherwise it works before the value exists.`));continue}for(let k of d)k===p||Ys(e,p,k)||n.push(mt(w,pt.writerMustBlock,`"${k}" liest "${l}", liegt aber nicht hinter dem zur\xFCckgehaltenen Knoten "${p}" \u2014 auf einem Weg an ihm vorbei l\xE4se er den Wert, bevor er feststeht.`,`"${k}" reads "${l}" but does not lie behind the held-back node "${p}" \u2014 on a path past it, it would read the value before it is settled.`))}return n}s(gP,"processBindingIssues");function i2(e,n){return!we(n)||n.scope!=="task"||n.path!==void 0||!gp(e).some(t=>t.key===n.key)||ci(e,n.owner,n.key)===null?null:mP(e,n)}s(i2,"draftLeafOf");function o2(e,n,t){let r=e.get(n)?.find(i=>i.taskKey===t);return r===void 0&&F(`[process] the leaf of "${n}" names task "${t}", which does not write it`),r}s(o2,"writerOf");function hP(e){return we(e)?de(e):JSON.stringify(e)}s(hP,"shown");var s2="Europe/Berlin";function wP(){return s2}s(wP,"tenantTimeZone");var yP=new Map;function a2(e){let n=yP.get(e);if(n)return n;let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{ae("INVALID",{de:`Unbekannte Zeitzone "${e}".`,en:`Unknown time zone "${e}".`})}return yP.set(e,t),t}s(a2,"formatterFor");function l2(e,n){let t=new Map(a2(e).formatToParts(new Date(n)).map(a=>[a.type,a.value])),r=s(a=>{let l=t.get(a);return l===void 0&&F(`Zeitzone "${e}" liefert kein Feld ${a}.`),Number(l)},"read"),i=r("hour")%24;return Date.UTC(r("year"),r("month")-1,r("day"),i,r("minute"),r("second"))-Math.floor(n/1e3)*1e3}s(l2,"zoneOffsetAt");function _w(e,n){let t=e+l2(n,e);return{wallClock:new Date(t).toISOString().slice(0,19),timeZone:n}}s(_w,"instantToLocalDateTime");function Pw(e){let n={};for(let t of Ye)n[t]=e(t);return n}s(Pw,"localized");var Co=5,Do=480;function fi(e){return typeof e=="string"&&e.trim().length>0}s(fi,"isNonEmptyString");function bP(e,n,t){return Object.keys(e).filter(r=>!n.includes(r)).map(r=>({field:`result.${r}`,code:Ue.unknownField,message:{de:`Unbekanntes Feld '${r}' im ${t.de}; erlaubt sind: ${n.join(", ")}.`,en:`Unknown field '${r}' in the ${t.en}; allowed: ${n.join(", ")}.`}}))}s(bP,"unknownFieldIssues");var yp="primaryHostTeams";function c2(e){let n=[],t=e.title;(t===void 0||typeof t!="object"||t===null||!fi(t.de)||!fi(t.en))&&n.push({field:"result.title",code:Ue.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;(typeof r!="number"||!Number.isInteger(r)||r<Co||r>Do)&&n.push({field:"result.durationMinutes",code:Ue.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Co} bis ${Do} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Co} to ${Do}, got ${JSON.stringify(r)}.`}});let{[yp]:i,...o}=e;return n.push(...bP(o,["kind","title","durationMinutes","primaryParticipantTeams","participants"],{de:"Termin-Ergebnis",en:"appointment result"})),n}s(c2,"appointmentIssues");function kP(e){if(typeof e!="object"||e===null)return!1;let n=e;return fi(n.de)&&fi(n.en)}s(kP,"isBilingual");var Nw=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom","multiple","tasks","maxLength"];function u2(e,n){let t=s((o,a)=>({field:o,code:Ue.recordFields,message:a}),"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 r=[],i=new Set;for(let[o,a]of e.entries()){let l=`result.fields[${o}]`;if(typeof a!="object"||a===null||Array.isArray(a)){r.push(t(l,{de:"Ein Feld der Erfassung muss ein Objekt sein.",en:"A field of the record must be an object."}));continue}let d=a,c=d.key;typeof c!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel ${JSON.stringify(c)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,en:`Field key ${JSON.stringify(c)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`})):i.has(c)?r.push(t(`${l}.key`,{de:`Feld-Schl\xFCssel "${c}" ist doppelt.`,en:`Field key "${c}" is duplicated.`})):i.add(c);let u=typeof c=="string"?`"${c}"`:`Nr. ${o+1}`,p=typeof c=="string"?`"${c}"`:`no. ${o+1}`;if(Hy(d.type)||r.push(t(`${l}.type`,{de:`Feld ${u}: Typ ${JSON.stringify(d.type)} \u2014 erlaubt: ${Bf.join(", ")}.`,en:`Field ${p}: type ${JSON.stringify(d.type)} \u2014 allowed: ${Bf.join(", ")}.`})),kP(d.label)||r.push(t(`${l}.label`,{de:`Feld ${u} braucht ein Label in beiden Sprachen ({ de, en }).`,en:`Field ${p} needs a label in both languages ({ de, en }).`})),fi(d.writes)||r.push(t(`${l}.writes`,{de:`Feld ${u} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`,en:`Field ${p} writes to no process key ('writes') \u2014 a value nobody can read does not belong in a record.`})),d.type==="enum"){let w=Array.isArray(d.options)?d.options:[],k=w.map(y=>y.key);(w.length<2||k.some(y=>typeof y!="string"||y.length===0)||new Set(k).size!==k.length||w.some(y=>!kP(y.label)))&&r.push(t(`${l}.options`,{de:`Feld ${u} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`,en:`Field ${p} (choice) needs at least 2 options with unique keys and labels in both languages.`}))}else d.options!==void 0&&r.push(t(`${l}.options`,{de:`Feld ${u}: 'options' gibt es nur bei Typ 'enum'.`,en:`Field ${p}: 'options' exists only for type 'enum'.`}));if(d.min!==void 0&&(d.type!=="number"||typeof d.min!="number"||!Number.isInteger(d.min))&&r.push(t(`${l}.min`,{de:`Feld ${u}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`,en:`Field ${p}: 'min' exists only for type 'number', as a whole number.`})),d.evidence!==void 0&&typeof d.evidence!="boolean"&&r.push(t(`${l}.evidence`,{de:`Feld ${u}: 'evidence' ist true oder false.`,en:`Field ${p}: 'evidence' is true or false.`})),d.evidenceFrom!==void 0){let w=typeof d.min=="number"?d.min:0;(d.type!=="number"||d.evidence!==!0||typeof d.evidenceFrom!="number"||!Number.isInteger(d.evidenceFrom)||d.evidenceFrom<=w)&&r.push(t(`${l}.evidenceFrom`,{de:`Feld ${u}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${w}) \u2014 sonst g\xE4lte der Nachweis immer.`,en:`Field ${p}: 'evidenceFrom' exists only for type 'number' with 'evidence', as a whole number above the minimum (${w}) \u2014 otherwise the proof would always apply.`}))}if(r.push(...f2(d,l,u,p,n)),d.suggest!==void 0){let w=d.suggest,k=typeof w=="object"&&w!==null?w.kind:void 0,y=k==="form"&&"address"in w&&Object.keys(w).length===2&&(!we(w.address)||un(w.address))||k==="siblingRank"&&Object.keys(w).length===1&&d.type==="number";TO(d.type)?y||r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: Vorschlag ${JSON.stringify(d.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${Jy.join(", ")}.`,en:`Field ${p}: suggestion ${JSON.stringify(d.suggest)} \u2014 allowed: { kind: 'form', address: '$node.<form>.admission.<export>' } or { kind: 'siblingRank' } (only for type 'number'); known kinds: ${Jy.join(", ")}.`}}):r.push({field:`${l}.suggest`,code:Ue.recordSuggest,message:{de:`Feld ${u}: einen Vorschlag gibt es nur bei Typ number, boolean oder enum.`,en:`Field ${p}: a suggestion exists only for type number, boolean or enum.`}})}let h=Object.keys(d).filter(w=>!Nw.includes(w));h.length>0&&r.push(t(l,{de:`Feld ${u}: unbekannte Angabe ${h.map(w=>`'${w}'`).join(", ")}; erlaubt: ${Nw.join(", ")}.`,en:`Field ${p}: unknown entry ${h.map(w=>`'${w}'`).join(", ")}; allowed: ${Nw.join(", ")}.`}))}return r}s(u2,"recordFieldIssues");function f2(e,n,t,r,i){let o=[],a=e.maxLength;if(a!==void 0&&(e.type!=="text"||typeof a!="number"||!Number.isInteger(a)||a<1||a>Uf)&&o.push({field:`${n}.maxLength`,code:Ue.recordText,message:{de:`Feld ${t}: 'maxLength' gibt es nur bei Typ 'text', als ganze Zahl von 1 bis ${Uf}.`,en:`Field ${r}: 'maxLength' exists only for type 'text', as a whole number from 1 to ${Uf}.`}}),e.multiple!==void 0&&(e.type!=="person"||typeof e.multiple!="boolean")&&o.push({field:`${n}.multiple`,code:Ue.recordPerson,message:{de:`Feld ${t}: 'multiple' gibt es nur bei Typ 'person', als true oder false.`,en:`Field ${r}: 'multiple' exists only for type 'person', as true or false.`}}),e.type!=="assignment")return e.tasks!==void 0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t}: 'tasks' gibt es nur bei Typ 'assignment'.`,en:`Field ${r}: 'tasks' exists only for type 'assignment'.`}}),o;let l=e.tasks;if(!Array.isArray(l)||l.length===0||l.some(d=>typeof d!="string"||d.length===0)||new Set(l).size!==l.length)return o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:{de:`Feld ${t} (Zuordnung) braucht in 'tasks' mindestens eine Aufgabe, jede einmal.`,en:`Field ${r} (assignment) needs at least one task in 'tasks', each once.`}}),o;if(i.nodeTasks===void 0)return o;for(let d of l){let c=i.nodeTasks.get(d);c?.feedback!==!0&&o.push({field:`${n}.tasks`,code:Ue.recordAssignment,message:c===void 0?{de:`Feld ${t}: "${d}" ist keine Aufgabe dieses Knotens.`,en:`Field ${r}: "${d}" is no task of this node.`}:{de:`Feld ${t}: "${d}" ist keine Feedback-Aufgabe ('feedback: true') \u2014 zugeordnet wird nur, wer eine R\xFCckmeldung gibt.`,en:`Field ${r}: "${d}" is no feedback task ('feedback: true') \u2014 only a person who gives feedback is assigned.`}})}return o}s(f2,"typedFieldIssues");function p2(e,n,t){let r=[],i=n.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:Ue.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:Ue.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=n.item;if(!fi(o))r.push({field:"result.item",code:Ue.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(t.billingItemKeys!==void 0&&!t.billingItemKeys.has(o))r.push({field:"result.item",code:Ue.pricedItemUnknownItem,message:{de:`'result.item' "${o}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...t.billingItemKeys].join(", ")||"keine"}).`,en:`'result.item' "${o}" \u2014 no article of this school has this key (known: ${[...t.billingItemKeys].join(", ")||"none"}).`}});else if(t.offerProgram===null)r.push({field:"result.item",code:Ue.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(t.offerProgram!==void 0&&!t.offerProgram.billingItemKeys.has(o)){let l=t.offerProgram;r.push({field:"result.item",code:Ue.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=n.label;(typeof a!="object"||a===null||!fi(a.de)||!fi(a.en))&&r.push({field:"result.label",code:Ue.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 n.item!==void 0&&r.push({field:"result.item",code:Ue.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(...u2(n.fields,t)),n.writes!==void 0&&r.push({field:"result.writes",code:Ue.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')."}}),n.label!==void 0&&r.push({field:"result.label",code:Ue.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')."}})):n.fields!==void 0&&r.push({field:"result.fields",code:Ue.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"&&(fi(n.writes)||r.push({field:"result.writes",code:Ue.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."}})),n.writes!==void 0&&(e==="freetext"||e==="recommendation")&&r.push({field:"result.writes",code:Ue.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"&&n.textRequired!==void 0&&r.push({field:"result.textRequired",code:Ue.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."}}),n.chat===void 0)r.push({field:"result.chat",code:Ue.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=n.chat,a=typeof o=="string"?Ks(o):null;o==="external"||a===null?r.push({field:"result.chat",code:Ue.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"&&!t.channelKeys.has(a.channelKey)&&r.push({field:"result.chat",code:Ue.chatUnknownChannel,message:{de:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...t.channelKeys].join(", ")||"keine"}).`,en:`'result.chat' "${a.channelKey}" is neither 'all' nor 'team:<group>' nor a channel of the workflow (known: ${[...t.channelKeys].join(", ")||"none"}).`}})}return r.push(...bP(n,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(p2,"recordedIssues");function vP(e,n,t={channelKeys:new Set}){if(n===void 0)return[];if(e!=="task")return[{field:"result",code:Ue.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 n!="object"||n===null||Array.isArray(n))return[{field:"result",code:Ue.unknownKind,message:{de:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${Ls.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Ls.join(", ")}.`}}];let r=n;return EO(r.kind)?r.kind==="appointment"?c2(r):p2(r.kind,r,t):[{field:"result.kind",code:Ue.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Ls.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Ls.join(", ")}.`}}]}s(vP,"taskResultIssues");function Cw(e){let n=Je(e);return e.outcomes&&e.outcomes.length>0?[...e.outcomes]:n.outcomes&&n.outcomes.length>0?[...n.outcomes]:null}s(Cw,"nodeOutcomes");var m2=["documentChangeRequested","documentReturned","coverLetterConfirmed","coverLetterRevisionRequested"];function xP(e){return m2.includes(e)}s(xP,"isNonAdvancingExternalEvent");var na=["offer","contract"];function wp(e){return typeof e=="string"&&na.includes(e)}s(wp,"isArtifactSlotType");var SP="open",ta="done";var AP=[{key:"tenantSlug",type:"string"}];var h2=/^(\d{4})-(\d{2})-(\d{2})$/;function g2(e){return e>=1900&&e<=2100}s(g2,"isSupportedYear");function y2(e,n,t){let r=new Date(Date.UTC(e,n-1,t));return r.getUTCFullYear()===e&&r.getUTCMonth()===n-1&&r.getUTCDate()===t}s(y2,"isRealDate");function Dw(e){if(typeof e!="string")return null;let n=h2.exec(e);if(n===null)return null;let[,t,r,i]=n;return t===void 0||r===void 0||i===void 0||!g2(Number(t))||!y2(Number(t),Number(r),Number(i))?null:{year:t,month:r,day:i}}s(Dw,"isoDateParts");var Fw=3;function EP(e){return _w(e,wP()).wallClock.slice(0,10)}s(EP,"localIsoDate");var kp=["login","security","admission","tasks","deadlines","schoolMessages","staffAssigned","staffTeamQueue","staffFeedback","staffAppointments","staffDeadlines","staffWaitlist","staffUnassigned","familyMessages","mentions"],TP=m.union(...kp.map(e=>m.literal(e)));var _he=m.union(m.literal("admission"),m.literal("tasks"),m.literal("staff"),m.literal("chat")),Lw=["loginOnly","all"],Phe=m.union(m.literal("loginOnly"),m.literal("all"));function $P(e){return typeof e=="string"&&Lw.includes(e)}s($P,"isMailLevel");function RP(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=30}s(RP,"isUnassignedTaskNoticeDays");function IP(e){return e*864e5}s(IP,"unassignedTaskNoticeMs");var Dhe=IP(3),Fhe=IP(1);var Ul="subject";function OP(e){return e.category==="login"}s(OP,"isSignInLetter");var fn={key:"schoolName",label:"Name der Schule"},CP={de:"Zu Ihren Bewerbungen",en:"View your applications"},xn={key:"portalLink",label:"Link zum Bewerberportal",required:!0,link:!0,actionLabel:CP},Mw={key:xn.key,label:xn.label,link:!0,actionLabel:CP},DP={key:"authorName",label:"Name der schreibenden Person"},Fo={key:"applicationLink",label:"Link zur Bewerbung",required:!0,link:!0,actionLabel:{de:"Bewerbung \xF6ffnen",en:"Open application"}},Gl={key:"anmeldeLink",label:"Anmeldelink",required:!0,link:!0,actionLabel:{de:"Jetzt anmelden",en:"Sign in now"},previewValue:{de:"https://beispiel.plexus.schule/anmelden?token=BEISPIEL",en:"https://beispiel.plexus.schule/anmelden?token=BEISPIEL"}},w2={key:"passwortLink",label:"Link zum neuen Passwort",required:!0,link:!0,actionLabel:{de:"Neues Passwort festlegen",en:"Set a new password"},previewValue:{de:"https://beispiel.plexus.schule/login/reset?token=BEISPIEL",en:"https://beispiel.plexus.schule/login/reset?token=BEISPIEL"}},FP={key:"bestaetigungsLink",label:"Best\xE4tigungslink",required:!0,link:!0,actionLabel:{de:"E-Mail best\xE4tigen",en:"Confirm email address"},previewValue:{de:"https://beispiel.plexus.schule/bestaetigen?token=BEISPIEL",en:"https://beispiel.plexus.schule/bestaetigen?token=BEISPIEL"}},zl={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"15 Minuten",en:"15 minutes"}},LP={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"24 Stunden",en:"24 hours"}},k2={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"60 Minuten",en:"60 minutes"}};function $e(e){return{key:Ul,label:"Betreff",default:e}}s($e,"subjectSlot");var Ui=m.object({de:m.string(),en:m.string()}),An={tenantSlug:m.string(),applicationId:m.id("applications")},b2=m.object({tenantSlug:m.string()}),v2={id:"applicant.welcome",category:"admission",label:"Willkommen",occasion:{de:"Sobald f\xFCr eine Familie ein Zugang angelegt wurde",en:"As soon as an account has been created for a family"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:b2,channels:["email"],portalVisible:!0,placeholders:[fn,xn],slots:[$e({de:"Willkommen \u2014 Ihre Bewerbung bei uns",en:"Welcome \u2014 your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`vielen Dank f\xFCr Ihre Registrierung bei {{schoolName}}. \xDCber den folgenden Link k\xF6nnen Sie jederzeit Ihre Bewerbungen einsehen und fortsetzen:
11025
11025
 
11026
11026
  {{portalLink}}`,en:`Thank you for registering with {{schoolName}}. You can view and continue your applications at any time using the link below:
@@ -11273,35 +11273,35 @@ The link is valid for {{gueltigkeit}} and works once. Afterwards you are signed
11273
11273
 
11274
11274
  {{einstellungenLink}}`,en:`Open Plexus and, in the user menu, \u201CSettings\u201D \u2192 \u201CSignature\u201D:
11275
11275
 
11276
- {{einstellungenLink}}`}}]},Vw=[v2,$2,O2,_2,P2,L2,F2,uY,pY,AY,TY,RY,_Y,CY,FY,qY,VY,GY,WY,mY,hY,gY,YY,HY,JY,M2,q2,V2,B2,z2,Z2,nY,Y2,iY,dY,vY,gH,wH,S2,E2,ZY,eH,tH,iH,aH,dH,uH];function Bw(e){let n=Vw.find(t=>t.id===e);return n===void 0&&F(`notifications: unknown letter "${e}"`),n}s(Bw,"letterDefFor");function Uw(e){return Vw.some(n=>n.id===e)}s(Uw,"hasLetterDef");function Gw(e,n){return n===void 0?!0:Zf(e,n)}s(Gw,"letterArgCompatible");function Hl(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${rt(e)} (${e})`,en:`${rt(e)} (${e})`}}s(Hl,"letterArgTypeLabel");function KP(e){let n=new Map,t=s((r,i)=>{let o=n.get(r);o===void 0?n.set(r,[i]):o.push(i)},"add");for(let r of e.args)t(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of AP)t(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return n}s(KP,"eventArgSources");function jP(e,n){let t=e.type===void 0?[...n]:n.filter(r=>Gw(r.type,e.type));if(t.length>1)return{status:"ambiguous",matches:t};if(t.length===1){let r=t[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...n]}:{status:"unused"}}s(jP,"resolveLetterParam");var zw=["booked","rescheduled","cancelled"],kH={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},BP=":";function UP(e,n){return`${e}${BP}${n}`}s(UP,"appointmentEventId");function bH(e){let n=e.lastIndexOf(BP);if(n<=0)return null;let t=e.slice(n+1);return zw.includes(t)?{taskKey:e.slice(0,n),kind:t}:null}s(bH,"parseAppointmentEventId");var VP={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function ia(e){return Array.isArray(e.tasks)?e.tasks.filter(n=>typeof n?.key=="string"&&n.result?.kind==="appointment"):[]}s(ia,"appointmentTasksOf");function vH(e){return zw.map(n=>({id:UP(e.key,n),label:{de:`${VP[n].de} \u2013 \u201E${e.title.de}\u201C`,en:`${VP[n].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(vH,"appointmentTaskEvents");function GP(e,n){let t=n.notificationEvents?.(e)??[],r=ia(e).flatMap(vH);return r.length===0?t:[...t,...r]}s(GP,"nodeNotificationEvents");function xH(e){return Object.fromEntries(zw.map(n=>[UP(e,n),{templateId:kH[n]}]))}s(xH,"defaultAppointmentBindings");function SH(e,n){if(e===void 0)return{notifications:e,dropped:[]};let t=[],r={};for(let[i,o]of Object.entries(e))bH(i)?.taskKey===n?t.push(i):r[i]=o;return t.length===0?{notifications:e,dropped:t}:{notifications:Object.keys(r).length===0?void 0:r,dropped:t}}s(SH,"withoutAppointmentBindings");function Ep(e,n,t){let r=new Set(ia(n).map(d=>d.key)),i=new Set(ia(t).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=SH(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(xH(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(Ep,"syncAppointmentBindings");function AH(e){return e.kind==="task"&&!("title"in e)}s(AH,"isLegacyFreeTodoContext");function Ww(e){let{context:n}=e;if(AH(n)&&F(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),n.kind==="task")return{...e,context:n,kind:"task",createdVia:"human",partyId:n.partyId};let{anchor:t,task:r,kind:i,title:o,description:a,...l}=n,d=t.scope==="node"?{nodeId:t.nodeId,templateKey:t.templateKey,gatesNode:t.gatesNode,blocks:t.blocks}:t.scope==="application"?{scope:"application",templateKey:t.templateKey}:t.scope==="crossNode"?{scope:"application",nodeId:t.nodeId,templateKey:t.templateKey,blocks:t.blocks}:{};return{...e,context:n,...l,...d,...r??{},kind:i}}s(Ww,"readWorkItem");async function oa(e,n){let t;if(n.nodeId!==void 0){let r=n.nodeId;t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(n.isOpen!==void 0){let r=n.isOpen;t=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",n.applicationId).eq("isOpen",r)).collect()}else t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",n.applicationId)).collect();return t.filter(r=>n.isOpen===void 0||r.isOpen===n.isOpen).map(Ww)}s(oa,"listWorkItemsForApplication");var yge=m.union(m.literal("approved"),m.literal("rejected")),Jl=new Set(["task","approval"]);function TH(e,n){switch(e){case"task":return n?.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:n?.gatesNode??!0};default:F(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Jl].join(", ")}`)}}s(TH,"expandComposedTask");for(let e of["task","approval"]){let n=TH(e);n.kind==="approval"!=(n.isApproval===!0)&&F(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var zP=Fi,Gi=`${zP}.`,$H=new Set(["text","number","date","boolean","option","edge"]);function Tp(e,n){let t=e[n];return t===void 0&&F(`[env/unknownKey] no environment key '${n}'`),typeof t=="string"?null:Object.keys(t)}s(Tp,"contextFields");function WP(e,n){return Object.hasOwn(e,n)}s(WP,"isContextKey");function YP(e){let n=[];for(let t of Object.keys(e)){let r=Tp(e,t);if(r===null)n.push(t);else for(let i of r)n.push(`${t}.${i}`)}return n}s(YP,"leafPaths");function Ql(e,n){let[t="",r,...i]=n.split(".");if(!WP(e,t)||i.length>0)return;let o=e[t];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Ql,"leafType");function HP(e){let n=new Set;for(let t of e){let r=sa(t);r!==null&&n.add(r.split(".")[0])}return[...n]}s(HP,"contextKeysOf");function sa(e){return e.startsWith(Gi)?e.slice(Gi.length):null}s(sa,"contextPathOf");function Zl(e){return e===zP||e.startsWith(Gi)}s(Zl,"isContextIdentifier");function $p(e,n){let t=sa(n)??"",[r=""]=t.split("."),i=Object.keys(e);if(!WP(e,r))return{code:"env/unknownKey",message:{de:`'${n}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${n}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Ql(e,t)!==void 0)return null;let o=Tp(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${n}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${Gi}${r}'.`,en:`'${n}': environment key '${r}' is a single value \u2014 read it as '${Gi}${r}'.`}:{de:`'${n}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${n}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s($p,"identifierIssue");function Rp(e,n,t=Object.keys(e)){let r={};for(let i of t){let o=Tp(e,i),a=Object.hasOwn(n,i)?n[i]:void 0;if(a===void 0&&F(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${Gi}${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[`${Gi}${i}.${l}`]=d}}return r}s(Rp,"flatten");function JP(e,n,t){if(t===void 0)return!1;let r=Tp(e,n);return r===null?!0:typeof t=="object"&&t!==null&&r.every(i=>t[i]!==void 0)}s(JP,"contextValueComplete");function RH(e,n){switch(n){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(RH,"valueMatchesDataType");function QP(e,n,t=Object.keys(e.types)){let r=new Set(t);for(let i of YP(e.types)){if(!r.has(i.split(".")[0]))continue;let o=n[`${Gi}${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=rt(Ql(e.types,i));RH(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(QP,"assertContextValues");function IH(e){let n=[],t=YP(e.types);for(let r of t){let i=Ql(e.types,r),o=rt(i);if(!qi(i)||o===void 0||!$H.has(o)){n.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){n.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&n.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&n.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))t.includes(r)||n.push(`field spec '${r}' names no leaf of the schema`);return n}s(IH,"schemaIssues");function aa(e){let n=IH(e);n.length>0&&F(`[env/schema] ${n.join("; ")}`)}s(aa,"assertSchema");var Ip={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function zi(e){return JSON.stringify(e)}s(zi,"canonical");function da(e){return e.kind==="binary"&&e.op==="&&"?[...da(e.left),...da(e.right)]:[e]}s(da,"conjuncts");function eN(e,n){let t;try{t=On(e)}catch{return!1}let r=zi(On(n));return da(t).some(i=>zi(i)===r)}s(eN,"hasConjunct");function nN(e,n){try{return zi(On(e))===zi(On(n))}catch{return!1}}s(nN,"sameCondition");function tN(e){let n=[];for(let t of e)n.push(..._n(di(t)));return HP(n)}s(tN,"contextKeysRead");function rN(e){try{return _n(On(e)).some(Zl)}catch{return!1}}s(rN,"readsContext");var OH=/^\d{4}-\d{2}-\d{2}$/,_H=new Set(["==","!=","<","<=",">",">=","in"]),PH=new Set(["<","<=",">",">="]);function _p(e,n,t=[]){aa(n);let r;try{r=On(e)}catch(a){let l=a.message;return[Wn("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of _n(r)){if(!Zl(a)){i.push(Wn("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=$p(n.types,a);l!==null&&i.push(Wn("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Gr(r,n,i);Xl(o)||i.push(Wn("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),FH(r,n,i);for(let{identifier:a,op:l}of Jw(r,n))i.push(Wn("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(...NH(r,t)),i}s(_p,"conditionIssues");function NH(e,n){let t=da(e).map(zi);return n.flatMap(r=>{let i=On(r),o=CH(i);return o===null||!t.includes(zi(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(NH,"guardFormHints");function CH(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let n={...e,left:e.right,right:e.left};return zi(n)===zi(e)?null:n}s(CH,"mirror");function Xl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Xl,"isBooleanish");function iN(e){let n=sa(e);return n===null&&F(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),n}s(iN,"contextPath");function oN(e,n){let t=sa(n);return t!==null&&e.fields[t]?.nullable===!0}s(oN,"isNullableLeaf");function DH(e,n){let t=rt(Ql(e.types,iN(n)));return t===void 0?{t:"unknown"}:{t:"data",dt:t}}s(DH,"identType");function Op(e,n){return e.t==="unknown"||n.t==="unknown"||e.t==="null"||n.t==="null"?!0:e.t==="array"||n.t==="array"?!1:e.t==="str"&&n.t==="str"?!0:e.t==="str"?ZP(e.value,n.dt):n.t==="str"?ZP(n.value,e.dt):e.dt===n.dt}s(Op,"fits");function ZP(e,n){return n==="text"||n==="option"||n==="edge"?!0:n==="date"?OH.test(e):!1}s(ZP,"strFits");function XP(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(XP,"orderedCategory");function Gr(e,n,t){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 DH(n,e.path);case"arr":for(let r of e.items)Gr(r,n,t);return{t:"array"};case"unary":{let r=Gr(e.operand,n,t);return Xl(r)||t.push(Wn("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(Ip,e.name)?Ip[e.name]:void 0,i=e.args.map(l=>Gr(l,n,t));return r===void 0?(t.push(Wn("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(Ip).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(Ip).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&Op(l,{t:"data",dt:r.params[d]}))||t.push(Wn("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Gr(e.cond,n,t);Xl(r)||t.push(Wn("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Gr(e.then,n,t),o=Gr(e.else,n,t);return Op(i,o)||t.push(Wn("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=Gr(e.left,n,t),i=Gr(e.right,n,t);if(e.op==="&&"||e.op==="||")(!Xl(r)||!Xl(i))&&t.push(Wn("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?t.push(Wn("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=>Op(r,Gr(o,n,[])))||t.push(Wn("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(PH.has(e.op)){let o=XP(r),a=XP(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&t.push(Wn("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 Op(r,i)||t.push(Wn("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Gr,"typeOf");function Yw(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(Yw,"isLiteral");function sN(e){let n=[],t=s(r=>{if(r.kind==="binary"&&_H.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(Yw):Yw(r.right)?[r.right]:[];i.length>0&&n.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&Yw(r.left)&&n.push({ident:r.right.path,literals:[r.left]})}aN(r,t)},"visit");return t(e),n}s(sN,"comparedLiterals");function FH(e,n,t){for(let{ident:r,literals:i}of sN(e)){let o=LH(r,i,n);o!==null&&t.push(o)}}s(FH,"literalIssues");function Hw(e,n){let t;try{t=On(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of sN(t)){let a=sa(i);if(!(a===null||n.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(Hw,"liveLiterals");function LH(e,n,t){let r=t.fields[iN(e)]?.valueSet;if(r?.kind==="unstable")return Wn("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=n.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 Wn("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(LH,"valueSetIssue");function aN(e,n){switch(e.kind){case"binary":n(e.left),n(e.right);return;case"unary":n(e.operand);return;case"call":e.args.forEach(n);return;case"arr":e.items.forEach(n);return;case"if":n(e.cond),n(e.then),n(e.else);return;default:return}}s(aN,"forEachChild");function lN(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(lN,"isNullTest");function dN(e){return da(e).flatMap(n=>{let t=cN(n);return t===null?[]:[t]})}s(dN,"guardsOf");function ed(e,n,t){switch(e.kind){case"ident":return oN(n,e.path)&&!t.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=ed(r,n,t);if(i!==null)return i}return null;case"if":return ed(e.then,n,new Set([...t,...dN(e.cond)]))??ed(e.else,n,t);default:return null}}s(ed,"unguardedNullSource");function cN(e){return!lN(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(cN,"guardedIdent");function la(e,n,t,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(t);for(let o of da(e)){la(o,n,i,r);let a=cN(o);a!==null&&i.add(a)}return}if(e.kind==="if"){la(e.cond,n,t,r),la(e.then,n,new Set([...t,...dN(e.cond)]),r),la(e.else,n,t,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=ed(e.left,n,t)??ed(e.right,n,t);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!lN(e.operand)){let i=_n(e.operand).filter(o=>oN(n,o)&&!t.has(o));i.length>0&&r(i[0],"!")}aN(e,i=>la(i,n,t,r))}s(la,"nullableReads");function Jw(e,n){aa(n);let t=[];return la(e,n,new Set,(r,i)=>{t.some(o=>o.identifier===r)||t.push({identifier:r,op:i})}),t}s(Jw,"unguardedNullableReads");function Wn(e,n,t){return{severity:"error",code:e,message:{de:`[${e}] ${n}`,en:`[${e}] ${t}`}}}s(Wn,"error");function nd(e){let n=Array.isArray(e.nodes)?e.nodes:[],t=new Set;for(let r of n)for(let i of dp(r))i.key!==null&&zs[i.leaf].involves&&t.add(i.key);return t}s(nd,"declaredGroupKeys");var ca=Pf;var MH="unit.key",qH="offer.key";function uN(e,n){return e===MH?n.unitKeys:e===qH?n.offerKeys:null}s(uN,"liveKeyUniverse");function Pp(e){return[yn,...[...nd(e)].sort((n,t)=>n.localeCompare(t)).map(qf)]}s(Pp,"requiredSlots");var Wi=`${Cf("applicant.channel")} == 'staff'`;var Zw=["strict","leastLoaded"];var Qw=2;function fN(e){return e.some(n=>n.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<Qw?{de:`braucht mindestens ${Qw} Personen`,en:`needs at least ${Qw} people`}:null}s(fN,"rotationPoolProblem");function KH(e,n){let t=n===null?-1:e.indexOf(n);return[...e.slice(t+1),...e.slice(0,t+1)]}s(KH,"strictOrder");function pN(e){let n=KH(e.pool,e.previous).filter(i=>e.eligible.has(i));if(n.length===0)return null;if(e.mode==="strict")return n[0];let t=e.openCounts;t===void 0&&F("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=t.get(i);return o===void 0&&F(`[assignment/rotation] no open count for '${i}'`),o},"load");return n.reduce((i,o)=>r(o)<r(i)?o:i)}s(pN,"pickFromPool");function hN(e){return e.map(n=>({slot:sO(n.slot),rules:[...n.rules]}))}s(hN,"rulesOfStored");function gN(e){return e.map(n=>({slot:jH(n.slot),rules:[...n.rules]}))}s(gN,"storedOfRules");function jH(e){let n=jf(e);return n===null&&F(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),n}s(jH,"slotOf");function yN(e,n){let t=e?.assignmentRules;t===void 0&&F(`[assignment/noRules] ${n}: the workflow has no assignment rule`);let r=vN(t);return r.length>0&&F(`${r.join("; ")} (${n})`),hN(t)}s(yN,"rulesOfGraph");function VH(e){return e===yn?{slot:e,rules:[{when:Wi,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(VH,"defaultSlotRules");function wN(e,n){let t=new Set(e.map(o=>o.slot)),r=n.filter(o=>!t.has(o)).map(VH);return[...r.filter(o=>o.slot===yn),...e,...r.filter(o=>o.slot!==yn)]}s(wN,"withRequiredSlots");function Nn(e,n){return n===void 0?`slot '${e}'`:`slot '${e}' row #${n+1}`}s(Nn,"where");function Ft(e,n){return n===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${n+1}`}s(Ft,"whereDe");function Et(e,n,t={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${n.de}`,en:`[${e}] ${n.en}`},...t}}s(Et,"issue");function mN(e){if(e===yn)return!0;let n=Kf(e);return n!==null&&n.length>0}s(mN,"isKnownSlot");function BH(e,n){aa(ca);let t=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;mN(l)||t.push(Et("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)&&t.push(Et("assignment/duplicateSlot",{de:`${Ft(l)} steht zweimal da`,en:`${Nn(l)} is listed twice`},{slot:l})),r.add(l),l===yn&&a!==0&&t.push(Et("assignment/responsibleFirst",{de:`'${yn}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${yn}' must be the first slot \u2014 team rows copy it`},{slot:l})),t.push(...UH(o))});for(let o of n)r.has(o)||t.push(Et("assignment/slotMissing",{de:`${Ft(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${Nn(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(n);for(let{slot:o}of e)o!==yn&&!i.has(o)&&mN(o)&&t.push(Et("assignment/unusedSlot",{de:`${Ft(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${Nn(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return t}s(BH,"validateRules");function UH({slot:e,rules:n}){let t=[];return(n.length===0||n[n.length-1].when!==null)&&t.push(Et("assignment/defaultRowMissing",{de:`${Ft(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${Nn(e)} must end with a row without condition ("otherwise")`},{slot:e})),n.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<n.length-1&&t.push(Et("assignment/ruleAfterDefault",{de:`${Ft(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${Nn(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=_p(a,ca,[Wi]);for(let c of d)t.push({...c,message:{de:`${c.message.de} (${Ft(e,i)})`,en:`${c.message.en} (${Nn(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){rN(a)||t.push(Et("assignment/shadowedRule",{de:`${Ft(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${Nn(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=n.slice(0,i).findIndex(u=>u.when!==null&&nN(u.when,a));c!==-1&&t.push(Et("assignment/shadowedRule",{de:`${Ft(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${Nn(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===yn&&l.kind==="slot"&&t.push(Et("assignment/slotForwardRef",{de:`${Ft(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${yn}'`,en:`${Nn(e,i)} copies '${l.slot}' \u2014 only a team slot after '${yn}' may`},o)),e===yn&&l.kind==="queue"&&t.push(Et("assignment/queueOnProcessSlot",{de:`${Ft(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${Nn(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&t.push(Et("assignment/targetMissing",{de:`${Ft(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${Nn(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=fN(l.configKeys);d!==null&&t.push(Et("assignment/rotationPool",{de:`${Ft(e,i)}: die Reihum-Liste ${d.de}`,en:`${Nn(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!eN(a,Wi))&&t.push(Et("assignment/unguardedTarget",{de:`${Ft(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${Wi}' ist (oder enth\xE4lt)`,en:`${Nn(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${Wi}'`},o))}),t}s(UH,"rowIssues");function kN(e,n){for(let r of n)e.some(i=>i.slot===r)||F(`[assignment/slotMissing] ${Nn(r)} has no rule list`);let t=new Set(n);return e.filter(r=>t.has(r.slot))}s(kN,"selectSlots");function GH(e,n){return tN(kN(e,n).flatMap(t=>t.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(GH,"contextKeysOfRules");function bN(e,n,t,r){aa(ca);let i=kN(e,t),o=GH(e,t),a=Rp(ca.types,n,o);QP(ca,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 _n(di(h.when)))Object.hasOwn(a,k)||F(`[condition/unknownIdentifier] ${Nn(d,w)} reads '${k}', which the context does not carry`);return DO(h.when,{values:a})});u===-1&&F(`[assignment/defaultRowMissing] ${Nn(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:zH(d,u,p,l,r)})}return l}s(bN,"evaluateRules");function zH(e,n,t,r,i){switch(t.kind){case"person":return{kind:"value",value:i.person(t.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(t,{slot:e,row:n})};case"unassigned":return F(`[assignment/targetMissing] ${Nn(e,n)} names no one`);case"queue":return e===yn&&F(`[assignment/queueOnProcessSlot] ${Nn(e,n)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===yn?void 0:r.find(a=>a.slot===t.slot);return o===void 0&&F(`[assignment/slotForwardRef] ${Nn(e,n)} copies '${t.slot}', which is not decided before it`),o.value}}}s(zH,"resolveTarget");var Xw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function WH(e){if(typeof e!="object"||e===null)return!1;let{kind:n,groupKey:t,...r}=e;return Object.keys(r).length>0?!1:n==="responsible"?t===void 0:n==="team"&&typeof t=="string"&&t.length>0}s(WH,"isStoredSlot");function vN(e){let n=[],t=s((r,i)=>n.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 t(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&t(o,`unknown field(s) ${Object.keys(d).join(", ")}`),WH(a)||t(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return t(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return t(p,"must be { when, assign }");let{when:h,assign:w,...k}=c;Object.keys(k).length>0&&t(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&t(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(Xw,y))return t(p,`assign must be one of ${Object.keys(Xw).map(R=>`{kind:'${R}'}`).join(", ")}`);let b=Xw[y],E=Object.keys(w);(E.some(R=>!b.includes(R))||b.some(R=>!E.includes(R)))&&t(p,`a '${y}' target has exactly the field(s) ${b.join(", ")}`);let T=w;if(y==="person"&&(typeof T.configKey!="string"||T.configKey.length===0)&&t(p,"a 'person' target needs a non-empty configKey"),y==="rotation"){let R=T.configKeys;(!Array.isArray(R)||R.some(D=>typeof D!="string"))&&t(p,"a 'rotation' target needs configKeys, a list of person keys"),Zw.includes(T.mode)||t(p,`a 'rotation' target's mode is one of ${Zw.map(D=>`'${D}'`).join(", ")}`)}y==="slot"&&T.slot!==yn&&t(p,`a 'slot' target copies '${yn}' and nothing else`)})}),n):(t("slots","must be a list of { slot, rules }"),n)}s(vN,"ruleShapeIssues");function xN(e){let n=e??{},t=[];if(n.teamOwnerBindings!==void 0&&t.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"}),n.assignmentRules===void 0)return t.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"}),t;let r=vN(n.assignmentRules);if(r.length>0)return[...t,...r.map(o=>({de:o,en:o}))];let i=Pp({nodes:Array.isArray(n.nodes)?n.nodes:[]});for(let o of BH(hN(n.assignmentRules),i))o.severity==="error"&&t.push(o.message);return t}s(xN,"workflowAssignmentIssues");function Np(e,n){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:n(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:n(p),idx:0}))}}return l}s(Np,"detectBackEdges");var ek="team:",YH=/^[a-z0-9][a-z0-9-]*$/;function HH(e){if(!e.startsWith(ek))return null;let n=e.slice(ek.length);return n.length>0?n:null}s(HH,"teamKeyOfMember");function Cp(e){return`${ek}${e}`}s(Cp,"teamMember");function ua(e){let n=e.channels;return n===void 0?[]:(Array.isArray(n)||F("graph.channels must be an array"),n)}s(ua,"readAuthoredChannels");function SN(e){return[...nd(e)].sort()}s(SN,"derivedChannelTeamKeys");function AN(e,n){let t=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!n.has(t))return t;for(let r=2;;r++){let i=`${t}-${r}`;if(!n.has(i))return i}}s(AN,"mintChannelKey");function EN(e,n){let t=e.channels;if(t===void 0)return[];if(!Array.isArray(t))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=nd(e),o=new Set,a=new Map;return t.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||In(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(E=>typeof E=="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}"`};YH.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=In(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 E of u.members){let T=HH(E);if(T===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${E}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${E}" is not a "team:<key>".`}});continue}if(w.includes(T)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${T}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${T}" is named twice.`}});continue}n!==void 0&&!n.has(T)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${T}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${T}" does not exist at this school (or it is the applicant group).`}}),w.push(T)}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 b=a.get(k);b!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${b}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${b}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(EN,"channelIssues");var fye=Object.freeze({});function JH(e,n){return Object.freeze(Rp(ri,e,n))}s(JH,"formContextEntries");function TN(e){return e.env??[]}s(TN,"declaredContextKeys");function $N(e,n){return TN(e).every(t=>RN(t,n?.[t]))}s($N,"scenarioContextComplete");function RN(e,n){return JP(ri,e,n)}s(RN,"contextValueComplete");function IN(e,n){return JH(n??{},TN(e))}s(IN,"scenarioContextEntries");function tk(e){return Zl(e)}s(tk,"isContextIdentifier");function QH(e,n,t){let r=$p(ri,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,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(QH,"contextIdentifierIssue");var nk=Cf("stage.key");function ZH(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===nk,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.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),n}s(ZH,"stageKeyLiterals");function Dp(e,n,t){return n===void 0?[]:ZH(e).filter(r=>!n.has(r)).map(r=>_N(r,n,t))}s(Dp,"stageKeyAstIssues");function ON(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(_N(i.key,n,`scenario:${r.id}/env`))}return t}s(ON,"scenarioStageKeyIssues");function _N(e,n,t){let r=[...n].sort();return{severity:"error",path:t,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.")+` \`${nk}\` 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.")+` \`${nk}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(_N,"unknownStageKeyIssue");function PN(e,n,t){let r=[];for(let i of _n(e)){if(!tk(i))continue;let o=QH(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Jw(e,Pf))r.push({severity:"error",path:t,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(PN,"contextAstIssues");function NN(e,n){let t=[...XH(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Ns(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${Ps.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${Ps.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.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=>Ns(a)&&!RN(a,i.env?.[a]));o.length>0&&t.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??{}))Ns(a)?r.has(a)||t.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.`}}):t.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 t}s(NN,"formContextIssues");function XH(e){let n=[];Object.hasOwn(e,"context")&&n.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 t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.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 n}s(XH,"retiredContextFields");function Fp(e,n,t){let r=_p(e,n).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(t?.liveEnvKeys!==void 0)for(let o of Hw(e,n)){let a=uN(o.path,t.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 Dp(On(e),t?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(Fp,"envConditionFindings");function Lp(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(Lp,"isReviewField");function fa(e){let n=[],t=[];function r(y,b){try{return On(y)}catch(E){n.push({path:b,src:y,reason:E instanceof Error?E.message:String(E)});return}}s(r,"tryParse");function i(y,b){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,requiredIf:y.requiredIf?r(y.requiredIf,`${b}.requiredIf`):void 0,disabledIf:y.disabledIf?r(y.disabledIf,`${b}.disabledIf`):void 0,defaultValue:y.defaultValue?r(y.defaultValue,`${b}.defaultValue`):void 0}}s(i,"compileField");function o(y,b){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,fields:y.fields.map((E,T)=>i(E,`${b}.fields[${T}]`))}}s(o,"compileGroup");function a(y,b){return{...y,itemTemplate:y.itemTemplate.map((E,T)=>i(E,`${b}.itemTemplate[${T}]`)),effects:y.effects?.map((E,T)=>d(E,`${b}.effects[${T}]`)),itemVisibleIf:y.itemVisibleIf?r(y.itemVisibleIf,`${b}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(y,b){let E=[];return y.fields.forEach((T,R)=>{if(T.externalFlag){t.push({key:T.key,label:T.label,defaultValue:T.defaultValue?r(T.defaultValue,`${b}.fields[${R}].defaultValue`):void 0});return}E.push(i(T,`${b}.fields[${R}]`))}),{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,fields:E,groups:y.groups?.map((T,R)=>o(T,`${b}.groups[${R}]`)),computed:y.computed?.map((T,R)=>{let D=r(T.expression,`${b}.computed[${R}].expression`);return{key:T.key,expression:D??{kind:"null"}}}),subsections:y.subsections?.map((T,R)=>l(T,`${b}.subsections[${R}]`)),repeated:y.repeated?.map((T,R)=>a(T,`${b}.repeated[${R}]`)),validators:y.validators}}s(l,"compileSection");function d(y,b){return{...y,when:y.when?r(y.when,`${b}.when`):void 0}}s(d,"compileEffect");function c(y,b){let E=r(y.when,`${b}.when`);return E?{...y,when:E}:null}s(c,"compileOutcome");let u=e.sections.map((y,b)=>l(y,`sections[${b}]`)),p=(e.effects??[]).map((y,b)=>d(y,`effects[${b}]`)),h=[],w=e.outcomes??[];for(let y=0;y<w.length;y++){let b=w[y],E=c(b,`outcomes[${y}]`);E&&h.push(E)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:t},errors:n}}s(fa,"compileForm");var eJ=new Set(["decision","review","governedDocument"]);function DN(e){return eJ.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(DN,"isReadinessGatedNode");function nJ(e){let n=new Map,t=rJ(e),r=s((i,o)=>{let a=rk(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&n.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:tJ(d.bucket,t,a),section:a,type:d.type,enumSource:CN(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}`;n.set(u,{kind:"entered",key:u,label:c.label,qualifier:rk(d),section:a,type:c.type,enumSource:CN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=_n(On(d.expression));n.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 n}s(nJ,"formFieldCatalog");function CN(e){return e.type==="enum"?e:null}s(CN,"enumSourceOf");function tJ(e,n,t){return e===void 0?t:n.get(e)??t}s(tJ,"fieldQualifier");function rJ(e){let n=new Map,t=s((r,i)=>{i===void 0||n.has(r)||n.set(r,rk(i))},"add");for(let r of LN(e))r.kind==="person"?t(r.bucket,r.display):r.kind==="organization"&&t(r.id.replace(/^o\./,""),r.display);return n}s(rJ,"bucketWordings");function FN(e){return e.flatMap(n=>[n,...FN(n.subsections??[])])}s(FN,"allSections");function LN(e){return[...e.effects,...FN(e.sections).flatMap(n=>(n.repeated??[]).flatMap(t=>t.effects??[]))]}s(LN,"allEffects");function rk(e){return{label:e.label}}s(rk,"wordingOf");function MN(e){return Fl(e).flatMap(({slot:n,address:t})=>{let r=jO(t);return r===null||Dl.includes(r.path)?[]:[{slotId:n,owner:r.owner,fieldKey:r.path}]})}s(MN,"admissionBindingLeaves");function iJ(e,n){let t=e.get(n);if(t===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(t),r}s(iJ,"expandKey");function oJ(e){let n=new Set;for(let t of LN(e))if(!(t.kind!=="person"||t.contractParty===void 0)&&t.when!==void 0)for(let r of _n(On(t.when)))n.add(r);return[...n]}s(oJ,"contractPartyConditionKeys");function sJ(e){return fa(e).compiled.flags.map(n=>({key:n.key,name:n.label}))}s(sJ,"formExternalFlags");function qN(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([n,t])=>[n,nJ(t)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(oJ(t))])),formFlagKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(sJ(t).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set((t.views??[]).map(r=>r.key))]))}}s(qN,"readinessUniverse");function ik(e,n){let t=new Set;for(let r of n)for(let i of iJ(e,r)??[])i.kind==="entered"&&t.add(i.fieldKey);return t}s(ik,"enteredFieldsBehind");var aJ=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function lJ(e){return aJ.has(e)?!0:KN(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(lJ,"isTextKey");function KN(e){return/^localized[A-Z]/.test(e)}s(KN,"isLegacyTwinKey");var dJ=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),cJ=new Set(["inputs","resolver","library"]);function qp(e,n){let t=[];return ok(e,n,t),t}s(qp,"findUnlocalizedTexts");function ok(e,n,t){if(Array.isArray(e)){e.forEach((i,o)=>ok(i,`${n}[${fJ(i,o)}]`,t));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${n}.${i}`;if(!cJ.has(i)){if(KN(i)){t.push({path:a,missing:"legacy-twin"});continue}if(lJ(i)){uJ(o,a,t);continue}if(dJ.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&jN(d,`${a}.${l}`,t);continue}ok(o,a,t)}}}s(ok,"walk");function uJ(e,n,t){e!=null&&jN(e,n,t)}s(uJ,"checkText");function jN(e,n,t){let r=In(e);(r==="not-localized"||r.length>0)&&t.push({path:n,missing:r})}s(jN,"report");function fJ(e,n){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.id=="string")return t.id;if(typeof t.key=="string")return t.key}return String(n)}s(fJ,"keyOf");function Mp(e,n){return e==="not-localized"?n==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?n==="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"':n==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(Mp,"describe");function sk({path:e,missing:n}){return n==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${Mp(n,"de")}.`,en:`[i18n/legacyTwin] ${e} ${Mp(n,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${Mp(n,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${Mp(n,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(sk,"unlocalizedTextReason");var pJ={engagePush:["engage"]};function mJ(e){let n=pJ[e.type];return n===void 0?e:Object.fromEntries(Object.entries(e).filter(([t])=>!n.includes(t)))}s(mJ,"withoutMachineData");function VN(e,n){return[...qp(e.nodes.map(mJ),"nodes"),...n===void 0?[]:qp(n,`layout.${n.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:sk(r),severity:"error"}))}s(VN,"checkLocalizedTexts");var hJ="optionalAction:";function BN(e){return`${hJ}${e}:trigger`}s(BN,"optionalActionTriggerActionId");var gJ="processDecide";function UN(e){let n=e.optionalActions;return n==null?[]:(Array.isArray(n)||F(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof n}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),n)}s(UN,"optionalActionBindings");function GN(e){return UN(e).map(n=>({id:BN(n.key),kind:"internal",label:n.label,surface:gJ,placement:"overflow",superUserOnly:!0}))}s(GN,"optionalActionTriggers");function zN(e){let n=e.tasks;return Array.isArray(n)?n:[]}s(zN,"authoredTemplates");function WN(e){let n=e?.result;return n?.kind!=="appointment"?[]:n.participants?.feedback?.tasks??[]}s(WN,"personTasksOf");function ak(e){let n=zN(e);return UN(e).map(t=>{let r=new Set(t.tasks??[]),i=new Set;for(let o of r)for(let a of WN(n.find(l=>l.key===o)))i.add(a);return{binding:t,tasks:r,personTasks:i,keys:new Set([...r,...i])}})}s(ak,"optionalActionMembership");function yJ(e){let n=new Set;for(let t of zN(e))for(let r of WN(t))n.add(r);return n}s(yJ,"personRowTemplateKeys");function YN(e){let n=new Set(yJ(e));for(let{keys:t}of ak(e))for(let r of t)n.add(r);return n}s(YN,"referencedTaskTemplateKeys");var zr={shape:"[taskInput/shape]",notInRound:"[taskInput/notInRound]",notRecord:"[taskInput/notRecord]",prefillNotDeclared:"[taskInput/prefillNotDeclared]",prefillType:"[taskInput/prefillType]",feedbackTasks:"[appointment/feedbackTasks]",feedbackOptional:"[appointment/feedbackOptional]",recordAssignment:"[taskResult/recordAssignment]"},lk=60;function pa(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(pa,"error");function Mo(e){return Array.isArray(e.tasks)?e.tasks:[]}s(Mo,"tasksOf");function HN(e){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(t=>t.action==="spawnTasks")}s(HN,"spawnBindingsOf");function td(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}s(td,"stringList");function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(Wr,"record");function dk(e){let n=Wr(e?.result);return n?.kind==="appointment"?Wr(n.participants):null}s(dk,"participantsOf");function JN(e){return td(Wr(dk(e)?.feedback)?.tasks)}s(JN,"feedbackTasksOf");function QN(e,n){return ak(e).find(t=>t.keys.has(n))}s(QN,"roundOf");function wJ(e,n,t){let r=s(u=>({code:zr.notInRound,reason:u}),"notInRound"),i=QN(e,n);if(i===void 0)return r({de:`Aufgabe "${n}" geh\xF6rt zu keiner optionalen Aktion \u2014 Vorgaben liest nur eine Aufgabe einer Runde.`,en:`Task "${n}" belongs to no optional action \u2014 only a task of a round reads inputs.`});if(t.scope!=="task"||t.path!==void 0)return r({de:`${de(t)} ist kein Wert einer Aufgabe ($task.<aufgabe>.<schl\xFCssel>).`,en:`${de(t)} is no value of a task ($task.<task>.<key>).`});let{binding:o}=i,a=t.owner;if(a===n)return r({de:`Aufgabe "${n}" liest ihren eigenen Wert.`,en:`Task "${n}" reads its own value.`});let l=Mo(e).find(u=>u.key===a),d=Wr(l?.blocks),c=i.tasks.has(a)&&d?.templateKey===n&&(d.node===void 0||d.node===e.id);return a!==o.input&&!c?r({de:`"${a}" ist weder die Eingabe der Aktion "${o.key}" noch eine ihrer Aufgaben, die "${n}" per 'blocks' zur\xFCckh\xE4lt \u2014 der Wert st\xFCnde nicht fest, wenn die Aufgabe \xF6ffnet.`,en:`"${a}" is neither the input of the action "${o.key}" nor one of its tasks that holds "${n}" through 'blocks' \u2014 the value would not be settled when the task opens.`}):Wr(l?.result)?.kind!=="record"?{code:zr.notRecord,reason:{de:`"${a}" hat kein Ergebnis vom Typ 'record' \u2014 Vorgaben sind Felder einer Eingabe.`,en:`"${a}" has no result of kind 'record' \u2014 inputs are fields of an input task.`}}:null}s(wJ,"taskInputRefusal");function kJ(e,n){if(n.scope!=="task")return;let t=Mo(e).find(i=>i.key===n.owner),r=Wr(t?.result);if(r?.kind==="record")return(Array.isArray(r.fields)?r.fields:[]).map(Wr).find(i=>i?.writes===n.key)??void 0}s(kJ,"writerField");function bJ(e,n,t){let r=String(n.key);if(n.inputs===void 0)return[];if(!Array.isArray(n.inputs))return[pa(`${t}.inputs`,zr.shape,{de:"'inputs' ist eine Liste von Adressen.",en:"'inputs' is a list of addresses."})];let i=[],o=new Set;for(let[a,l]of n.inputs.entries()){if(!we(l))continue;let d=de(l);if(o.has(d)){i.push(pa(`${t}.inputs.${a}`,zr.shape,{de:`${d} steht zweimal in 'inputs'.`,en:`${d} is listed twice in 'inputs'.`}));continue}o.add(d);let c=wJ(e,r,l);c!==null&&i.push(pa(`${t}.inputs.${a}`,c.code,c.reason))}return i}s(bJ,"inputIssues");function vJ(e,n,t,r){let i=t,o=Array.isArray(i.inputs)?i.inputs.filter(we).map(de):[];if(!we(r)||!o.includes(de(r)))return{code:zr.prefillNotDeclared,reason:{de:"Die Vorbelegung der Teilnehmenden ist keine der Vorgaben ('inputs') der Aufgabe.",en:"The participants' prefill is none of the task's inputs ('inputs')."}};let a=s(c=>({code:zr.prefillType,reason:c}),"prefillType"),l=JN(i),d=Cl(e,r);if(d===void 0)return null;if(rt(d)==="staffUser")return l.length===1?null:a({de:"Eine Personenliste belegt nur vor, wenn 'feedback.tasks' genau eine Feedback-Art nennt \u2014 sonst w\xE4re offen, wer welche Art gibt.",en:"A list of persons prefills only when 'feedback.tasks' names exactly one feedback kind \u2014 otherwise who gives which kind would be open."});if(d==="taskAssignment"){let u=td(kJ(n,r)?.tasks).filter(p=>!l.includes(p));return u.length===0?null:a({de:`Die Zuordnung ordnet ${u.map(p=>`"${p}"`).join(", ")} zu, die 'feedback.tasks' nicht nennt.`,en:`The assignment assigns ${u.map(p=>`"${p}"`).join(", ")}, which 'feedback.tasks' does not name.`})}return a({de:`Vorbelegt werden Teilnehmende nur aus Personen ('person') oder einer Zuordnung ('assignment'), nicht aus "${d}".`,en:`Participants are prefilled only from persons ('person') or an assignment ('assignment'), not from "${d}".`})}s(vJ,"participantPrefillRefusal");function xJ(e,n,t,r){let i=dk(t)?.prefill;if(i===void 0)return[];let o=vJ(e,n,t,i);return o===null?[]:[pa(`${r}.result.participants.prefill`,o.code,o.reason)]}s(xJ,"prefillIssues");function SJ(e,n){return HN(e).some(t=>td(t.tasks).includes(n))}s(SJ,"belongsToOptionalAction");function AJ(e,n,t){let r=n.key,i=Mo(e).find(c=>c.key===t),o=s(c=>({code:zr.feedbackTasks,reason:c}),"feedbackTasks");if(i===void 0)return[o({de:`"${t}" ist keine Aufgabe dieses Knotens.`,en:`"${t}" is no task of this node.`})];let a=[];i.feedback!==!0&&a.push(o({de:`"${t}" ist keine Feedback-Aufgabe ('feedback: true').`,en:`"${t}" is no feedback task ('feedback: true').`})),HN(e).some(c=>td(c.tasks).includes(t))&&a.push(o({de:`"${t}" steht in den Aufgaben einer optionalen Aktion \u2014 eine Personenzeile entsteht nur beim Buchen.`,en:`"${t}" is among an optional action's tasks \u2014 a person row exists only through a booking.`}));let l=Mo(e).find(c=>c.key!==r&&JN(c).includes(t));l!==void 0&&a.push(o({de:`"${t}" wird auch von "${String(l.key)}" angelegt \u2014 jede Feedback-Art geh\xF6rt zu genau einem Termin.`,en:`"${t}" is also created by "${String(l.key)}" \u2014 each feedback kind belongs to exactly one appointment.`}));let d=["when","blocks"].filter(c=>i[c]!==void 0);return d.length>0&&a.push(o({de:`"${t}" tr\xE4gt ${d.map(c=>`'${c}'`).join(", ")} \u2014 eine Personenzeile entsteht nur beim Buchen und h\xE4lt nur ihre Runde.`,en:`"${t}" carries ${d.map(c=>`'${c}'`).join(", ")} \u2014 a person row exists only through a booking and holds only its round.`})),i.optional!==void 0&&a.push({code:zr.feedbackOptional,reason:{de:`"${t}" ist optional \u2014 eine Personenzeile h\xE4lt ihre Runde und damit die Pause, sie kann nicht \xFCbersprungen werden.`,en:`"${t}" is optional \u2014 a person row holds its round and with it the pause; it cannot be skipped.`}}),a}s(AJ,"participantFeedbackRefusals");function EJ(e,n,t){let r=dk(n);if(r===null||r.feedback===void 0)return[];let i=String(n.key),o=`${t}.result.participants.feedback`,a=Wr(r.feedback),l=a?.tasks,d=[],c=s((p,h,w=zr.feedbackTasks)=>d.push(pa(p,w,h)),"fail");if(!Array.isArray(l)||l.length===0||l.some(p=>typeof p!="string")||new Set(l).size!==l.length)return c(`${o}.tasks`,{de:"'feedback.tasks' nennt mindestens eine Feedback-Aufgabe, jede einmal.",en:"'feedback.tasks' names at least one feedback task, each once."}),d;let u=a?.dueDaysAfterEnd;(typeof u!="number"||!Number.isInteger(u)||u<0||u>lk)&&c(`${o}.dueDaysAfterEnd`,{de:`'feedback.dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${lk}.`,en:`'feedback.dueDaysAfterEnd' is a whole number from 0 to ${lk}.`}),SJ(e,i)||c(o,{de:`Aufgabe "${i}" legt Personenzeilen an, geh\xF6rt aber zu keiner optionalen Aktion \u2014 Personenzeilen geh\xF6ren zur Runde einer Aktion.`,en:`Task "${i}" creates person rows but belongs to no optional action \u2014 person rows belong to an action's round.`});for(let p of l)for(let h of AJ(e,n,p))c(`${o}.tasks`,h.reason,h.code);return d}s(EJ,"feedbackIssues");function TJ(e,n){let t=QN(e,n)?.personTasks??new Set;return Mo(e).filter(r=>r.feedback===!0&&typeof r.key=="string"&&t.has(r.key)).map(r=>r.key)}s(TJ,"assignableFeedbackTasks");function $J(e,n,t){let r=Wr(n.result);if(r?.kind!=="record"||!Array.isArray(r.fields))return[];let i=TJ(e,String(n.key)),o=new Map(Mo(e).map(l=>[l.key,l])),a=[];for(let[l,d]of r.fields.entries()){let c=Wr(d);if(c?.type!=="assignment")continue;let u=td(c.tasks).filter(p=>o.get(p)?.feedback===!0&&!i.includes(p));u.length!==0&&a.push(pa(`${t}.result.fields.${l}.tasks`,zr.recordAssignment,{de:`Feld "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} legt kein Termin derselben optionalen Aktion an ('participants.feedback.tasks') \u2014 die Zuordnung h\xE4tte keine Zeile, die sie erh\xE4lt.`,en:`Field "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} is created by no appointment of the same optional action ('participants.feedback.tasks') \u2014 the assignment would have no row to receive it.`}))}return a}s($J,"assignmentIssues");function ZN(e,n){let t=[];for(let r of Mo(n)){if(typeof r.key!="string")continue;let i=`nodes.${n.id}.tasks.${r.key}`;t.push(...bJ(n,r,i)),t.push(...xJ(e,n,r,i)),t.push(...EJ(n,r,i)),t.push(...$J(n,r,i))}return t}s(ZN,"taskInputIssues");var Tt={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 $t(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s($t,"issue");function RJ(e,n,t){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===t&&a===n}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(RJ,"blockersOf");function XN(e){let{graph:n,node:t,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${t.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(n,t.id,"de")}\u201C (${t.id})`,en:`Task "${o}" on node "${_e(n,t.id,"en")}" (${t.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[$t(`${a}.familyRequest`,Tt.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($t(`${a}.familyRequest.${c[0]}`,Tt.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($t(`${a}.familyRequest`,Tt.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($t(`${a}.familyRequest`,Tt.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($t(`${a}.kind`,Tt.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($t(`${a}.${k}`,Tt.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($t(`${a}.blocks`,Tt.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 RJ(n.nodes,t.id,o))d.push($t(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,Tt.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($t(`${a}.params.dueInDays`,Tt.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($t(`${a}.familyRequest.fields`,Tt.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(!we(k))continue;let y=de(k);if(w.has(y)){d.push($t(`${a}.familyRequest.fields`,Tt.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} more than once.`}));continue}w.add(y),un(k)||d.push($t(`${a}.familyRequest.fields`,Tt.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(XN,"familyRequestIssues");function eC(e){let n=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"&&n.has(a));return o.length<=1?[]:[$t(`nodes.${e.id}.optionalActions.${i}.tasks`,Tt.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(eC,"familyRequestActionIssues");function nC(e,n){let t=e.nodes,r=new Map;for(let a of t)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)un(l)&&r.set(de(l),l);if(r.size===0)return[];let i=s(a=>{let l=Ur(n,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(un):!we(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return t.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(de(y)));return k.length===0?[]:[{...$t(`nodes.${a.id}.requiresOneOf`,Tt.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(nC,"familyRequestDeadlockWarnings");var ck={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,view:!0,familyRequest:!0,optional:!0,inputs:!0,params:!0},uk={appointment:s((e,n)=>({de:`Aufgabe "${e}" an ${n.de}: \`appointment\` (Terminaufgabe) gibt es nicht mehr \u2014 ein Termin hat keine Leitung, die sie hielte. Was die Teilnehmenden nach dem Termin festhalten, ist je Person eine R\xFCckmeldung (\`result.participants.feedback\` der Terminvereinbarung).`,en:`Task "${e}" on ${n.en}: \`appointment\` (appointment task) no longer exists \u2014 an appointment has no lead to hold it. What the participants record after the appointment is one feedback per person (\`result.participants.feedback\` of the booking task).`}),"appointment")};function IJ(e){let n=Je(e);return new Map((typeof n.workItemTemplates=="function"?n.workItemTemplates(e):[]).map(t=>[t.key,t]))}s(IJ,"intrinsicTemplatesOf");function tC(e,n,t){if(t!==void 0&&typeof t!="string")return null;let r=t??n,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=Je(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:IJ(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(tC,"resolveBlocksTargetNode");function OJ(e){let n=new Map;for(let r of nr(e.nodes)){let i=n.get(r.source)??[];i.push(r.target),n.set(r.source,i)}let t=new Map;return r=>{let i=t.get(r);if(i!==void 0)return i;let o=new Set,a=[...n.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...n.get(l)??[]))}return t.set(r,o),o}}s(OJ,"reachability");function rC(e){let n=[],t=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;t.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("::");n.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=t.get(o);l!==void 0&&t.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of t.keys())i(o,[]);return n}s(rC,"checkBlocksCycles");function _J(e){let{requiresOneOf:n,optionalActions:t}=e;if(!Array.isArray(n)||!Array.isArray(t))return new Set;let r=new Set(n.filter(o=>typeof o=="string")),i=new Set;for(let o of t)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(_J,"tasksOfRequiresOneOf");function iC(e){if(typeof e!="object"||e===null)return!1;let{de:n,en:t}=e;return typeof n=="string"&&n.trim().length>0&&typeof t=="string"&&t.trim().length>0}s(iC,"isFilledBilingual");var PJ=["blocks","gatesNode","locksEvidence","completableIf"];function NJ(e,n){let t={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},r=[];e.feedback!==!0&&r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${t.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${t.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;if(e.kind!=="task"||typeof i?.kind!="string"||!Qy({kind:i.kind,writes:i.writes})){let a=e.kind==="task"&&i?.writes!==void 0,l={de:e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}${a?" mit writes":""}`,en:e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}${a?" with writes":""}`};r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackNeedsProse] ${t.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext, einer Empfehlung oder einer Auswahl ohne 'writes' \u2014 ein Wert, den ein sp\xE4terer Schritt liest, k\xE4me von einem wom\xF6glich weitergeleiteten Link; erhalten ${l.de}.`,en:`[workItems/feedbackNeedsProse] ${t.en} is a feedback task, so it closes with free text, a recommendation or a choice without 'writes' \u2014 a value a later step reads would come from a link that may have been forwarded; got ${l.en}.`}))}let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${t.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] ${t.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(NJ,"feedbackTaskIssues");function CJ(e,n){let t=[],r={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!iC(i.skipLabel))&&t.push(En(`${n.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"&&t.push(En(`${n.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"||!Qy({kind:a.kind,writes:a.writes}))&&t.push(En(`${n.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=PJ.filter(d=>e[d]!==void 0);return l.length>0&&t.push(En(`${n.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.`})),n.requiredByRule&&t.push(En(`${n.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.`})),t}s(CJ,"optionalTaskIssues");function En(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(En,"issue");function oC(e,n){let t=[],r=OJ(e),i=new Set(ua(e).map(o=>o.key));t.push(...nC(e,n));for(let o of e.nodes){let a=o,l=YN(a);t.push(...eC(a));let d=_J(a);t.push(...ZN(e,a));let c=new Map((Array.isArray(a.tasks)?a.tasks:[]).filter(u=>typeof u.key=="string").map(u=>[u.key,{feedback:u.feedback===!0}]));for(let u of Array.isArray(a.tasks)?a.tasks:[]){let p=typeof u.key=="string"?u.key:"?",h=`nodes.${o.id}.tasks.${p}`,w=u.kind,k=u.result,y=u.blocks,b=typeof y?.node=="string"&&y.node!==o.id?y.node:void 0;if(typeof y?.templateKey=="string"){let P=typeof y.node=="string"?y.node:o.id,A=e.nodes.find(oe=>oe.id===P),U=(Array.isArray(A?.tasks)?A.tasks:[]).find(oe=>oe.key===y.templateKey)?.blocks;typeof U?.node=="string"&&U.node!==P&&t.push(En(`${h}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${p}" auf Knoten "${o.id}" h\xE4lt "${y.templateKey}" auf Knoten "${P}" 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 "${p}" on node "${o.id}" holds back "${y.templateKey}" on node "${P}" \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(b!==void 0){let P=b;e.nodes.some(A=>A.id===P)&&!r(o.id).has(P)&&t.push(En(`${h}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${p}" auf Knoten "${o.id}" blockiert Knoten "${P}", 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 "${p}" on node "${o.id}" blocks node "${P}", 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.`})),(k===void 0||!Ms(k.kind))&&t.push(En(`${h}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${P}"), 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 "${p}" on node "${o.id}" blocks another node ("${P}") 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(p)&&t.push(En(`${h}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${p}" 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 "${p}" 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 P of vP(String(w),k,{channelKeys:i,nodeTasks:c,...n?.billingItemKeys!==void 0?{billingItemKeys:n.billingItemKeys}:{},...n?.offerProgram!==void 0?{offerProgram:n.offerProgram}:{}}))t.push(En(`${h}.${P.field}`,{de:`${P.code} ${P.message.de} (Task "${p}" auf Knoten "${o.id}").`,en:`${P.code} ${P.message.en} (task "${p}" on node "${o.id}").`}));let E=u.when,T=s((P,A,M)=>{!we(A)||un(A)||t.push(En(P,{de:`[workItems/evidenceNotFormField] ${M} auf Task "${p}" (Knoten "${o.id}") nennt ${je(e,A,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${M} on task "${p}" (node "${o.id}") names ${je(e,A,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");E!==void 0?(T(`${h}.when`,E,"'when'"),u.onConditionReturn!=="respawn"&&u.onConditionReturn!=="stayClosed"&&t.push(En(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (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 "${p}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):u.onConditionReturn!==void 0&&t.push(En(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${p}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${p}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let R=u.reads;if(R!==void 0)if(!Array.isArray(R))t.push(En(`${h}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${p}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${p}" (node "${o.id}") must be a list of field addresses.`}));else for(let[P,A]of R.entries())T(`${h}.reads.${P}`,A,"'reads'");let D=u.locksEvidence,L=s((P,A)=>t.push(En(`${h}.locksEvidence`,{de:`[workItems/${P}] Task "${p}" (Knoten "${o.id}") ${A.de}`,en:`[workItems/${P}] Task "${p}" (node "${o.id}") ${A.en}`})),"lockIssue");D!==void 0&&D!==!0&&L("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(D)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(D)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),D===!0&&(R===void 0&&E===void 0&&L("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."}),(k===void 0||!Ms(k.kind))&&L("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(p)&&L("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."})),t.push(...XN({graph:e,node:a,task:u,onTrigger:l,specCtx:n}));let _=Object.keys(u).filter(P=>!Object.hasOwn(ck,P)&&!Object.hasOwn(uk,P));_.length>0&&t.push(En(`${h}.${_[0]}`,{de:`[workItems/unknownKey] Task "${p}" (Knoten "${o.id}") tr\xE4gt ${_.map(P=>`'${P}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(ck).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${p}" (node "${o.id}") carries ${_.map(P=>`'${P}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(ck).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let v=u.description;v!==void 0&&!iC(v)&&t.push(En(`${h}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${p}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(v)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${p}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(v)}.`})),u.feedback!==void 0&&t.push(...NJ(u,{key:p,nodeId:o.id,base:h})),u.optional!==void 0&&t.push(...CJ(u,{key:p,nodeId:o.id,base:h,requiredByRule:d.has(p)}))}}return t}s(oC,"checkNodeTasks");function sC(e){let n=e.indexOf(":"),t=n===-1?"":e.slice(0,n),r=n===-1?"":e.slice(n+1).trim();if(t==="artifact"&&r.length>0)return{kind:t,key:r};let i=ti(r);return t==="field"&&i!==null?{kind:t,address:i}:ae("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel> (auch der Slot eines anderen Knotens) oder field:$node.<Formular>.admission.<Feld>.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key> (another node's slot too) or field:$node.<form>.admission.<field>.`})}s(sC,"parseTaskDocumentRef");function fk(e){return e.kind==="artifact"?`artifact:${e.key}`:`field:${de(e.address)}`}s(fk,"taskDocumentId");function pi(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(pi,"issue");function aC(e){return Array.isArray(e.tasks)?e.tasks:[]}s(aC,"tasksOf");function rd(e){let n=new Map;for(let t of e){let{id:r,artifacts:i}=t;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&n.set(o.key,[...n.get(o.key)??[],{nodeId:r,slot:o}])}return n}s(rd,"artifactSlotDeclarations");function DJ(e){return e.flatMap(n=>{let{id:t,artifacts:r}=n;return(Array.isArray(r)?r:[]).filter(i=>!wp(i?.type)).map(i=>({nodeId:String(t),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(DJ,"unknownArtifactSlotTypes");function lC(e){let n=[];for(let{nodeId:t,slotKey:r,type:i}of DJ(e.nodes))n.push(pi(`nodes.${t}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${t}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${na.join(", ")}.`,en:`[artifact/unknownType] Node "${t}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${na.join(", ")}.`}));for(let[t,r]of rd(e.nodes))for(let i of r.slice(1))n.push(pi(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${t}", 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 "${t}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return n}s(lC,"checkArtifactSlotKeys");function FJ(e,n,t,r=rd(e.nodes)){let i=r.get(n)?.[0]?.nodeId;return i===void 0?{reason:"unknown"}:Ys(e,i,t)?null:{reason:"notBefore",owner:i}}s(FJ,"slotLinkRefusal");function dC(e){if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let t of e){let r=typeof t=="object"&&t!==null?t:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)n.push({kind:"artifact",key:r.key});else if(r.kind==="field"&&i==="address,kind")n.push({kind:"field",address:r.address});else return null}return n}s(dC,"authoredRefs");function cC(e){let n=[],t=rd(e.nodes);for(let r of e.nodes)for(let i of aC(r)){if(i.documents===void 0)continue;let o=typeof i.key=="string"?i.key:"?",a=`nodes.${r.id}.tasks.${o}.documents`,l={de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},d=dC(i.documents);if(d===null){n.push(pi(a,{de:`[workItems/documentsInvalid] 'documents' auf ${l.de} muss eine nicht leere Liste von { kind: 'artifact', key } (Dokument-Slot eines Knotens) oder { kind: 'field', address } (Dateifeld eines Formulars) sein, erhalten ${JSON.stringify(i.documents)} \u2014 ein { kind: 'document', address } schreibt \`plexus-cli offer upgrade\` auf den Slot um.`,en:`[workItems/documentsInvalid] 'documents' on ${l.en} must be a non-empty list of { kind: 'artifact', key } (document slot of a node) or { kind: 'field', address } (file field of a form), got ${JSON.stringify(i.documents)} \u2014 \`plexus-cli offer upgrade\` rewrites a { kind: 'document', address } onto its slot.`}));continue}let c=new Set;for(let u of d){if(u.kind!=="artifact"&&!we(u.address))continue;let p=u.kind==="artifact"?fk(u):fk({kind:"field",address:u.address});if(c.has(p)&&n.push(pi(a,{de:`[workItems/documentsDuplicate] ${l.de} verweist zweimal auf ${p}.`,en:`[workItems/documentsDuplicate] ${l.en} refers to ${p} twice.`})),c.add(p),u.kind==="artifact"){let h=FJ(e,u.key,r.id,t);h?.reason==="unknown"?n.push(pi(a,{de:`[workItems/documentsUnknownArtifact] ${l.de} verweist auf das Dokument "${u.key}", aber kein Knoten deklariert einen solchen Slot.`,en:`[workItems/documentsUnknownArtifact] ${l.en} refers to the document "${u.key}", but no node declares such a slot.`})):h?.reason==="notBefore"&&n.push(pi(a,{de:`[workItems/documentsNotBefore] ${l.de} verweist auf das Dokument "${u.key}" des Knotens "${h.owner}", der nicht auf jedem Weg vor "${r.id}" liegt \u2014 auf einem Weg an ihm vorbei g\xE4be es das Dokument nie.`,en:`[workItems/documentsNotBefore] ${l.en} refers to the document "${u.key}" of node "${h.owner}", which does not lie on every path before "${r.id}" \u2014 on a path around it the document would never exist.`}))}u.kind==="field"&&!un(u.address)&&n.push(pi(a,{de:`[workItems/documentsInvalid] ${l.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,u.address,"de")}.`,en:`[workItems/documentsInvalid] ${l.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,u.address,"en")}.`}))}}return n}s(cC,"checkTaskDocuments");function uC(e,n){let t=[];for(let r of e.nodes)for(let i of aC(r)){let o=dC(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"||!un(d.address))continue;let c=Ur(n,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Js("taskDocument",Hs(c));if(p==="repeated"){t.push(pi(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"&&t.push(pi(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 t}s(uC,"checkTaskDocumentFields");var mk=["form","artifact","field"],ha=["coverLetter","contract"],fC=/^[A-Za-z0-9_.-]+$/;function LJ(e){return ha.includes(e)}s(LJ,"isArtifactPart");function ma(e){return ae("INVALID",{de:`Ansichts-Adresse "${e}" ist ung\xFCltig \u2014 erwartet form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${ha.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`View address "${e}" is invalid \u2014 expected form:<form node>#<view>, artifact:<slot>[#${ha.join("|")}] or field:$node.<form>.admission.<field>.`})}s(ma,"invalid");function hk(e){let n=e.indexOf(":");if(n===-1)return ma(e);let t=e.slice(0,n),r=e.slice(n+1);if(t==="field"){let l=ti(r);return l===null?ma(e):{kind:t,address:l}}let i=r.indexOf("#"),o=i===-1?r:r.slice(0,i),a=i===-1?null:r.slice(i+1);return fC.test(o)?t==="form"?a!==null&&fC.test(a)?{kind:t,form:o,view:a}:ma(e):t==="artifact"?a===null?{kind:t,slot:o}:LJ(a)?{kind:t,slot:o,part:a}:ma(e):ma(e):ma(e)}s(hk,"parseViewAddress");function pC(e){let n=qJ(e);if(n===null)return null;let t=MJ(n);return t!==null&&JSON.stringify(pk(t))===JSON.stringify(pk(e))?t:null}s(pC,"viewAddressOf");function MJ(e){try{return hk(e)}catch{return null}}s(MJ,"tryParseViewAddress");function qJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.kind==="form"&&typeof n.form=="string"&&typeof n.view=="string")return`form:${n.form}#${n.view}`;if(n.kind==="artifact"&&typeof n.slot=="string")return n.part===void 0?`artifact:${n.slot}`:typeof n.part=="string"?`artifact:${n.slot}#${n.part}`:null;if(n.kind==="field"&&n.address!==null&&typeof n.address=="object"){let t=n.address;return typeof t.scope!="string"||typeof t.key!="string"?null:`field:${de(t)}`}return null}s(qJ,"spellingOf");function pk(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([n],[t])=>n<t?-1:n>t?1:0).map(([n,t])=>[n,pk(t)]))}s(pk,"canonical");function mC(e){switch(e.kind){case"form":return`form:${e.form}#${e.view}`;case"artifact":return e.part===void 0?`artifact:${e.slot}`:`artifact:${e.slot}#${e.part}`;case"field":return`field:${de(e.address)}`}}s(mC,"formatViewAddress");var gk=["form","documents"],KJ=/^[a-z][a-zA-Z0-9_-]*$/;function jJ(e){let n=new Map,t=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])n.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){n.set(i.key,"other");for(let o of i.itemTemplate)n.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(jJ,"fieldPlaces");function hC(e,n,t){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!KJ.test(o)){r.push({severity:"error",path:`${t(a)}.key`,code:"view.invalid-key",message:{de:`${n.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${n.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:`${t(a)}.key`,code:"view.duplicate-key",message:{de:`${n.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${n.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(hC,"keyIssues");function VJ(e,n,t){return e==="document"?null:e===void 0?{severity:"error",path:t,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${n}'.`,en:`View: the form has no field '${n}'.`}}:e==="row"?{severity:"error",path:t,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${n}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${n}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:t,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${n}' enth\xE4lt keine Datei.`,en:`View: the field '${n}' holds no file.`}}}s(VJ,"fieldIssue");function BJ(e,n,t){let r=[];gk.includes(e.key)&&r.push({severity:"error",path:`${n}.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:`${n}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...hC(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${n}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${n}.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=VJ(t.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(BJ,"viewIssues");function UJ(e){if(!Array.isArray(e))return"views";for(let[n,t]of e.entries()){let r=t?.groups;if(!Array.isArray(r))return`views[${n}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${n}].groups[${i}].fields`}}return null}s(UJ,"malformedAt");function gC(e){let n=e.views;if(n===void 0)return[];let t=UJ(n);if(t!==null)return[{severity:"error",path:t,code:"view.malformed",message:{de:`${t} 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:`${t} 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=jJ(e);return[...hC(n.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...n.flatMap((i,o)=>BJ(i,`views[${o}]`,r))]}s(gC,"formViewIssues");function ga(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(ga,"issue");function yC(e,n,t,r,i){let o=pC(e);if(o===null)return[ga(n,{de:`[view/invalid] 'view' auf ${t.de} ist keine Ansichts-Adresse \u2014 erwartet { kind: ${mk.join(" | ")}, \u2026 }: form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${ha.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] 'view' on ${t.en} is no view address \u2014 expected { kind: ${mk.join(" | ")}, \u2026 }: form:<form node>#<view>, artifact:<slot>[#${ha.join("|")}] or field:$node.<form>.admission.<field>.`})];let a=mC(o);switch(o.kind){case"artifact":return r.has(o.slot)?[]:[ga(n,{de:`[view/unknownSlot] ${t.de} nennt "${a}", aber kein Knoten dieses Graphen hat den Dokument-Slot "${o.slot}".`,en:`[view/unknownSlot] ${t.en} names "${a}", but no node of this graph has the document slot "${o.slot}".`})];case"form":case"field":{let l=o.kind==="form"?o.form:o.address.scope==="node"?o.address.owner:null;if(l===null)return[ga(n,{de:`[view/invalid] ${t.de} nennt "${a}" \u2014 ein Dateifeld liegt in einem Formular: field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] ${t.en} names "${a}" \u2014 a file field lives in a form: field:$node.<form>.admission.<field>.`})];let d=i?.formViewKeysByFormNode;if(d===void 0)return[];let c=d.get(l);return c===void 0?[ga(n,{de:`[view/unknownForm] ${t.de} nennt "${a}", aber kein Formularknoten hei\xDFt so.`,en:`[view/unknownForm] ${t.en} names "${a}", but no form node has that id.`})]:o.kind==="field"?[]:c.has(o.view)||gk.includes(o.view)?[]:[ga(n,{de:`[view/unknownView] ${t.de} nennt "${a}", aber das Formular "${o.form}" hat keine Ansicht "${o.view}".`,en:`[view/unknownView] ${t.en} names "${a}", but the form "${o.form}" has no view "${o.view}".`})]}}}s(yC,"viewIssues");function wC(e,n){let t=[],r=new Set(rd(e.nodes).keys());for(let i of e.nodes){if(i.view!==void 0){let o={de:`Knoten "${i.id}"`,en:`node "${i.id}"`};i.type!=="decision"?t.push(ga(`nodes.${i.id}.view`,{de:`[view/invalid] ${o.de}: 'view' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[view/invalid] ${o.en}: 'view' on a node applies to a decision only; a task carries its own.`})):t.push(...yC(i.view,`nodes.${i.id}.view`,o,r,n))}for(let o of Array.isArray(i.tasks)?i.tasks:[]){if(o.view===void 0)continue;let a=String(o.key);t.push(...yC(o.view,`nodes.${i.id}.tasks.${a}.view`,{de:`Task "${a}" (Knoten "${i.id}")`,en:`Task "${a}" (node "${i.id}")`},r,n))}}return t}s(wC,"checkTaskViews");var Lt="traeger",kC={de:"Tr\xE4ger",en:"Provider"};function ya(e){let n=e.inputs?.[Lt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(ya,"traegerKeyOfNode");var Kp={name:"input.traeger.name",address:"input.traeger.anschrift"},Bwe=Object.values(Kp);var bC="governedDocument",qo="prepareDocument",id="prepareDocument:revision",Ar="releaseApproval",Ko="documentResponse",Yi="coverLetterResponse",jp="confirmCoverLetter",Vp="requestCoverLetterRevision",wa="coverLetterConfirmation",Yr="responseCheck",Bp="returnSigned";var vC="requestApproval";var xC="issueDocument",SC="correctInPlace",AC="rescindAndReissue",Up="requestChange";var ka="releaseArtifact",ht="signingRecovery",Gp="resendESignature",jo="switchToPaper";var od=new Set([qo,id]),EC=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],zp=["upload","resolver","template","none"],Vo=1,Bo=366,mi="responseDueInDays";function Uo(e){let n=e.inputs?.[wa];return n?.kind==="literal"&&n.value===!0}s(Uo,"coverLetterConfirmationOf");function sd(e){let n=e.inputs?.[mi];return n?.kind==="literal"&&ad(n.value)?n.value:void 0}s(sd,"responseDueInDaysForVocabulary");function ad(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Vo&&e<=Bo}s(ad,"isValidResponseDueInDays");var Wp=["generatedAt","responseDueInDays","countersignature"],Go=["release","none"],Yp=["confirm","signedUpload","signedUploadChecked","eSignature"];var GJ={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"}}},TC={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"}}},$C={...TC,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},zJ={...$C,kind:"eSignature",issuesBy:"provider"},hi={confirm:GJ,signedUpload:TC,signedUploadChecked:$C,eSignature:zJ};function gi(e){let n=e.responseStrategy;if(typeof n=="string"&&n in hi)return hi[n];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(gi,"responseStrategyOf");function Hp(e){if(e.type!==bC||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in hi?hi[n].acceptEvent==="contractEvent":!1}s(Hp,"isFamilySignedContractNode");function va(e){return e.label}s(va,"governedDocTitle");function yk(e){return e.approval==="release"?vC:xC}s(yk,"submitActionId");function RC(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[yk(e)],gatesNode:!0,advancesNode:!0}}s(RC,"producerTemplate");function WJ(e){return e.titles?.respond??e.label}s(WJ,"responseTitle");var ba={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Jp(e){let n=gi(e),t=[];if(e.production!=="none"&&t.push(RC(e,qo,e.titles?.prepare??ba),RC(e,id,e.titles?.revise??ba)),e.approval==="release"&&t.push({key:Ar,recipient:"internal",title:e.titles?.approve??ba,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Ko,recipient:"external",title:WJ(e),unlocks:n.producesResponseArtifact?[n.checksReturn?Bp:n.acceptOutcomeId,n.declineOutcomeId,Up]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...sd(e)!==void 0?{dueInDays:sd(e)}:{}}),Uo(e)){let r=va(e);t.push({key:Yi,recipient:"external",title:{de:`${r.de}: Angebot best\xE4tigen`,en:`${r.en}: confirm offer`},unlocks:[jp,Vp,n.declineOutcomeId],advancesNode:!0,...sd(e)!==void 0?{dueInDays:sd(e)}:{}})}if(n.checksReturn&&t.push({key:Yr,recipient:"internal",title:e.titles?.check??ba,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=va(e);t.push({key:ht,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Gp,jo],gatesNode:!1,advancesNode:!1})}return t}s(Jp,"governedDocIntrinsicTemplates");function YJ(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(YJ,"governedDocSlot");function Qp(e){return YJ(e).key}s(Qp,"governedDocSlotKey");var tr="processFooter";var Zp="countersign",wk="countersign",IC="countersigned",OC="countersigning",_C="countersigned";var PC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},ld=["scan","eSignature"],Xp="service_provider:1",NC=["countersigning","awaitingSignature","signatureStalled","done"],CC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function DC(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(DC,"traegerSignatoryMissingReason");function rr(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(rr,"issue");function em(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&we(r)&&r.scope==="node"&&r.owner===n})}s(em,"countersignersOf");function dd(e){return e.signing==="eSignature"}s(dd,"isElectronic");function HJ(e,n){if(n===void 0||n.sendable||!dd(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[rr(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(HJ,"countersignProviderIssues");function JJ(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return Hp(r)||i.push("sourceNotCheckedContract"),em(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(JJ,"countersignContractRefusals");function FC(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(FC,"validDueInDays");function QJ(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!ld.includes(o))return[rr(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?.[ht];if(!dd(e))return a===void 0?[]:[rr(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 a===void 0&&l.push(rr(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(...ZJ(e,n,t),...XJ(e,n,t),...HJ(e,t?.signingProvider)),l}s(QJ,"signingIssues");function MC(e,n){let t=e.contract;if(!(!we(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(MC,"contractNodeOf");function ZJ(e,n,t){let r=MC(e,n),i=r===void 0?null:ya(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[rr(e,"signing",DC(o.name))]}s(ZJ,"traegerSignatoryIssues");function XJ(e,n,t){let r=MC(e,n);if(r===void 0)return[];let i=t?.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(rr(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(Xp)||l.push(rr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Xp}/ \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:${Xp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(XJ,"traegerAnchorIssues");var kk=100;async function e4(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(kk+1);t.length>kk&&F(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${kk} rows`);let r=t.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)===ht)?"signatureStalled":r.some(o=>i(o)===Zp)?"countersigning":dd(n.node)?"awaitingSignature":"done"}s(e4,"countersignCurrentState");var LC={[OC]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:en(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("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."))}},qC={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:IC,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:LC,progressEvents:qn(LC),notificationEvents:s(()=>[{id:_C,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:wk,kind:"internal",label:PC,surface:tr,availableIn:["countersigning"]},...dd(e)?[{id:jo,kind:"internal",surface:tr,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Zp,recipient:"internal",title:e.titles?.countersign??ba,unlocks:[wk],advancesNode:!0,...FC(e)!==void 0?{dueInDays:FC(e)}:{}},...dd(e)?[{key:ht,recipient:"internal",title:CC,unlocks:[jo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:NC,currentState:e4,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id;e.assign?.[Zp]===void 0&&r.push(rr(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.`})),Ci(e.titles?.countersign)||r.push(rr(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(rr(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(...QJ(e,n,t));let d=e.contract;if(!we(d))return r;let c=JJ(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(rr(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=em(n,u.id).filter(h=>h.id!==e.id);r.push(rr(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 n4(e){return Hp(e)?ya(e):null}s(n4,"traegerSignerOf");var t4=s(e=>e.type==="end"&&No(e)==="approved","isApprovedEnd");function KC(e){let n=[];for(let t of e.nodes){let r=n4(t);if(r===null)continue;let i=em(e,t.id).map(u=>u.id),o=H_(e,t.id,new Set(i),t4);if(o===null)continue;let a=t.label?.de||t.id,l=t.label?.en||t.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${t.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${t.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.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}" (${t.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 (${t.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}" (${t.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}`};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}`,reason:c,severity:"error"})}return n}s(KC,"checkCountersignCoverage");var r4=[{key:"blocks",why:{de:"sie h\xE4lt nichts zur\xFCck, sie ist mit dem Ausl\xF6sen erledigt",en:"it holds nothing back, it is done with the press"}},{key:"when",why:{de:"sie entsteht bei jedem Ausl\xF6sen",en:"it is created on every press"}},{key:"optional",why:{de:"wer ausl\xF6st, beantwortet sie immer",en:"whoever presses always answers it"}},{key:"familyRequest",why:{de:"sie fragt nicht die Familie",en:"it does not ask the family"}},{key:"feedback",why:{de:"sie beantwortet die ausl\xF6sende Person, nicht ein Link",en:"the presser answers it, not a link"}},{key:"completableIf",why:{de:"sie wird beim Ausl\xF6sen erledigt, eine Vorbedingung w\xFCrde jedes Ausl\xF6sen ablehnen",en:"it is completed at the press, a precondition would refuse every press"}},{key:"locksEvidence",why:{de:"eine offene Korrektur w\xFCrde jedes Ausl\xF6sen ablehnen",en:"an open correction would refuse every press"}}];function jC(e){let{nodeId:n,bindingKey:t,binding:r}=e,i=[],o=`nodes.${n}.optionalActions.${t}.input`,a=s((u,p=o)=>{i.push({layer:"GRAPH",kind:"nodeRule",path:p,severity:"error",reason:{de:`[optionalAction/input] Optionale Aktion "${t}" auf Knoten "${n}": ${u.de}`,en:`[optionalAction/input] Optional action "${t}" on node "${n}": ${u.en}`}})},"push");if(r.input===void 0)return r.submitLabel!==void 0&&a({de:"'submitLabel' beschriftet das Absenden des Eingabedialogs \u2014 ohne 'input' \xF6ffnet das Ausl\xF6sen keinen Dialog.",en:"'submitLabel' names the input dialog's submit button \u2014 without 'input' the press opens no dialog."},`nodes.${n}.optionalActions.${t}.submitLabel`),i;let l=r.input;if(typeof l!="string"||l.trim().length===0)return a({de:"'input' muss der Schl\xFCssel einer ihrer Aufgaben sein.",en:"'input' must be the key of one of its tasks."}),i;let d=Array.isArray(r.tasks)?r.tasks:[];if(!d.includes(l))return a({de:`Die Eingabe "${l}" ist keine ihrer Aufgaben ('tasks') \u2014 die Eingabe geh\xF6rt zur Runde der Aktion.`,en:`The input "${l}" is none of its tasks ('tasks') \u2014 the input belongs to the action's round.`}),i;let c=s(u=>{let p=e.templates.find(h=>h.key===u);return p!==void 0&&p.optional===void 0&&p.blocks===void 0},"holdsNode");d.some(u=>u!==l&&c(u))||a({de:`Neben der Eingabe "${l}" hat die Aktion keine Aufgabe, die den Schritt zur\xFCckh\xE4lt (weder 'optional' noch hinter 'blocks') \u2014 die Runde w\xE4re mit dem Ausl\xF6sen schon erledigt.`,en:`Besides the input "${l}" the action has no task that holds the step (neither 'optional' nor behind 'blocks') \u2014 the round would be done with the press.`});for(let u of i4({nodeId:n,binding:r,templates:e.templates,input:l}))a(u);return i}s(jC,"optionalActionInputIssues");function i4(e){let{nodeId:n,binding:t,templates:r,input:i}=e,o=r.find(u=>u.key===i);if(o===void 0)return[];let a=[];o.result?.kind!=="record"&&a.push({de:`Die Eingabe "${i}" braucht ein Ergebnis der Art 'record' \u2014 nur dessen Werte lesen die anderen Aufgaben der Runde.`,en:`The input "${i}" needs a result of kind 'record' \u2014 only its values are read by the round's other tasks.`});let l=o.assign?.group;typeof t.trigger!="string"?a.push({de:"Mit einer Eingabe braucht die Aktion ein 'trigger'-Team \u2014 die Eingabe ist eine Aufgabe dieses Teams.",en:"With an input the action needs a 'trigger' team \u2014 the input is a task of that team."}):l!==void 0&&l!==t.trigger&&a.push({de:`Die Eingabe "${i}" geh\xF6rt dem Team "${String(l)}", ausgel\xF6st wird die Aktion vom Team "${t.trigger}" \u2014 wer ausl\xF6st, beantwortet die Eingabe, also ist es dasselbe Team.`,en:`The input "${i}" belongs to the team "${String(l)}", the action is pressed by the team "${t.trigger}" \u2014 whoever presses answers the input, so it is the same team.`});let d=o.result,c=d?.fields;for(let u of Array.isArray(c)?c:[])u.evidence===!0&&a.push({de:`Das Feld "${String(u.key)}" der Eingabe "${i}" verlangt eine Datei ('evidence') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(u.key)}" of the input "${i}" demands a file ('evidence') \u2014 the press carries values only.`}),u.suggest!==void 0&&a.push({de:`Das Feld "${String(u.key)}" der Eingabe "${i}" tr\xE4gt einen Vorschlag ('suggest') \u2014 eine Abweichung verlangt eine Begr\xFCndung, das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(u.key)}" of the input "${i}" carries a suggestion ('suggest') \u2014 a departure demands a reason, the press carries values only.`});d?.textRequired===!0&&a.push({de:`Die Eingabe "${i}" verlangt einen Text ('textRequired') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The input "${i}" demands a text ('textRequired') \u2014 the press carries values only.`});for(let{key:u,why:p}of r4)o[u]!==void 0&&a.push({de:`Die Eingabe "${i}" tr\xE4gt '${u}' \u2014 ${p.de}.`,en:`The input "${i}" carries '${u}' \u2014 ${p.en}.`});for(let u of r){let p=u.blocks;p?.templateKey!==i||p.node!==void 0&&p.node!==n||a.push({de:`"${String(u.key)}" h\xE4lt die Eingabe "${i}" per 'blocks' zur\xFCck \u2014 sie ist beim Anlegen der Runde schon erledigt, es gibt nichts zur\xFCckzuhalten.`,en:`"${String(u.key)}" holds the input "${i}" back through 'blocks' \u2014 it is already done when the round is created, there is nothing to hold back.`})}return a}s(i4,"optionalActionInputRefusals");function o4(e){let n="error",t=new Map;for(let a of nr(e.nodes)){let l=t.get(a.source)??[];l.push({id:a.id,target:a.target}),t.set(a.source,l)}let r=[],i=new Set,o=Np(e.nodes.map(a=>a.id),a=>(t.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:n}));return r}s(o4,"checkAcyclic");function s4(e){let n=[],t=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))t.has(l.to)||n.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))&&n.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 n}s(s4,"checkNextTargets");function a4(e){let n=[];for(let t of e.nodes){let r=t.next;if(!r)continue;let i=Cw(t),o=new Set(i?i.map(a=>a.id):[ta]);for(let a of Object.keys(r))o.has(a)||n.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${t.id}.next.${a}`,reason:{de:`${t.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:`${t.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 n}s(a4,"checkNextOutcomesKnown");function l4(e){let n=[],t=new Set(nr(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!t.has(o.id));return r.length===0?n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&n.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&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),n}s(l4,"checkStartEnd");function d4(e){let n=new Map;for(let r of nr(e.nodes))n.set(r.source,(n.get(r.source)??0)+1);let t=[];for(let r of e.nodes)r.type!=="end"&&(n.get(r.id)??0)===0&&t.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 t}s(d4,"checkNoOutgoingEdge");function c4(e){return e.nodes.filter(n=>!Oy(n.id)).map(n=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${n.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${kr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${n.id}": a node id is an identifier without a dot (${kr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(c4,"checkNodeIdFormat");function u4(e){let n=new Set(e.nodes.map(r=>r.id)),t=[];for(let r of nr(e.nodes))n.has(r.source)||t.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"}),n.has(r.target)||t.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 t}s(u4,"checkEdgeEndpoints");function f4(e){let n=[];for(let t of e.nodes)for(let r of t.tasks??[]){let i=r.result;i===null||typeof i!="object"||!(yp in i)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.tasks.${r.key}.result.${yp}`,reason:{de:`[graph/retiredField] Aufgabe "${r.key}": \`primaryHostTeams\` hei\xDFt jetzt \`primaryParticipantTeams\` \u2014 der alte Name wird nicht mehr gelesen, die Teilnehmer-Auswahl zeigt die Teams nicht oben. Bitte umbenennen.`,en:`[graph/retiredField] Task "${r.key}": \`primaryHostTeams\` is now called \`primaryParticipantTeams\` \u2014 the old name is no longer read, so the participant picker does not list the teams first. Please rename it.`},severity:"warning"})}return n}s(f4,"checkRetiredFieldWarnings");var p4=new Set(["countersignature"]);function m4(e){let n=[],t=s((o,a)=>{n.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&&t("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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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(cw[o.type]??{}))c in a&&t(`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:[]){if(c===null||typeof c!="object")continue;let u=String(c.key),p=c.assign;p!==null&&typeof p=="object"&&"userId"in p&&t(`nodes.${o.id}.tasks.${u}.assign.userId`,{de:`Aufgabe "${u}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${u}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`});for(let[h,w]of Object.entries(uk))h in c&&t(`nodes.${o.id}.tasks.${u}.${h}`,w(u,l))}for(let c of uw[o.type]??[])c in a&&t(`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(p_[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&t(`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"&&p4.has(u)&&t(`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 n}s(m4,"checkRetiredDataFields");function xa(e,n){return n?.wiring&&n.layout?{wiring:n.wiring,layout:n.layout}:null}s(xa,"resolveLayoutContext");function h4(e,n){let t=xa(e,n);if(!t)return e.nodes.some(o=>(Je(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 ${n?.wiring?"vorhanden":"fehlt"}, Layout ${n?.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 ${n?.wiring?"present":"missing"}, layout ${n?.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=Je(i)?.progressEvents;if(a)for(let l of a){let d=Qs(t.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 '${t.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 '${t.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=fp(t.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 '${t.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${t.layout.id}'`},severity:"error"});continue}Bl(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(h4,"checkProgressEventMappings");function g4(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.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),Bl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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(g4,"checkProgressBoardCoverage");function y4(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of Ye){let l=new Map;for(let d of o.columns){if(!Ci(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.${t.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(y4,"checkProgressBoardDistinctLabels");function w4(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)for(let o of i.states){let a=pp(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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(w4,"checkProgressTerminalSemantics");function k4(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Bl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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??[])Bl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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.${t.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(k4,"checkProgressSeatStates");var nm={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 b4(e){return e==="both"?{de:`${nm.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:`${nm.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:`${nm.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${nm.en}, or move the state into the successor's column.`}}s(b4,"passThroughRemedy");function v4(e,n){let t=xa(e,n);if(!t)return[];let{layout:r,wiring:i}=t;if(!r.buses.some(b=>b.key==="process"))return[];let o=tP(r);if(!o)return[];let a=new Map(e.nodes.map(b=>[b.id,b])),l=s(b=>Je(b).progressEvents??[],"eventsOf"),d=s(b=>Object.values(b.next??{}).map(E=>E.to),"routesOf"),c=s((b,E)=>{let T=a.get(b);if(!T||E.has(b))return null;if(l(T).length>0)return[T];if(BC[T.type]!==!1)return null;let R=d(T);if(R.length===0)return null;let D=[];for(let L of R){let _=c(L,new Set([...E,b]));if(!_)return null;D.push(..._)}return D},"firstProgressNodes"),u=s((b,E)=>{let T=[];for(let R of l(b)){let D=Qs(i,b,R);if(!D||D.bus!==E.bus||D.state===E.state)return null;T.push(D.state)}return[...new Set(T)].join("' / '")},"overwrites"),p=s((b,E)=>{let T=d(b);if(T.length===0)return null;let R=[];for(let D of T){let L=c(D,new Set([b.id]));if(!L)return null;for(let _ of L){let v=u(_,E);if(v===null)return null;R.push({de:`'${_.id}' (${_.type}) mit '${v}'`,en:`'${_.id}' (${_.type}) with '${v}'`})}}return[...new Map(R.map(D=>[D.de,D])).values()]},"submitOverwrittenBy"),h=new Map;for(let b of e.nodes)for(let E of l(b)){let T=Qs(i,b,E);if(!T||T.bus!=="process")continue;let R=b.type==="form"&&E===Rf?p(b,T):null,D=R?{de:`'${b.id}'.${E} erreicht ihn, und ${R.map(L=>L.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${b.id}'.${E} reaches it, and ${R.map(L=>L.en).join(", ")} overwrites it in the same transaction`}:null;h.set(T.state,[...h.get(T.state)??[],D])}let w=fp(r,"process"),k=new Map;for(let[b,E]of h){if(!E.every(R=>R!==null))continue;let T=[...new Map(E.map(R=>[R.de,R])).values()];k.set(b,{de:T.map(R=>R.de).join("; "),en:T.map(R=>R.en).join("; ")})}let y=[];for(let b of o.columns){if(b.states.length===0||!b.states.every(R=>k.has(R)))continue;let E=b.states.map(R=>{let D=w.holdsSeat?.includes(R)===!0,L=k.get(R);return{de:`Zustand '${R}'${D?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${L.de}`,en:`State '${R}'${D?" (is in holdsSeat, but never takes a seat)":""}: ${L.en}`}}),T=b4(o.audience);y.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${b.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${b.label.de}" ('${b.id}', Board '${o.id}') bleibt immer leer \u2014 ${E.map(R=>R.de).join("; ")}. ${T.de}`,en:`[progress/passThroughState] Column "${b.label.en}" ('${b.id}', board '${o.id}') always stays empty \u2014 ${E.map(R=>R.en).join("; ")}. ${T.en}`},severity:"warning"})}return y}s(v4,"checkProgressPassThroughColumns");function x4(e){let n=["workItems","workitems","work_items","taskTemplates"],t=[];for(let r of e.nodes){let i=r;for(let o of n){let a=i[o];a!=null&&t.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 t}s(x4,"checkMisnamedTasksKey");function S4(e){let n=[];for(let t of e.nodes){let r=t,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)&&n.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=Je(t),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(t):[]).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||!Jl.has(p)){n.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: ${[...Jl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Jl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&n.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:tC(e,r.id,h.node);if(h!==void 0&&w===null)n.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,b=w.node.id,E=y?o:w.composedKeys,T=y?d:w.intrinsicByKey,R=w.node.assign??{};p==="approval"&&n.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 D=h.templateKey,L=[...new Set([...E,...T.keys()])].filter(v=>!y||v!==u).join(", "),_={de:L||"keine",en:L||"none"};if(typeof D!="string"||y&&D===u||!E.has(D)&&!T.has(D))n.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(D)} auf Knoten "${b}"; zul\xE4ssige Ziele: ${_.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(D)} on node "${b}"; allowed targets: ${_.en}.`},severity:"error"});else if(w.refuse(D)!==null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:w.refuse(D),severity:"error"});else{let v=T.get(D);h.except!==void 0&&n.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"}),v!==void 0&&v.recipient!=="external"&&v.verdictResolved!==!0&&R[D]===void 0&&n.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 "${D}" (Knoten "${b}") zur\xFCck, aber der Knoten weist "${D}" keiner Gruppe zu \u2014 ohne 'assign.${D}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${D}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${D}" (node "${b}"), but the node assigns "${D}" to no group \u2014 without 'assign.${D}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${D}' or remove the 'blocks'.`},severity:"error"})}}{let y=c.completableIf;if(typeof y=="string"&&y.trim().length>0){let b=y.trim().replace(/^!/,"").trim();a.has(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${y}" verweist auf unbekannten Node-Export "${b}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${y}" refers to unknown node export "${b}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&n.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 b of y)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${b}`,reason:{de:`[workItems/approvalOnlyField] '${b}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${b}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&n.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)&&n.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 n.push(...rC(e)),n}s(S4,"checkWorkItemTemplates");var A4=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 E4(e){let n=[];for(let t of e.nodes){let r=t,i=Je(t),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(t)??[];if(o+a.length>0){let b=BC[r.type];b===void 0?n.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"}):b||n.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?.(t)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(b=>[b.id,b]));for(let b of l)A4.has(b.id)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${b.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 "${b.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??[SP]);for(let b of l)if(b.availableIn!==void 0)for(let E of b.availableIn)c.has(E)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${b.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${E}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${b.id}" on node type "${r.type}" is declared for state "${E}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=Cw(t),p=new Set(u?u.map(b=>b.id):[ta]);for(let b of l){if(b.external===void 0)continue;let E=xP(b.external.event),T={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},R=E?b.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${b.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${b.external.event}") \u2014 such actions are "internal"`}:b.outcome!==void 0?{de:`nennt das Outcome "${b.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${b.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${b.outcome}", but does not resolve the node (event "${b.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:b.label===void 0?T:null:b.kind!=="advance"?{de:`ist als "${b.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${b.kind}" (external actions resolve the node and must be "advance")`}:b.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(b.outcome)?b.label===void 0?T:null:{de:`verweist auf das unbekannte Outcome "${b.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${b.outcome}" (declared: ${[...p].join(", ")||"none"})`};R!==null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${b.id}" auf Knotentyp "${r.type}" ${R.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${b.id}" on node type "${r.type}" ${R.en}.`},severity:"error"})}for(let b of a){let E=b.unlocks;if(E.length===0&&b.verdictResolved!==!0&&b.informational!==!0){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${b.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${b.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${b.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let T of E)d.get(T)===void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${b.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${b.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${T}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${b.key}" on node "${r.id}" unlocks the unknown action "${T}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(b=>b.key));for(let b of Object.keys(r.assign??{}))h.has(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${b}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${b}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${b}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});for(let[b,E]of Object.entries(r.assign??{})){if(E===void 0)continue;let T=`nodes.${r.id}.assign.${b}`,R={de:`Team der Vorlage "${b}" (Knoten "${r.id}")`,en:`team of the template "${b}" (node "${r.id}")`};n.push(...q_(E,T,R));for(let[D,L]of(Array.isArray(E)?E:[]).entries()){let _=L?.when;_==null||!we(_)||un(_)||n.push({layer:"GRAPH",kind:"nodeRule",path:`${T}.${D}.when`,severity:"error",reason:{de:`[assign/conditionNotFormField] ${R.de}, Zeile ${D+1}: die Bedingung nennt ${je(e,_,"de")} \u2014 ein Team wird nach einem Ja/Nein-Feld eines Formulars gew\xE4hlt ($node.<formular>.admission.<feld>).`,en:`[assign/conditionNotFormField] ${R.en}, row ${D+1}: the condition names ${je(e,_,"en")} \u2014 a team is chosen by a yes/no field of a form ($node.<form>.admission.<field>).`}})}}let w=l.filter(b=>b.teamAssignable===!0).map(b=>b.id);for(let b of Object.keys(r.actionTeams??{}))w.includes(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${b}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${b}", 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 "${b}", but this action cannot be given to a team here; possible: ${w.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let b of a)if(b.recipient==="external"||(r.assign??{})[b.key]!==void 0)for(let T of b.unlocks)k.add(T);let y=i.strictActionCoverage===!0;for(let b of l){if(k.has(b.id)||b.superUserOnly===!0)continue;let E=a.find(R=>R.unlocks.includes(b.id)),T=E!==void 0?{de:` Fehlt die Zuweisung assign.${E.key}?`,en:` Is the assignment assign.${E.key} missing?`}:{de:"",en:""};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}`,reason:{de:`[capability/superUserOnly] Action "${b.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${T.de}`,en:`[capability/superUserOnly] Action "${b.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${T.en}`},severity:y?"error":"warning"})}}return n}s(E4,"checkNodeCapabilityWiring");function T4(e){let n=new Set(qO()),t=[];for(let r of e.nodes)n.has(r.type)||t.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: ${[...n].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...n].join(", ")}.`},severity:"error"});return t}s(T4,"checkKnownNodeTypes");function $4(e,n){let t=[],r=s((a,l)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=YI(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(t.push(...j4(l,d)),d.length===0)continue;let c=Je(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 b=y.key,E=typeof b=="string"&&b.trim().length>0?b:void 0,T=E??"?",R=`nodes.${l.id}.optionalActions.${T}`,D=typeof y.action=="string"?y.action:void 0;if(y.when!==void 0){let L=s(_=>r(`${R}.when`,{de:`[optionalAction/when] Optionale Aktion "${T}" auf Knoten "${l.id}": ${_.de}`,en:`[optionalAction/when] Optional action "${T}" on node "${l.id}": ${_.en}`}),"conditionFinding");if(typeof y.when!="string"||y.when.trim()==="")L({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 _ of Fp(y.when,i,n))L(_)}if((D===void 0||!u.has(D))&&r(`${R}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${T}" 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 "${T}" 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(", ")}.`)}),E===void 0?r(`${R}.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(E)&&r(`${R}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${E}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${E}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),w.add(E)),o(y.label)||r(`${R}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${T}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${T}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),D==="spawnTasks"){y.except!==void 0&&r(`${R}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${T}" 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 "${T}" 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'.`}),t.push(...jC({nodeId:l.id,bindingKey:T,binding:y,templates:p}));let L=Array.isArray(y.tasks)?y.tasks:void 0;if(L===void 0||L.length===0)r(`${R}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${T}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${T}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let _=new Set,v=new Set(L.filter(P=>typeof P=="string"));for(let P of L){let A=typeof P=="string"?P:void 0;if(A===void 0||A.length===0){r(`${R}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${T}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(_.has(A)){r(`${R}.tasks.${A}`,{de:`[optionalAction/duplicateTaskRef] Template "${A}" ist in der Aktion "${T}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${A}" is referenced twice in the action "${T}" on node "${l.id}".`});continue}_.add(A);let M=h.get(A);if(M===void 0){r(`${R}.tasks.${A}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${l.id}" referenziert das Template "${A}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${T}" on node "${l.id}" references the template "${A}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let U=k.get(A);U!==void 0&&U!==T?r(`${R}.tasks.${A}`,{de:`[optionalAction/taskDoublyBound] Template "${A}" auf Knoten "${l.id}" ist bereits von der Aktion "${U}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${A}" on node "${l.id}" is already referenced by the action "${U}" \u2014 a template belongs to at most one optional action.`}):k.set(A,T);let oe=M.blocks?.templateKey;typeof oe=="string"&&!v.has(oe)&&r(`${R}.tasks.${A}`,{de:`[optionalAction/taskRefBlocks] Template "${A}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${oe}", das nicht zur selben Aktion "${T}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${A}" on node "${l.id}" carries 'blocks' on "${oe}", which does not belong to the same action "${T}" \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===A&&(re!==void 0&&v.has(re)||r(`${R}.tasks.${A}`,{de:`[optionalAction/taskRefBlocks] Template "${A}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${T}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${A}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${T}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return t}s($4,"checkOptionalActions");function R4(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(R4,"literalValueType");function I4(e,n){let t=[],r=n?.notificationTemplates;for(let i of e.nodes){let o=i,a=GP(i,Je(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)||t.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)){t.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"){t.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){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": die Benachrichtigung "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the notification "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&t.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=KP(c),k=new Set(h.params.map(y=>y.key));for(let y of Object.keys(u.args??{}))k.has(y)||t.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(b=>b.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The letter "${h.id}" has no argument "${y}" \u2014 expected: ${h.params.map(b=>b.key).join(", ")||"(none)"}.`},severity:"error"});for(let y of h.params){let b=u.args?.[y.key],E=`${p}.args.${y.key}`;if(b!==void 0&&"literal"in b){let R=R4(b.literal);y.type!==void 0&&!Gw(R,y.type)&&t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/argTypeMismatch] "${y.key}" erwartet ${Hl(y.type).de}, festgelegt ist aber ${JSON.stringify(b.literal)} (${R}).`,en:`[notification/argTypeMismatch] "${y.key}" expects ${Hl(y.type).en}, but ${JSON.stringify(b.literal)} (${R}) is set.`},severity:"error"});continue}if(b!==void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unsupportedArg] "${y.key}" ist an ${JSON.stringify(b)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${VC(w,"de")} kommen.`,en:`[notification/unsupportedArg] "${y.key}" is bound to ${JSON.stringify(b)} \u2014 a letter argument can only be a fixed value ({ literal }) or come automatically from ${VC(w,"en")}.`},severity:"error"});continue}let T=jP(y,w.get(y.key)??[]);if(!(T.status==="resolved"||T.status==="unused")){if(T.status==="sometimes"){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}" immer, ${T.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 ${T.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(T.status==="ambiguous"){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/ambiguousArg] "${y.key}" hat mehrere passende Quellen \u2014 ${T.matches.map(R=>R.source).join(", ")}. In notifications.${c.id}.args.${y.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${y.key}" has several matching sources \u2014 ${T.matches.map(R=>R.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${y.key}.`},severity:"error"});continue}t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unresolvedArg] Der Brief "${h.id}" braucht "${y.key}"${y.type!==void 0?` (${Hl(y.type).de})`:""}, und der Knoten hat daf\xFCr ${T.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${T.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The letter "${h.id}" needs "${y.key}"${y.type!==void 0?` (${Hl(y.type).en})`:""}, and the node has ${T.rejected.length===0?"no source for it":`only unsuitable sources for it: ${T.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`},severity:"error"})}}}}return t}s(I4,"checkNotificationBindings");function O4(e){return xN(e).map(n=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:n,severity:"error"}))}s(O4,"checkAssignmentRules");function VC(e,n){let t=[...e.keys()].sort();return t.length===0?n==="de"?"(nichts)":"(nothing)":t.join(", ")}s(VC,"describeCandidates");function _4(e,n){return EN(e,n?.teamKeys).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(_4,"checkChannels");function P4(e){return JI(e).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(P4,"checkStaffInputs");function N4(e,n){let t=[];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=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!DN(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(!we(c))continue;let u=de(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),!un(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=Ur(n,c);p!=null&&Js("nodeReads",Hs(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 t}s(N4,"checkReadinessReads");function C4(e,n){let t=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=QO(r),o=Jf(r);if(i===null||o===null)continue;let a=n?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${Pn.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 t}s(C4,"checkSetFlagKeys");function D4(e,n){let t=n?.readinessFormFieldsByFormNode,r=n?.readinessPartyConditionKeysByFormNode;if(t===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(!we(a)||!Sr(a))continue;let l=t.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=ik(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(y=>un(y)&&y.owner===a.owner),h=ik(l,[...p.map(y=>y.path),...MN(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(D4,"checkReadinessPartyConditions");function bk(e){let n=Object.keys(e.inputs??{});if(n.length===0)return[];let t=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(t?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(ea(e).map(l=>l.id));return n.filter(l=>!a.has(l))}s(bk,"undeclaredInputKeys");function F4(e,n){return e.nodes.flatMap(t=>[...M4(e,t,ea(t),n),...L4(e,t,n)])}s(F4,"checkUnknownResources");function L4(e,n,t){let r=[],i=new Set((Je(n).workItemTemplates?.(n)??[]).map(a=>a.key)),o=new Set((n.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of dp(n)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=zs[a.leaf],d=`nodes.${n.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,n.id,"en")}" (${n.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=t?.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(L4,"referenceIssues");function M4(e,n,t,r){let i=[];for(let o of t){if(!Qf(o.type))continue;let a=Bs[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=n.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=Bs[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.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,n.id,"en")}" (${n.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(M4,"unknownResourceIssues");function q4(e){let n=[];for(let t of e.nodes)for(let r of bk(t))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.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,t.id,"en")}" (${t.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 n}s(q4,"checkUndeclaredInputs");function K4(e){let n=[];for(let t of e.nodes){let r=new Set;for(let i of ea(t)){if(!r.has(i.id)){r.add(i.id);continue}n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.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,t.id,"en")}" (${t.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 n}s(K4,"checkDuplicateSlots");function UC(e,n,t){let r=[],i=T4(e);if(i.length>0)return i;r.push(...c4(e)),r.push(...l4(e)),r.push(...u4(e)),r.push(...d4(e)),r.push(...o4(e)),r.push(...s4(e)),r.push(...a4(e)),r.push(...m4(e)),r.push(...f4(e)),r.push(...aP(e,n)),r.push(...h4(e,n)),r.push(...g4(e,n)),r.push(...y4(e,n)),r.push(...VN(e,n?.layout)),r.push(...w4(e,n)),r.push(...k4(e,n)),r.push(...v4(e,n)),r.push(...Z_(e,t)),r.push(...uP(e)),r.push(...gP(e)),r.push(...dP(e)),r.push(...cP(e)),r.push(...q4(e)),r.push(...F4(e,t)),r.push(...K4(e)),r.push(...x4(e)),r.push(...S4(e)),r.push(...oC(e,t)),r.push(...cC(e)),r.push(...lC(e)),r.push(...uC(e,t)),r.push(...wC(e,t)),r.push(...E4(e)),r.push(...I4(e,t)),r.push(...$4(e,t)),r.push(...O4(e)),r.push(...N4(e,t)),r.push(...D4(e,t)),r.push(...C4(e,t)),r.push(..._4(e,t)),r.push(...P4(e)),r.push(...KC(e));for(let o of e.nodes){let a=Je(o);a.validate&&r.push(...a.validate(o,e,t))}return r}s(UC,"checkGraph");function j4(e,n){let t=e.requiresOneOf;if(t===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(t)||t.length===0||t.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=n.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of t){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(j4,"checkRequiresOneOf");function V4(e){return e.nodes.flatMap(n=>bk(n).map(t=>({nodeId:n.id,key:t,binding:n.inputs?.[t]?.kind==="binding"})))}s(V4,"undeclaredInputCells");function GC(e,n){let t=V4(e).filter(o=>n.bindings||!o.binding);if(t.length===0)return{graph:e,dropped:t};let r=new Map;for(let o of t)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:t}}s(GC,"dropUndeclaredInputs");function vk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(vk,"isObject");function zC(e){return vk(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(zC,"oldShape");function WC(e){return(e?.nodes??[]).some(zC)}s(WC,"needsTemplateStampMove");function B4(e){let n=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(n)?n:null;let t=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(t)?t:null}s(B4,"stampedFields");function U4(e){let n=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:n,reason:"templateAndStamp"}};let t={...e},r=[];if("template"in e){let{template:i}=e;if(delete t.template,vk(i))t.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:n,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete t.cockpitFields;let o=vk(e.inputs)?{...e.inputs}:{},a=B4(t);if(a===null&&i.length>0)return{unmoved:{nodeId:n,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:n,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:n,key:l,reason:"processSource"}):d?r.push({nodeId:n,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}t.inputs=o}return{node:t,reports:r}}s(U4,"moveNode");function YC(e){let n=[],t=[],r=[],i=e.nodes.map(o=>{if(!zC(o))return o;let a=U4(o);return"unmoved"in a?(r.push(a.unmoved),o):(n.push(String(o.id)),t.push(...a.reports),a.node)});return n.length===0?{graph:e,moved:n,reports:t,unmoved:r}:{graph:{...e,nodes:i},moved:n,reports:t,unmoved:r}}s(YC,"moveTemplateStampAndCockpit");var HC=If,G4="applicant.applicationSubmitted";function tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(tm,"isObject");function JC(e){return tm(e)&&e.type==="form"&&typeof e.id=="string"&&!At(e)}s(JC,"isCreatingFormNode");function z4(e){return tm(e.notifications)&&HC in e.notifications}s(z4,"hasSubmittedBinding");function xk(e){let n={toBind:[],alreadyBound:[],malformed:[]};for(let t of e?.nodes??[])JC(t)&&(t.notifications!==void 0&&!tm(t.notifications)?n.malformed.push(t.id):z4(t)?n.alreadyBound.push(t.id):n.toBind.push(t.id));return n}s(xk,"submitReceiptInventory");function QC(e){let{toBind:n}=xk(e);if(n.length===0)return{graph:e,bound:[]};let t=new Set(n),r=e.nodes.map(i=>{if(!JC(i)||!t.has(i.id))return i;let o=tm(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[HC]:{templateId:G4}}}});return{graph:{...e,nodes:r},bound:n}}s(QC,"bindSubmitReceipt");var zo=["park","advance"],ir="whenNothingOwed",ZC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function XC(e){let n=e.inputs?.[ir],t=n?.kind==="literal"?n.value:void 0;return Sk(t)?t:null}s(XC,"reviewModeOrNull");function Sk(e){return zo.includes(e)}s(Sk,"isReviewMode");function Ak(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ak,"isObject");function eD(e){return Ak(e)&&e.type==="review"&&!(Ak(e.inputs)&&ir in e.inputs)}s(eD,"lacksMode");function nD(e){return(e?.nodes??[]).some(eD)}s(nD,"needsReviewMode");function tD(e){let n=[],t=e.nodes.map(r=>{if(!eD(r))return r;n.push(r.id);let i=Ak(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[ir]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:t},set:n}}s(tD,"setReviewModePark");function rm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(rm,"isObject");function rD(e){let{notifications:n,bound:t}=Ep(e.notifications,{tasks:[]},e);return{next:n,bound:t}}s(rD,"bindingsFor");function iD(e){let n={toBind:[],malformed:[]};for(let t of e?.nodes??[])if(!(!rm(t)||typeof t.id!="string"||ia(t).length===0)){if(t.notifications!==void 0&&!rm(t.notifications)){n.malformed.push(t.id);continue}for(let r of rD(t).bound)n.toBind.push(`${t.id}.${r}`)}return n}s(iD,"appointmentLetterInventory");function oD(e){let n=[],t=!1,r=e.nodes.map(i=>{if(!rm(i)||typeof i.id!="string"||ia(i).length===0||i.notifications!==void 0&&!rm(i.notifications))return i;let{next:o,bound:a}=rD(i);return a.length===0?i:(t=!0,n.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return t?{graph:{...e,nodes:r},bound:n}:{graph:e,bound:[]}}s(oD,"bindAppointmentLetters");function Sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Sa,"isObject");var sD=["id","label","dataFlow"],aD=["audience","populates","stages","expectedOutcomes"];function lD(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(n=>Sa(n)&&typeof n.slot=="string")}s(lD,"carriesStringSlots");function dD(e){return(e.nodes??[]).some(n=>Sa(n)&&n.type==="form"&&aD.some(t=>t in n))}s(dD,"carriesRetiredFormNodeKey");var W4=[{key:"generatorPin",editor:!0,holds:vO,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:t_,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:l_,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:g_,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:uO,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:hO,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:WC,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:"paymentSettlement",editor:!0,holds:S_,what:{de:"Zahlungsknoten mit \u201EAbrechnung\u201C (`inputs.settlement`) statt \u201EZahlungsweg\u201C (`inputs.mode`)",en:'payment node with "Settlement" (`inputs.settlement`) instead of "Payment mode" (`inputs.mode`)'}},{key:"documentRef",editor:!0,holds:D_,what:{de:"Dokument eines anderen Knotens als `document:$node.<Knoten>.document` statt als Slot `artifact:<Slot>`",en:"another node's document as `document:$node.<node>.document` instead of the slot `artifact:<slot>`"}},{key:"formView",editor:!0,holds:$_,what:{de:"Ansicht einer Aufgabe als `formView` statt als Ansichts-Adresse `view`",en:"a task's view as `formView` instead of the view address `view`"}},{key:"nodeAssignString",editor:!0,holds:N_,what:{de:"Team einer Knoten-Aufgabe als Text (`assign.<Vorlage>`) statt als Regelliste",en:"a node task's team as text (`assign.<template>`) instead of a rule list"}},{key:"reviewWithoutMode",editor:!0,holds:nD,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=>ap(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=>sD.some(n=>n in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:lD,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:dD,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function cD(e){if(!Sa(e)||!Array.isArray(e.nodes))return[];let n=e;return W4.filter(t=>t.holds(n)).map(({key:t,what:r,editor:i})=>({key:t,what:r,editor:i}))}s(cD,"legacyGraphShapes");function uD(e,n){let t=n.answers??{},r=[],i=[],o=e,a=sD.filter(A=>A in o);if(a.length>0){let A={...o};for(let M of a)delete A[M],r.push({message:`graph.${M}: deleted (read by nothing)`});o=A}if(dD(o)&&(o={...o,nodes:o.nodes.map(A=>{if(!Sa(A)||A.type!=="form")return A;let M=aD.filter(oe=>oe in A);if(M.length===0)return A;let U={...A};for(let oe of M)delete U[oe];return r.push({nodeId:String(A.id),message:`form node: deleted ${M.map(oe=>`\`${oe}\``).join(", ")} (read by nothing)`}),U})}),lD(o)){let A=o.assignmentRules.map((M,U)=>{if(!Sa(M)||typeof M.slot!="string")return M;let oe=jf(M.slot);return oe===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${U}].slot "${M.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),M):(r.push({message:`assignmentRules[${U}].slot "${M.slot}" \u2192 ${JSON.stringify(oe)}`}),{...M,slot:oe})});o={...o,assignmentRules:A}}let l=xO(o);o=l.graph;for(let A of l.moved)r.push({nodeId:A,message:"generator / template pin moved into its input"});for(let A of l.unmoved)i.push({code:`generatorPin/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${A.reason}) \u2014 edit the node by hand`});let d=r_(o);o=d.graph;for(let A of d.moved)r.push({nodeId:A,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let A of d.unmoved)i.push({code:`setFlag/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${A.reason}) \u2014 edit the node by hand`});let c=d_(o);o=c.graph;for(let A of c.moved)r.push({nodeId:A,message:"scalar settings moved into inputs"});for(let A of c.unmoved)i.push({code:`scalar/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`\`${A.key}\` cannot be moved into an input (${A.reason}) \u2014 edit the node by hand`});let u=y_(o);o=u.graph;for(let A of u.moved)r.push({nodeId:A,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let A of u.unmoved)i.push({code:`nodeConfig/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`\`${A.key}\` cannot be moved into an input (${A.reason}) \u2014 edit the node by hand`});let p=YC(o);o=p.graph;for(let A of p.moved){let M=o.nodes.find(Q=>Sa(Q)&&Q.id===A),U=M?.inputs?.documentTemplate,oe=U?.kind==="literal"&&typeof U.value=="string"?U.value:null;r.push({nodeId:A,message:M!==void 0&&"templateStamp"in M&&oe!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${oe}\` 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 A of p.reports)r.push({nodeId:A.nodeId,message:`cockpit field \`${A.key??""}\` deleted (${A.reason}: ${A.reason==="unknownKey"?"the stamp declares no such parameter":A.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let A of p.unmoved)i.push({code:`templateStamp/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.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":A.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=gO(o);o=h.graph;for(let A of h.moved)r.push({nodeId:A,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let A of h.unmoved)i.push({code:`eventTrigger/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${A.reason}) \u2014 edit the node by hand`});let w=fO(o,t.semantics);o=w.graph;for(let A of w.written){if(A.source==="formerDefault"){r.push({nodeId:A.nodeId,message:`outcome \`${A.outcomeId}\`: semantic "${A.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${A.nodeId}.${A.outcomeId}`,value:A.semantic}});continue}r.push({nodeId:A.nodeId,message:`outcome \`${A.outcomeId}\`: semantic "${A.semantic}" (${A.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let A of w.refused)i.push({code:A.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:A.nodeId,answer:"semantic",answerKey:`${A.nodeId}.${A.outcomeId}`,candidates:A.allowed,message:A.answer===void 0?`${A.nodeType} outcome \`${A.outcomeId}\` ran as "${zy(A.outcomeId)??""}", which a ${A.nodeType} outcome may no longer carry \u2014 say which one it is`:`${A.nodeType} outcome \`${A.outcomeId}\`: "${A.answer}" is not a meaning a ${A.nodeType} outcome may carry`});for(let A of w.invalid)i.push({code:"outcome/semanticInvalid",nodeId:A.nodeId,answer:"edit",candidates:St,message:`outcome \`${A.outcomeId}\` carries the semantic "${A.value}", which is no meaning \u2014 edit it`});let k=kO(o,n.selection,t.waitlistPolicy);o=k.graph;for(let A of k.moved){let M=A.policy.waitlistOrder;r.push({nodeId:A.nodeId,message:`waitlist policy into inputs: ${Y4(A.policy)} (${A.source==="answer"?"answered":A.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...A.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:A.nodeId,value:M}}:{}})}for(let A of k.refused)i.push({code:`waitlist/${A.reason}`,nodeId:A.nodeId,answer:"waitlistPolicy",answerKey:A.nodeId,candidates:Xt,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});let y=A_(o);o=y.graph;for(let A of y.moved)r.push({nodeId:A,message:"payment: `inputs.settlement` \u2192 `inputs.mode` (separate \u2192 manual)"});for(let A of y.refused)i.push({code:`collectPayment/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.reason==="bothCells"?"the payment node carries both `inputs.settlement` and `inputs.mode` \u2014 delete `settlement` by hand":"`inputs.settlement` is no literal online | separate \u2014 set `inputs.mode` by hand"});let b=R_(o);o=b.graph;for(let A of b.moved)r.push({nodeId:A.split(".")[0],message:`\`formView\` \u2192 \`view\` (${A})`});for(let A of b.refused){let M=A.taskKey===void 0?"the node":`task "${A.taskKey}"`;i.push({code:`view/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.reason==="bothFields"?`${M} carries both \`formView\` and \`view\` \u2014 delete \`formView\` by hand`:`${M}'s \`formView\` is no { form, key } \u2014 set \`view\` by hand`})}let E=C_(o);o=E.graph;for(let A of E.moved)r.push({nodeId:A.nodeId,message:`\`assign.${A.templateKey}\`: team \u2192 rule list`});for(let A of E.refused)i.push({code:"assign/shape",nodeId:A.nodeId,answer:"edit",message:`\`assign.${A.templateKey}\` is neither a team key nor a rule list \u2014 set it by hand`});let T=F_(o);o=T.graph;for(let A of T.moved)r.push({nodeId:A.split(".")[0],message:`documents: \`document:$node.<node>.document\` \u2192 \`artifact:<slot>\` (${A})`});for(let A of T.refused)i.push({code:`workItems/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`task "${A.taskKey}" links a document whose node declares no single slot \u2014 name the slot as \`artifact:<slot>\` by hand`});if(k_(o)){let A=b_(o,t.payee);o=A.graph;for(let M of A.set)r.push({nodeId:M.nodeId,message:`online payment: payee "${M.payee}" (answered)`});for(let M of A.refused)i.push({code:"collectPayment/payeeMissing",nodeId:M,answer:"payee",answerKey:M,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 A of xk(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:A,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let R=QC(o);o=R.graph;for(let A of R.bound)r.push({nodeId:A,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let D=tD(o);o=D.graph;for(let A of D.set)r.push({nodeId:A,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let A of iD(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:A,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let L=oD(o);o=L.graph;for(let A of L.bound){let M=A.indexOf(".");r.push({nodeId:A.slice(0,M),message:`appointment letter bound to \`notifications.${A.slice(M+1)}\` (the standard letter, sent by code before)`})}let _=ap(o).filter(A=>!A.hasTeam);for(let A of _)i.push({code:"task/userWithoutTeam",nodeId:A.nodeId,answer:"edit",message:`task \`${A.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let v=L_(o);o=v.graph;for(let A of v.dropped.filter(M=>M.hasTeam))r.push({nodeId:A.nodeId,message:`task \`${A.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let P=GC(o,{bindings:!0});o=P.graph;for(let A of P.dropped){if(!A.binding){r.push({nodeId:A.nodeId,message:`input \`${A.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:A.nodeId,message:`input \`${A.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:`${A.nodeId}.${A.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(uD,"upgradeGraph");function Y4(e){return`waitlistOrder=${e.waitlistOrder}`}s(Y4,"formatPolicy");function yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(yi,"isObject");var fD="admission.generic",pD=Object.keys(Mf).filter(e=>e!=="label");function mD(e){return yi(e.smartforms)?Object.entries(e.smartforms):[]}s(mD,"smartformEntries");function H4(e){let n=[];mD(e.index).some(([,i])=>yi(i)&&"outcomeFnRef"in i)&&n.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let t=Object.keys(e.manifest).filter(i=>Object.hasOwn(_l,i));if(t.length>0){let i=t.map(o=>`\`${o}\``).join(", ");n.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>pD.some(o=>o in i))&&n.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(yi(r.progressWiring)&&"layoutId"in r.progressWiring&&n.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),n.push(...cD(r.graph).map(i=>i.what))),n}s(H4,"legacyBundleShapes");function om(e,n){let t=H4(e);t.length!==0&&ae("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${n} stammt aus einem \xE4lteren Bundle-Format (${t.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: ${n} is in an older bundle format (${t.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(om,"assertBundleCurrent");function im(e){let n=s(t=>Array.isArray(t)?t.map(n):yi(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(im,"canonical");function hD(e,n={}){let t=[],r=[],i=e.index,o=mD(i);if(o.some(([,u])=>yi(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!yi(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!==fD){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(y=>`\`${y}\``).join(", ")} \u2014 only \`outcomeFnRef: ${fD}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}t.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,t.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?t.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},t.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):im(l.progressLayout)===im(p)?t.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(_l,u)?_l[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}t.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(yi(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},t.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(yi(u)&&Array.isArray(u.nodes)){let p=uD(u,{selection:d,answers:n});l={...l,graph:p.graph},t.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 pD)if(y in h){if(y==="outcomeIds"){let b=Array.isArray(h.outcomes)?h.outcomes.map(E=>yi(E)?E.id:void 0):[];if(im([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==im(b.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],t.push({file:k,message:`\`${y}\` deleted (${Mf[y].en})`})}u[p]=w}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:t,refusals:r}}s(hD,"upgradeOfferBundle");var J4={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},fve={createManifest:tt.workflow.createManifestInternal,publishManifest:tt.workflow.publishManifestInternal,publishOfferInternal:tt.workflow.publishOfferInternalInternal,publishOfferExternal:tt.workflow.publishOfferExternalInternal,getOfferPublishState:tt.workflow.getOfferPublishStateInternal,upsertCustomField:tt.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:tt.admission.upsertDerivedAttributeRuleInternal,createSmartForm:tt.forms.createSmartFormInternal,getSmartFormBySlug:tt.forms.getSmartFormBySlugInternal,saveSmartFormDraft:tt.forms.saveSmartFormDraftInternal,publishSmartForm:tt.forms.publishSmartFormInternal,createWorkflow:tt.workflow.createWorkflowInternal,getWorkflowGraph:tt.workflow.getWorkflowGraphInternal,saveWorkflowDraft:tt.workflow.saveWorkflowDraftInternal,publishWorkflow:tt.workflow.publishWorkflowInternal};function Ek(e,n){for(let[t,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&ae("INVALID",{de:`offer: ${n}: smartforms.${t} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${n}: smartforms.${t} 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: ${n}: smartforms.${t} 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: ${n}: smartforms.${t} 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(Ek,"assertSmartformEntries");function gD(e){let n=s(t=>Array.isArray(t)?t.map(n):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(gD,"canonicalJson");function yD(e,n){return n==null?!0:gD(e)!==gD(n)}s(yD,"changed");async function wD(e,n,t,r={},i=J4){let{index:o}=n;om({index:o,manifest:n.manifest,...n.smartforms!==void 0?{smartforms:n.smartforms}:{},...n.workflow!==void 0?{workflow:n.workflow}:{}},`bundle of ${o.slugs.manifest}`),Ek(o,`bundle of ${o.slugs.manifest}`);let a=Lf(n.manifest);a.length>0&&ae("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
11276
+ {{einstellungenLink}}`}}]},Vw=[v2,$2,O2,_2,P2,L2,F2,uY,pY,AY,TY,RY,_Y,CY,FY,qY,VY,GY,WY,mY,hY,gY,YY,HY,JY,M2,q2,V2,B2,z2,Z2,nY,Y2,iY,dY,vY,gH,wH,S2,E2,ZY,eH,tH,iH,aH,dH,uH];function Bw(e){let n=Vw.find(t=>t.id===e);return n===void 0&&F(`notifications: unknown letter "${e}"`),n}s(Bw,"letterDefFor");function Uw(e){return Vw.some(n=>n.id===e)}s(Uw,"hasLetterDef");function Gw(e,n){return n===void 0?!0:Zf(e,n)}s(Gw,"letterArgCompatible");function Hl(e){return e==="localizedText"?{de:"Text in jeder Sprache (localizedText)",en:"Text in every language (localizedText)"}:{de:`${rt(e)} (${e})`,en:`${rt(e)} (${e})`}}s(Hl,"letterArgTypeLabel");function KP(e){let n=new Map,t=s((r,i)=>{let o=n.get(r);o===void 0?n.set(r,[i]):o.push(i)},"add");for(let r of e.args)t(r.key,{source:`Ereignis "${e.id}"`,type:r.type,always:r.required===!0});for(let r of AP)t(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return n}s(KP,"eventArgSources");function jP(e,n){let t=e.type===void 0?[...n]:n.filter(r=>Gw(r.type,e.type));if(t.length>1)return{status:"ambiguous",matches:t};if(t.length===1){let r=t[0];return!e.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return e.required?{status:"missing",rejected:[...n]}:{status:"unused"}}s(jP,"resolveLetterParam");var zw=["booked","rescheduled","cancelled"],kH={booked:"admission.appointmentBooked",rescheduled:"admission.appointmentRescheduled",cancelled:"admission.appointmentCancelled"},BP=":";function UP(e,n){return`${e}${BP}${n}`}s(UP,"appointmentEventId");function bH(e){let n=e.lastIndexOf(BP);if(n<=0)return null;let t=e.slice(n+1);return zw.includes(t)?{taskKey:e.slice(0,n),kind:t}:null}s(bH,"parseAppointmentEventId");var VP={booked:{de:"Termin vereinbart",en:"Appointment booked"},rescheduled:{de:"Termin verschoben",en:"Appointment moved"},cancelled:{de:"Termin abgesagt",en:"Appointment cancelled"}};function ia(e){return Array.isArray(e.tasks)?e.tasks.filter(n=>typeof n?.key=="string"&&n.result?.kind==="appointment"):[]}s(ia,"appointmentTasksOf");function vH(e){return zw.map(n=>({id:UP(e.key,n),label:{de:`${VP[n].de} \u2013 \u201E${e.title.de}\u201C`,en:`${VP[n].en} \u2013 \u201C${e.title.en}\u201D`},audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"bookingId",type:"string",required:!0}]}))}s(vH,"appointmentTaskEvents");function GP(e,n){let t=n.notificationEvents?.(e)??[],r=ia(e).flatMap(vH);return r.length===0?t:[...t,...r]}s(GP,"nodeNotificationEvents");function xH(e){return Object.fromEntries(zw.map(n=>[UP(e,n),{templateId:kH[n]}]))}s(xH,"defaultAppointmentBindings");function SH(e,n){if(e===void 0)return{notifications:e,dropped:[]};let t=[],r={};for(let[i,o]of Object.entries(e))bH(i)?.taskKey===n?t.push(i):r[i]=o;return t.length===0?{notifications:e,dropped:t}:{notifications:Object.keys(r).length===0?void 0:r,dropped:t}}s(SH,"withoutAppointmentBindings");function Ep(e,n,t){let r=new Set(ia(n).map(d=>d.key)),i=new Set(ia(t).map(d=>d.key)),o=e,a=[];for(let d of r){if(i.has(d))continue;let c=SH(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(xH(d)))o?.[c]===void 0&&(o={...o??{},[c]:u},l.push(c));return{notifications:o,bound:l,dropped:a}}s(Ep,"syncAppointmentBindings");function AH(e){return e.kind==="task"&&!("title"in e)}s(AH,"isLegacyFreeTodoContext");function Ww(e){let{context:n}=e;if(AH(n)&&F(`[workItems/legacyFreeTodo] work_item ${e._id} is a free to-do in its former shape \u2014 run migrations:freeTodosToContext`),n.kind==="task")return{...e,context:n,kind:"task",createdVia:"human",partyId:n.partyId};let{anchor:t,task:r,kind:i,title:o,description:a,...l}=n,d=t.scope==="node"?{nodeId:t.nodeId,templateKey:t.templateKey,gatesNode:t.gatesNode,blocks:t.blocks}:t.scope==="application"?{scope:"application",templateKey:t.templateKey}:t.scope==="crossNode"?{scope:"application",nodeId:t.nodeId,templateKey:t.templateKey,blocks:t.blocks}:{};return{...e,context:n,...l,...d,...r??{},kind:i}}s(Ww,"readWorkItem");async function oa(e,n){let t;if(n.nodeId!==void 0){let r=n.nodeId;t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",i=>i.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",r)).collect()}else if(n.isOpen!==void 0){let r=n.isOpen;t=await e.db.query("work_items").withIndex("by_applicationId_and_isOpen",i=>i.eq("context.applicationId",n.applicationId).eq("isOpen",r)).collect()}else t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",r=>r.eq("context.applicationId",n.applicationId)).collect();return t.filter(r=>n.isOpen===void 0||r.isOpen===n.isOpen).map(Ww)}s(oa,"listWorkItemsForApplication");var yge=m.union(m.literal("approved"),m.literal("rejected")),Jl=new Set(["task","approval"]);function TH(e,n){switch(e){case"task":return n?.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:n?.gatesNode??!0};default:F(`expandComposedTask: unknown composed-task kind ${JSON.stringify(e)} \u2014 authorable: ${[...Jl].join(", ")}`)}}s(TH,"expandComposedTask");for(let e of["task","approval"]){let n=TH(e);n.kind==="approval"!=(n.isApproval===!0)&&F(`composed-task kind "${e}": isApproval must be present iff kind === 'approval'`)}var zP=Fi,Gi=`${zP}.`,$H=new Set(["text","number","date","boolean","option","edge"]);function Tp(e,n){let t=e[n];return t===void 0&&F(`[env/unknownKey] no environment key '${n}'`),typeof t=="string"?null:Object.keys(t)}s(Tp,"contextFields");function WP(e,n){return Object.hasOwn(e,n)}s(WP,"isContextKey");function YP(e){let n=[];for(let t of Object.keys(e)){let r=Tp(e,t);if(r===null)n.push(t);else for(let i of r)n.push(`${t}.${i}`)}return n}s(YP,"leafPaths");function Ql(e,n){let[t="",r,...i]=n.split(".");if(!WP(e,t)||i.length>0)return;let o=e[t];if(typeof o=="string")return r===void 0?o:void 0;if(!(r===void 0||!Object.hasOwn(o,r)))return o[r]}s(Ql,"leafType");function HP(e){let n=new Set;for(let t of e){let r=sa(t);r!==null&&n.add(r.split(".")[0])}return[...n]}s(HP,"contextKeysOf");function sa(e){return e.startsWith(Gi)?e.slice(Gi.length):null}s(sa,"contextPathOf");function Zl(e){return e===zP||e.startsWith(Gi)}s(Zl,"isContextIdentifier");function $p(e,n){let t=sa(n)??"",[r=""]=t.split("."),i=Object.keys(e);if(!WP(e,r))return{code:"env/unknownKey",message:{de:`'${n}' nennt keinen Umgebungsschl\xFCssel \u2014 bekannt: ${i.join(", ")}.`,en:`'${n}' names no environment key \u2014 known: ${i.join(", ")}.`}};if(Ql(e,t)!==void 0)return null;let o=Tp(e,r);return{code:"env/unknownKey",message:o===null?{de:`'${n}': der Umgebungsschl\xFCssel '${r}' ist ein einzelner Wert \u2014 lies ihn als '${Gi}${r}'.`,en:`'${n}': environment key '${r}' is a single value \u2014 read it as '${Gi}${r}'.`}:{de:`'${n}': der Umgebungsschl\xFCssel '${r}' hat die Felder ${o.join(", ")}.`,en:`'${n}': environment key '${r}' has the fields ${o.join(", ")}.`}}}s($p,"identifierIssue");function Rp(e,n,t=Object.keys(e)){let r={};for(let i of t){let o=Tp(e,i),a=Object.hasOwn(n,i)?n[i]:void 0;if(a===void 0&&F(`[env/missing] context key '${i}' was not supplied`),o===null){r[`${Gi}${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[`${Gi}${i}.${l}`]=d}}return r}s(Rp,"flatten");function JP(e,n,t){if(t===void 0)return!1;let r=Tp(e,n);return r===null?!0:typeof t=="object"&&t!==null&&r.every(i=>t[i]!==void 0)}s(JP,"contextValueComplete");function RH(e,n){switch(n){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(RH,"valueMatchesDataType");function QP(e,n,t=Object.keys(e.types)){let r=new Set(t);for(let i of YP(e.types)){if(!r.has(i.split(".")[0]))continue;let o=n[`${Gi}${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=rt(Ql(e.types,i));RH(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(QP,"assertContextValues");function IH(e){let n=[],t=YP(e.types);for(let r of t){let i=Ql(e.types,r),o=rt(i);if(!qi(i)||o===void 0||!$H.has(o)){n.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){n.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&n.push(`'${r}' has an empty fixed value set`),o!=="text"&&o!=="option"&&n.push(`'${r}' is ${o}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(e.fields))t.includes(r)||n.push(`field spec '${r}' names no leaf of the schema`);return n}s(IH,"schemaIssues");function aa(e){let n=IH(e);n.length>0&&F(`[env/schema] ${n.join("; ")}`)}s(aa,"assertSchema");var Ip={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function zi(e){return JSON.stringify(e)}s(zi,"canonical");function da(e){return e.kind==="binary"&&e.op==="&&"?[...da(e.left),...da(e.right)]:[e]}s(da,"conjuncts");function eN(e,n){let t;try{t=On(e)}catch{return!1}let r=zi(On(n));return da(t).some(i=>zi(i)===r)}s(eN,"hasConjunct");function nN(e,n){try{return zi(On(e))===zi(On(n))}catch{return!1}}s(nN,"sameCondition");function tN(e){let n=[];for(let t of e)n.push(..._n(di(t)));return HP(n)}s(tN,"contextKeysRead");function rN(e){try{return _n(On(e)).some(Zl)}catch{return!1}}s(rN,"readsContext");var OH=/^\d{4}-\d{2}-\d{2}$/,_H=new Set(["==","!=","<","<=",">",">=","in"]),PH=new Set(["<","<=",">",">="]);function _p(e,n,t=[]){aa(n);let r;try{r=On(e)}catch(a){let l=a.message;return[Wn("condition/parse",`Bedingung '${e}' ist nicht lesbar: ${l}`,`condition '${e}' does not parse: ${l}`)]}let i=[];for(let a of _n(r)){if(!Zl(a)){i.push(Wn("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=$p(n.types,a);l!==null&&i.push(Wn("condition/unknownIdentifier",l.message.de,l.message.en))}if(i.length>0)return i;let o=Gr(r,n,i);Xl(o)||i.push(Wn("condition/notBoolean",`Bedingung '${e}' ist kein Ja/Nein-Ausdruck`,`condition '${e}' is not a yes/no expression`)),FH(r,n,i);for(let{identifier:a,op:l}of Jw(r,n))i.push(Wn("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(...NH(r,t)),i}s(_p,"conditionIssues");function NH(e,n){let t=da(e).map(zi);return n.flatMap(r=>{let i=On(r),o=CH(i);return o===null||!t.includes(zi(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(NH,"guardFormHints");function CH(e){if(e.kind!=="binary"||e.op!=="=="&&e.op!=="!=")return null;let n={...e,left:e.right,right:e.left};return zi(n)===zi(e)?null:n}s(CH,"mirror");function Xl(e){return e.t==="unknown"||e.t==="data"&&e.dt==="boolean"}s(Xl,"isBooleanish");function iN(e){let n=sa(e);return n===null&&F(`[condition/invariant] '${e}' reached a pass that only sees $env identifiers`),n}s(iN,"contextPath");function oN(e,n){let t=sa(n);return t!==null&&e.fields[t]?.nullable===!0}s(oN,"isNullableLeaf");function DH(e,n){let t=rt(Ql(e.types,iN(n)));return t===void 0?{t:"unknown"}:{t:"data",dt:t}}s(DH,"identType");function Op(e,n){return e.t==="unknown"||n.t==="unknown"||e.t==="null"||n.t==="null"?!0:e.t==="array"||n.t==="array"?!1:e.t==="str"&&n.t==="str"?!0:e.t==="str"?ZP(e.value,n.dt):n.t==="str"?ZP(n.value,e.dt):e.dt===n.dt}s(Op,"fits");function ZP(e,n){return n==="text"||n==="option"||n==="edge"?!0:n==="date"?OH.test(e):!1}s(ZP,"strFits");function XP(e){return e.t==="unknown"?"unknown":e.t==="data"&&e.dt==="number"?"number":null}s(XP,"orderedCategory");function Gr(e,n,t){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 DH(n,e.path);case"arr":for(let r of e.items)Gr(r,n,t);return{t:"array"};case"unary":{let r=Gr(e.operand,n,t);return Xl(r)||t.push(Wn("condition/notBoolean","'!' braucht einen Ja/Nein-Operanden","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(Ip,e.name)?Ip[e.name]:void 0,i=e.args.map(l=>Gr(l,n,t));return r===void 0?(t.push(Wn("condition/functionNotAllowed",`Funktion '${e.name}' ist nicht erlaubt \u2014 erlaubt: ${Object.keys(Ip).join(", ")}`,`function '${e.name}' is not allowed \u2014 allowed: ${Object.keys(Ip).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&Op(l,{t:"data",dt:r.params[d]}))||t.push(Wn("condition/typeMismatch",`'${e.name}' nimmt (${r.params.join(", ")})`,`'${e.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=Gr(e.cond,n,t);Xl(r)||t.push(Wn("condition/notBoolean","'if' braucht eine Ja/Nein-Bedingung","'if' needs a yes/no condition"));let i=Gr(e.then,n,t),o=Gr(e.else,n,t);return Op(i,o)||t.push(Wn("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=Gr(e.left,n,t),i=Gr(e.right,n,t);if(e.op==="&&"||e.op==="||")(!Xl(r)||!Xl(i))&&t.push(Wn("condition/notBoolean",`'${e.op}' braucht Ja/Nein-Operanden`,`'${e.op}' needs yes/no operands`));else if(e.op==="in")e.right.kind!=="arr"?t.push(Wn("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=>Op(r,Gr(o,n,[])))||t.push(Wn("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(PH.has(e.op)){let o=XP(r),a=XP(i);(o===null||a===null||o!=="unknown"&&a!=="unknown"&&o!==a)&&t.push(Wn("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 Op(r,i)||t.push(Wn("condition/typeMismatch",`'${e.op}' vergleicht Werte verschiedener Typen`,`'${e.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}s(Gr,"typeOf");function Yw(e){return e.kind==="str"||e.kind==="num"||e.kind==="bool"}s(Yw,"isLiteral");function sN(e){let n=[],t=s(r=>{if(r.kind==="binary"&&_H.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(Yw):Yw(r.right)?[r.right]:[];i.length>0&&n.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&Yw(r.left)&&n.push({ident:r.right.path,literals:[r.left]})}aN(r,t)},"visit");return t(e),n}s(sN,"comparedLiterals");function FH(e,n,t){for(let{ident:r,literals:i}of sN(e)){let o=LH(r,i,n);o!==null&&t.push(o)}}s(FH,"literalIssues");function Hw(e,n){let t;try{t=On(e)}catch{return[]}let r=[];for(let{ident:i,literals:o}of sN(t)){let a=sa(i);if(!(a===null||n.fields[a]?.valueSet.kind!=="live"))for(let l of o)l.kind==="str"&&r.push({path:a,value:l.value})}return r}s(Hw,"liveLiterals");function LH(e,n,t){let r=t.fields[iN(e)]?.valueSet;if(r?.kind==="unstable")return Wn("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=n.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 Wn("condition/literalOutsideSet",`'${e}' kennt nur ${o} \u2014 nicht ${i.join(", ")}`,`'${e}' takes only ${o} \u2014 not ${i.join(", ")}`)}s(LH,"valueSetIssue");function aN(e,n){switch(e.kind){case"binary":n(e.left),n(e.right);return;case"unary":n(e.operand);return;case"call":e.args.forEach(n);return;case"arr":e.items.forEach(n);return;case"if":n(e.cond),n(e.then),n(e.else);return;default:return}}s(aN,"forEachChild");function lN(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(lN,"isNullTest");function dN(e){return da(e).flatMap(n=>{let t=cN(n);return t===null?[]:[t]})}s(dN,"guardsOf");function ed(e,n,t){switch(e.kind){case"ident":return oN(n,e.path)&&!t.has(e.path)?e.path:null;case"call":for(let r of e.args){let i=ed(r,n,t);if(i!==null)return i}return null;case"if":return ed(e.then,n,new Set([...t,...dN(e.cond)]))??ed(e.else,n,t);default:return null}}s(ed,"unguardedNullSource");function cN(e){return!lN(e)||e.kind!=="binary"||e.op!=="!="?null:e.left.kind==="ident"?e.left.path:e.right.kind==="ident"?e.right.path:null}s(cN,"guardedIdent");function la(e,n,t,r){if(e.kind==="binary"&&e.op==="&&"){let i=new Set(t);for(let o of da(e)){la(o,n,i,r);let a=cN(o);a!==null&&i.add(a)}return}if(e.kind==="if"){la(e.cond,n,t,r),la(e.then,n,new Set([...t,...dN(e.cond)]),r),la(e.else,n,t,r);return}if(e.kind==="binary"&&e.op==="!="&&e.left.kind!=="null"&&e.right.kind!=="null"){let i=ed(e.left,n,t)??ed(e.right,n,t);i!==null&&r(i,"!=")}if(e.kind==="unary"&&!lN(e.operand)){let i=_n(e.operand).filter(o=>oN(n,o)&&!t.has(o));i.length>0&&r(i[0],"!")}aN(e,i=>la(i,n,t,r))}s(la,"nullableReads");function Jw(e,n){aa(n);let t=[];return la(e,n,new Set,(r,i)=>{t.some(o=>o.identifier===r)||t.push({identifier:r,op:i})}),t}s(Jw,"unguardedNullableReads");function Wn(e,n,t){return{severity:"error",code:e,message:{de:`[${e}] ${n}`,en:`[${e}] ${t}`}}}s(Wn,"error");function nd(e){let n=Array.isArray(e.nodes)?e.nodes:[],t=new Set;for(let r of n)for(let i of dp(r))i.key!==null&&zs[i.leaf].involves&&t.add(i.key);return t}s(nd,"declaredGroupKeys");var ca=Pf;var MH="unit.key",qH="offer.key";function uN(e,n){return e===MH?n.unitKeys:e===qH?n.offerKeys:null}s(uN,"liveKeyUniverse");function Pp(e){return[yn,...[...nd(e)].sort((n,t)=>n.localeCompare(t)).map(qf)]}s(Pp,"requiredSlots");var Wi=`${Cf("applicant.channel")} == 'staff'`;var Zw=["strict","leastLoaded"];var Qw=2;function fN(e){return e.some(n=>n.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<Qw?{de:`braucht mindestens ${Qw} Personen`,en:`needs at least ${Qw} people`}:null}s(fN,"rotationPoolProblem");function KH(e,n){let t=n===null?-1:e.indexOf(n);return[...e.slice(t+1),...e.slice(0,t+1)]}s(KH,"strictOrder");function pN(e){let n=KH(e.pool,e.previous).filter(i=>e.eligible.has(i));if(n.length===0)return null;if(e.mode==="strict")return n[0];let t=e.openCounts;t===void 0&&F("[assignment/rotation] leastLoaded needs the open counts");let r=s(i=>{let o=t.get(i);return o===void 0&&F(`[assignment/rotation] no open count for '${i}'`),o},"load");return n.reduce((i,o)=>r(o)<r(i)?o:i)}s(pN,"pickFromPool");function hN(e){return e.map(n=>({slot:sO(n.slot),rules:[...n.rules]}))}s(hN,"rulesOfStored");function gN(e){return e.map(n=>({slot:jH(n.slot),rules:[...n.rules]}))}s(gN,"storedOfRules");function jH(e){let n=jf(e);return n===null&&F(`[assignment/unknownSlot] '${e}' is no slot \u2014 'responsible' or 'team:<teamKey>'`),n}s(jH,"slotOf");function yN(e,n){let t=e?.assignmentRules;t===void 0&&F(`[assignment/noRules] ${n}: the workflow has no assignment rule`);let r=vN(t);return r.length>0&&F(`${r.join("; ")} (${n})`),hN(t)}s(yN,"rulesOfGraph");function VH(e){return e===yn?{slot:e,rules:[{when:Wi,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:e,rules:[{when:null,assign:{kind:"queue"}}]}}s(VH,"defaultSlotRules");function wN(e,n){let t=new Set(e.map(o=>o.slot)),r=n.filter(o=>!t.has(o)).map(VH);return[...r.filter(o=>o.slot===yn),...e,...r.filter(o=>o.slot!==yn)]}s(wN,"withRequiredSlots");function Nn(e,n){return n===void 0?`slot '${e}'`:`slot '${e}' row #${n+1}`}s(Nn,"where");function Ft(e,n){return n===void 0?`Liste '${e}'`:`Liste '${e}', Zeile #${n+1}`}s(Ft,"whereDe");function Et(e,n,t={},r="error"){return{severity:r,code:e,message:{de:`[${e}] ${n.de}`,en:`[${e}] ${n.en}`},...t}}s(Et,"issue");function mN(e){if(e===yn)return!0;let n=Kf(e);return n!==null&&n.length>0}s(mN,"isKnownSlot");function BH(e,n){aa(ca);let t=[],r=new Set;e.forEach((o,a)=>{let{slot:l}=o;mN(l)||t.push(Et("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)&&t.push(Et("assignment/duplicateSlot",{de:`${Ft(l)} steht zweimal da`,en:`${Nn(l)} is listed twice`},{slot:l})),r.add(l),l===yn&&a!==0&&t.push(Et("assignment/responsibleFirst",{de:`'${yn}' muss die erste Liste sein \u2014 Team-Zeilen \xFCbernehmen sie`,en:`'${yn}' must be the first slot \u2014 team rows copy it`},{slot:l})),t.push(...UH(o))});for(let o of n)r.has(o)||t.push(Et("assignment/slotMissing",{de:`${Ft(o)} hat keine Regeln \u2014 der Workflow braucht sie`,en:`${Nn(o)} has no rule list \u2014 the workflow needs it`},{slot:o}));let i=new Set(n);for(let{slot:o}of e)o!==yn&&!i.has(o)&&mN(o)&&t.push(Et("assignment/unusedSlot",{de:`${Ft(o)} wird hier nicht gebraucht \u2014 erlaubt, und nicht ausgewertet`,en:`${Nn(o)} is not needed here \u2014 allowed, and not evaluated`},{slot:o},"info"));return t}s(BH,"validateRules");function UH({slot:e,rules:n}){let t=[];return(n.length===0||n[n.length-1].when!==null)&&t.push(Et("assignment/defaultRowMissing",{de:`${Ft(e)} muss mit einer Zeile ohne Bedingung enden (\u201Esonst\u201C)`,en:`${Nn(e)} must end with a row without condition ("otherwise")`},{slot:e})),n.forEach((r,i)=>{let o={slot:e,row:i},{when:a,assign:l}=r;if(a===null&&i<n.length-1&&t.push(Et("assignment/ruleAfterDefault",{de:`${Ft(e,i)} hat keine Bedingung, aber es folgen Zeilen \u2014 sie treffen nie zu`,en:`${Nn(e,i)} has no condition, but rows follow it \u2014 they can never match`},o)),a!==null){let d=_p(a,ca,[Wi]);for(let c of d)t.push({...c,message:{de:`${c.message.de} (${Ft(e,i)})`,en:`${c.message.en} (${Nn(e,i)})`},...o});if(d.every(c=>c.severity!=="error")){rN(a)||t.push(Et("assignment/shadowedRule",{de:`${Ft(e,i)} liest nichts aus dem Vorgang \u2014 sie gilt immer oder nie`,en:`${Nn(e,i)} reads nothing of the application \u2014 it holds for every application or for none`},o));let c=n.slice(0,i).findIndex(u=>u.when!==null&&nN(u.when,a));c!==-1&&t.push(Et("assignment/shadowedRule",{de:`${Ft(e,i)} wiederholt die Bedingung von Zeile #${c+1} \u2014 sie trifft nie zu`,en:`${Nn(e,i)} repeats the condition of row #${c+1} \u2014 it can never match`},o))}}if(e===yn&&l.kind==="slot"&&t.push(Et("assignment/slotForwardRef",{de:`${Ft(e,i)} \xFCbernimmt '${l.slot}' \u2014 das darf nur eine Team-Liste nach '${yn}'`,en:`${Nn(e,i)} copies '${l.slot}' \u2014 only a team slot after '${yn}' may`},o)),e===yn&&l.kind==="queue"&&t.push(Et("assignment/queueOnProcessSlot",{de:`${Ft(e,i)} weist die Queue zu \u2014 die Prozesszust\xE4ndigkeit ist immer eine Person`,en:`${Nn(e,i)} assigns the queue \u2014 the responsible slot is always a person`},o)),l.kind==="unassigned"&&t.push(Et("assignment/targetMissing",{de:`${Ft(e,i)} nennt noch niemanden \u2014 Person w\xE4hlen`,en:`${Nn(e,i)} names no one yet \u2014 choose a person`},o)),l.kind==="rotation"){let d=fN(l.configKeys);d!==null&&t.push(Et("assignment/rotationPool",{de:`${Ft(e,i)}: die Reihum-Liste ${d.de}`,en:`${Nn(e,i)} rotates over a pool that ${d.en}`},o))}l.kind==="creator"&&(a===null||!eN(a,Wi))&&t.push(Et("assignment/unguardedTarget",{de:`${Ft(e,i)} weist die anlegende Person zu \u2014 die gibt es nur, wenn die Bedingung der Zeile '${Wi}' ist (oder enth\xE4lt)`,en:`${Nn(e,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${Wi}'`},o))}),t}s(UH,"rowIssues");function kN(e,n){for(let r of n)e.some(i=>i.slot===r)||F(`[assignment/slotMissing] ${Nn(r)} has no rule list`);let t=new Set(n);return e.filter(r=>t.has(r.slot))}s(kN,"selectSlots");function GH(e,n){return tN(kN(e,n).flatMap(t=>t.rules.flatMap(r=>r.when===null?[]:[r.when])))}s(GH,"contextKeysOfRules");function bN(e,n,t,r){aa(ca);let i=kN(e,t),o=GH(e,t),a=Rp(ca.types,n,o);QP(ca,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 _n(di(h.when)))Object.hasOwn(a,k)||F(`[condition/unknownIdentifier] ${Nn(d,w)} reads '${k}', which the context does not carry`);return DO(h.when,{values:a})});u===-1&&F(`[assignment/defaultRowMissing] ${Nn(d)}: no row matched and there is no default row`);let p=c[u].assign;l.push({slot:d,ruleIndex:u,assign:p,value:zH(d,u,p,l,r)})}return l}s(bN,"evaluateRules");function zH(e,n,t,r,i){switch(t.kind){case"person":return{kind:"value",value:i.person(t.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(t,{slot:e,row:n})};case"unassigned":return F(`[assignment/targetMissing] ${Nn(e,n)} names no one`);case"queue":return e===yn&&F(`[assignment/queueOnProcessSlot] ${Nn(e,n)} assigns the queue`),{kind:"queue"};case"slot":{let o=e===yn?void 0:r.find(a=>a.slot===t.slot);return o===void 0&&F(`[assignment/slotForwardRef] ${Nn(e,n)} copies '${t.slot}', which is not decided before it`),o.value}}}s(zH,"resolveTarget");var Xw={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function WH(e){if(typeof e!="object"||e===null)return!1;let{kind:n,groupKey:t,...r}=e;return Object.keys(r).length>0?!1:n==="responsible"?t===void 0:n==="team"&&typeof t=="string"&&t.length>0}s(WH,"isStoredSlot");function vN(e){let n=[],t=s((r,i)=>n.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 t(o,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&t(o,`unknown field(s) ${Object.keys(d).join(", ")}`),WH(a)||t(o,"slot must be { kind: 'responsible' } or { kind: 'team', groupKey: '<team key>' }"),!Array.isArray(l))return t(o,"rules must be a list");l.forEach((c,u)=>{let p=`${o}.rules[${u}]`;if(typeof c!="object"||c===null)return t(p,"must be { when, assign }");let{when:h,assign:w,...k}=c;Object.keys(k).length>0&&t(p,`unknown field(s) ${Object.keys(k).join(", ")}`),h!==null&&typeof h!="string"&&t(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(Xw,y))return t(p,`assign must be one of ${Object.keys(Xw).map(R=>`{kind:'${R}'}`).join(", ")}`);let b=Xw[y],E=Object.keys(w);(E.some(R=>!b.includes(R))||b.some(R=>!E.includes(R)))&&t(p,`a '${y}' target has exactly the field(s) ${b.join(", ")}`);let T=w;if(y==="person"&&(typeof T.configKey!="string"||T.configKey.length===0)&&t(p,"a 'person' target needs a non-empty configKey"),y==="rotation"){let R=T.configKeys;(!Array.isArray(R)||R.some(D=>typeof D!="string"))&&t(p,"a 'rotation' target needs configKeys, a list of person keys"),Zw.includes(T.mode)||t(p,`a 'rotation' target's mode is one of ${Zw.map(D=>`'${D}'`).join(", ")}`)}y==="slot"&&T.slot!==yn&&t(p,`a 'slot' target copies '${yn}' and nothing else`)})}),n):(t("slots","must be a list of { slot, rules }"),n)}s(vN,"ruleShapeIssues");function xN(e){let n=e??{},t=[];if(n.teamOwnerBindings!==void 0&&t.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"}),n.assignmentRules===void 0)return t.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"}),t;let r=vN(n.assignmentRules);if(r.length>0)return[...t,...r.map(o=>({de:o,en:o}))];let i=Pp({nodes:Array.isArray(n.nodes)?n.nodes:[]});for(let o of BH(hN(n.assignmentRules),i))o.severity==="error"&&t.push(o.message);return t}s(xN,"workflowAssignmentIssues");function Np(e,n){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:n(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:n(p),idx:0}))}}return l}s(Np,"detectBackEdges");var ek="team:",YH=/^[a-z0-9][a-z0-9-]*$/;function HH(e){if(!e.startsWith(ek))return null;let n=e.slice(ek.length);return n.length>0?n:null}s(HH,"teamKeyOfMember");function Cp(e){return`${ek}${e}`}s(Cp,"teamMember");function ua(e){let n=e.channels;return n===void 0?[]:(Array.isArray(n)||F("graph.channels must be an array"),n)}s(ua,"readAuthoredChannels");function SN(e){return[...nd(e)].sort()}s(SN,"derivedChannelTeamKeys");function AN(e,n){let t=e.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!n.has(t))return t;for(let r=2;;r++){let i=`${t}-${r}`;if(!n.has(i))return i}}s(AN,"mintChannelKey");function EN(e,n){let t=e.channels;if(t===void 0)return[];if(!Array.isArray(t))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=nd(e),o=new Set,a=new Map;return t.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||In(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(E=>typeof E=="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}"`};YH.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=In(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 E of u.members){let T=HH(E);if(T===null){r.push({path:`${c}.members`,reason:{de:`[channels/invalidMember] ${p.de}: "${E}" ist kein "team:<schl\xFCssel>".`,en:`[channels/invalidMember] ${p.en}: "${E}" is not a "team:<key>".`}});continue}if(w.includes(T)){r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMember] ${p.de}: Team "${T}" ist doppelt genannt.`,en:`[channels/duplicateMember] ${p.en}: team "${T}" is named twice.`}});continue}n!==void 0&&!n.has(T)&&r.push({path:`${c}.members`,reason:{de:`[channels/unknownTeam] ${p.de}: Team "${T}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`,en:`[channels/unknownTeam] ${p.en}: team "${T}" does not exist at this school (or it is the applicant group).`}}),w.push(T)}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 b=a.get(k);b!==void 0?r.push({path:`${c}.members`,reason:{de:`[channels/duplicateMembership] ${p.de}: dieselben Teams wie Kanal "${b}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`,en:`[channels/duplicateMembership] ${p.en}: the same teams as channel "${b}" \u2014 two tabs would be the same chat.`}}):a.set(k,u.key)}),r}s(EN,"channelIssues");var fye=Object.freeze({});function JH(e,n){return Object.freeze(Rp(ri,e,n))}s(JH,"formContextEntries");function TN(e){return e.env??[]}s(TN,"declaredContextKeys");function $N(e,n){return TN(e).every(t=>RN(t,n?.[t]))}s($N,"scenarioContextComplete");function RN(e,n){return JP(ri,e,n)}s(RN,"contextValueComplete");function IN(e,n){return JH(n??{},TN(e))}s(IN,"scenarioContextEntries");function tk(e){return Zl(e)}s(tk,"isContextIdentifier");function QH(e,n,t){let r=$p(ri,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,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(QH,"contextIdentifierIssue");var nk=Cf("stage.key");function ZH(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===nk,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.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),n}s(ZH,"stageKeyLiterals");function Dp(e,n,t){return n===void 0?[]:ZH(e).filter(r=>!n.has(r)).map(r=>_N(r,n,t))}s(Dp,"stageKeyAstIssues");function ON(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(_N(i.key,n,`scenario:${r.id}/env`))}return t}s(ON,"scenarioStageKeyIssues");function _N(e,n,t){let r=[...n].sort();return{severity:"error",path:t,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.")+` \`${nk}\` 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.")+` \`${nk}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(_N,"unknownStageKeyIssue");function PN(e,n,t){let r=[];for(let i of _n(e)){if(!tk(i))continue;let o=QH(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Jw(e,Pf))r.push({severity:"error",path:t,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(PN,"contextAstIssues");function NN(e,n){let t=[...XH(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!Ns(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${Ps.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${Ps.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.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=>Ns(a)&&!RN(a,i.env?.[a]));o.length>0&&t.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??{}))Ns(a)?r.has(a)||t.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.`}}):t.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 t}s(NN,"formContextIssues");function XH(e){let n=[];Object.hasOwn(e,"context")&&n.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 t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.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 n}s(XH,"retiredContextFields");function Fp(e,n,t){let r=_p(e,n).filter(o=>o.severity==="error").map(o=>o.message);if(r.length>0)return r;let i=[];if(t?.liveEnvKeys!==void 0)for(let o of Hw(e,n)){let a=uN(o.path,t.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 Dp(On(e),t?.stageKeys,""))i.push({de:`[${o.code}] ${o.message.de}`,en:`[${o.code}] ${o.message.en}`});return i}s(Fp,"envConditionFindings");function Lp(e){return e.kind==="entered"&&!e.repeated&&e.reviewRequired}s(Lp,"isReviewField");function fa(e){let n=[],t=[];function r(y,b){try{return On(y)}catch(E){n.push({path:b,src:y,reason:E instanceof Error?E.message:String(E)});return}}s(r,"tryParse");function i(y,b){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,requiredIf:y.requiredIf?r(y.requiredIf,`${b}.requiredIf`):void 0,disabledIf:y.disabledIf?r(y.disabledIf,`${b}.disabledIf`):void 0,defaultValue:y.defaultValue?r(y.defaultValue,`${b}.defaultValue`):void 0}}s(i,"compileField");function o(y,b){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,fields:y.fields.map((E,T)=>i(E,`${b}.fields[${T}]`))}}s(o,"compileGroup");function a(y,b){return{...y,itemTemplate:y.itemTemplate.map((E,T)=>i(E,`${b}.itemTemplate[${T}]`)),effects:y.effects?.map((E,T)=>d(E,`${b}.effects[${T}]`)),itemVisibleIf:y.itemVisibleIf?r(y.itemVisibleIf,`${b}.itemVisibleIf`):void 0}}s(a,"compileRepeated");function l(y,b){let E=[];return y.fields.forEach((T,R)=>{if(T.externalFlag){t.push({key:T.key,label:T.label,defaultValue:T.defaultValue?r(T.defaultValue,`${b}.fields[${R}].defaultValue`):void 0});return}E.push(i(T,`${b}.fields[${R}]`))}),{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${b}.visibleIf`):void 0,fields:E,groups:y.groups?.map((T,R)=>o(T,`${b}.groups[${R}]`)),computed:y.computed?.map((T,R)=>{let D=r(T.expression,`${b}.computed[${R}].expression`);return{key:T.key,expression:D??{kind:"null"}}}),subsections:y.subsections?.map((T,R)=>l(T,`${b}.subsections[${R}]`)),repeated:y.repeated?.map((T,R)=>a(T,`${b}.repeated[${R}]`)),validators:y.validators}}s(l,"compileSection");function d(y,b){return{...y,when:y.when?r(y.when,`${b}.when`):void 0}}s(d,"compileEffect");function c(y,b){let E=r(y.when,`${b}.when`);return E?{...y,when:E}:null}s(c,"compileOutcome");let u=e.sections.map((y,b)=>l(y,`sections[${b}]`)),p=(e.effects??[]).map((y,b)=>d(y,`effects[${b}]`)),h=[],w=e.outcomes??[];for(let y=0;y<w.length;y++){let b=w[y],E=c(b,`outcomes[${y}]`);E&&h.push(E)}return{compiled:{...e,sections:u,effects:p,outcomes:h,flags:t},errors:n}}s(fa,"compileForm");var eJ=new Set(["decision","review","governedDocument"]);function DN(e){return eJ.has(e.type)&&!(e.type==="governedDocument"&&e.production==="none")}s(DN,"isReadinessGatedNode");function nJ(e){let n=new Map,t=rJ(e),r=s((i,o)=>{let a=rk(o),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&n.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:tJ(d.bucket,t,a),section:a,type:d.type,enumSource:CN(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}`;n.set(u,{kind:"entered",key:u,label:c.label,qualifier:rk(d),section:a,type:c.type,enumSource:CN(c),repeated:!0,reviewRequired:!1})}for(let d of i.computed??[]){let c=_n(On(d.expression));n.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 n}s(nJ,"formFieldCatalog");function CN(e){return e.type==="enum"?e:null}s(CN,"enumSourceOf");function tJ(e,n,t){return e===void 0?t:n.get(e)??t}s(tJ,"fieldQualifier");function rJ(e){let n=new Map,t=s((r,i)=>{i===void 0||n.has(r)||n.set(r,rk(i))},"add");for(let r of LN(e))r.kind==="person"?t(r.bucket,r.display):r.kind==="organization"&&t(r.id.replace(/^o\./,""),r.display);return n}s(rJ,"bucketWordings");function FN(e){return e.flatMap(n=>[n,...FN(n.subsections??[])])}s(FN,"allSections");function LN(e){return[...e.effects,...FN(e.sections).flatMap(n=>(n.repeated??[]).flatMap(t=>t.effects??[]))]}s(LN,"allEffects");function rk(e){return{label:e.label}}s(rk,"wordingOf");function MN(e){return Fl(e).flatMap(({slot:n,address:t})=>{let r=jO(t);return r===null||Dl.includes(r.path)?[]:[{slotId:n,owner:r.owner,fieldKey:r.path}]})}s(MN,"admissionBindingLeaves");function iJ(e,n){let t=e.get(n);if(t===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(t),r}s(iJ,"expandKey");function oJ(e){let n=new Set;for(let t of LN(e))if(!(t.kind!=="person"||t.contractParty===void 0)&&t.when!==void 0)for(let r of _n(On(t.when)))n.add(r);return[...n]}s(oJ,"contractPartyConditionKeys");function sJ(e){return fa(e).compiled.flags.map(n=>({key:n.key,name:n.label}))}s(sJ,"formExternalFlags");function qN(e){return{readinessFormFieldsByFormNode:new Map([...e].map(([n,t])=>[n,nJ(t)])),readinessPartyConditionKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(oJ(t))])),formFlagKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set(sJ(t).map(r=>r.key))])),formViewKeysByFormNode:new Map([...e].map(([n,t])=>[n,new Set((t.views??[]).map(r=>r.key))]))}}s(qN,"readinessUniverse");function ik(e,n){let t=new Set;for(let r of n)for(let i of iJ(e,r)??[])i.kind==="entered"&&t.add(i.fieldKey);return t}s(ik,"enteredFieldsBehind");var aJ=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","notice","reason"]);function lJ(e){return aJ.has(e)?!0:KN(e)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(e)}s(lJ,"isTextKey");function KN(e){return/^localized[A-Z]/.test(e)}s(KN,"isLegacyTwinKey");var dJ=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),cJ=new Set(["inputs","resolver","library"]);function qp(e,n){let t=[];return ok(e,n,t),t}s(qp,"findUnlocalizedTexts");function ok(e,n,t){if(Array.isArray(e)){e.forEach((i,o)=>ok(i,`${n}[${fJ(i,o)}]`,t));return}if(e===null||typeof e!="object")return;let r=e;for(let[i,o]of Object.entries(r)){let a=`${n}.${i}`;if(!cJ.has(i)){if(KN(i)){t.push({path:a,missing:"legacy-twin"});continue}if(lJ(i)){uJ(o,a,t);continue}if(dJ.has(i)&&o!==null&&typeof o=="object"){for(let[l,d]of Object.entries(o))d!==void 0&&jN(d,`${a}.${l}`,t);continue}ok(o,a,t)}}}s(ok,"walk");function uJ(e,n,t){e!=null&&jN(e,n,t)}s(uJ,"checkText");function jN(e,n,t){let r=In(e);(r==="not-localized"||r.length>0)&&t.push({path:n,missing:r})}s(jN,"report");function fJ(e,n){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.id=="string")return t.id;if(typeof t.key=="string")return t.key}return String(n)}s(fJ,"keyOf");function Mp(e,n){return e==="not-localized"?n==="de"?"ist kein zweisprachiger Text ({ de, en })":"is not a bilingual text ({ de, en })":e==="legacy-twin"?n==="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"':n==="de"?`fehlt in: ${e.join(", ")}`:`is missing in: ${e.join(", ")}`}s(Mp,"describe");function sk({path:e,missing:n}){return n==="legacy-twin"?{de:`[i18n/legacyTwin] ${e} ${Mp(n,"de")}.`,en:`[i18n/legacyTwin] ${e} ${Mp(n,"en")}.`}:{de:`[i18n/missingTranslation] ${e} ${Mp(n,"de")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`,en:`[i18n/missingTranslation] ${e} ${Mp(n,"en")} \u2014 every displayed text needs German and English; the language follows the reader's account.`}}s(sk,"unlocalizedTextReason");var pJ={engagePush:["engage"]};function mJ(e){let n=pJ[e.type];return n===void 0?e:Object.fromEntries(Object.entries(e).filter(([t])=>!n.includes(t)))}s(mJ,"withoutMachineData");function VN(e,n){return[...qp(e.nodes.map(mJ),"nodes"),...n===void 0?[]:qp(n,`layout.${n.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:sk(r),severity:"error"}))}s(VN,"checkLocalizedTexts");var hJ="optionalAction:";function BN(e){return`${hJ}${e}:trigger`}s(BN,"optionalActionTriggerActionId");var gJ="processDecide";function UN(e){let n=e.optionalActions;return n==null?[]:(Array.isArray(n)||F(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof n}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),n)}s(UN,"optionalActionBindings");function GN(e){return UN(e).map(n=>({id:BN(n.key),kind:"internal",label:n.label,surface:gJ,placement:"overflow",superUserOnly:!0}))}s(GN,"optionalActionTriggers");function zN(e){let n=e.tasks;return Array.isArray(n)?n:[]}s(zN,"authoredTemplates");function WN(e){let n=e?.result;return n?.kind!=="appointment"?[]:n.participants?.feedback?.tasks??[]}s(WN,"personTasksOf");function ak(e){let n=zN(e);return UN(e).map(t=>{let r=new Set(t.tasks??[]),i=new Set;for(let o of r)for(let a of WN(n.find(l=>l.key===o)))i.add(a);return{binding:t,tasks:r,personTasks:i,keys:new Set([...r,...i])}})}s(ak,"optionalActionMembership");function yJ(e){let n=new Set;for(let t of zN(e))for(let r of WN(t))n.add(r);return n}s(yJ,"personRowTemplateKeys");function YN(e){let n=new Set(yJ(e));for(let{keys:t}of ak(e))for(let r of t)n.add(r);return n}s(YN,"referencedTaskTemplateKeys");var zr={shape:"[taskInput/shape]",notInRound:"[taskInput/notInRound]",notRecord:"[taskInput/notRecord]",prefillNotDeclared:"[taskInput/prefillNotDeclared]",prefillType:"[taskInput/prefillType]",feedbackTasks:"[appointment/feedbackTasks]",feedbackOptional:"[appointment/feedbackOptional]",recordAssignment:"[taskResult/recordAssignment]"},lk=60;function pa(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s(pa,"error");function Mo(e){return Array.isArray(e.tasks)?e.tasks:[]}s(Mo,"tasksOf");function HN(e){return(Array.isArray(e.optionalActions)?e.optionalActions:[]).filter(t=>t.action==="spawnTasks")}s(HN,"spawnBindingsOf");function td(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}s(td,"stringList");function Wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(Wr,"record");function dk(e){let n=Wr(e?.result);return n?.kind==="appointment"?Wr(n.participants):null}s(dk,"participantsOf");function JN(e){return td(Wr(dk(e)?.feedback)?.tasks)}s(JN,"feedbackTasksOf");function QN(e,n){return ak(e).find(t=>t.keys.has(n))}s(QN,"roundOf");function wJ(e,n,t){let r=s(u=>({code:zr.notInRound,reason:u}),"notInRound"),i=QN(e,n);if(i===void 0)return r({de:`Aufgabe "${n}" geh\xF6rt zu keiner optionalen Aktion \u2014 Vorgaben liest nur eine Aufgabe einer Runde.`,en:`Task "${n}" belongs to no optional action \u2014 only a task of a round reads inputs.`});if(t.scope!=="task"||t.path!==void 0)return r({de:`${de(t)} ist kein Wert einer Aufgabe ($task.<aufgabe>.<schl\xFCssel>).`,en:`${de(t)} is no value of a task ($task.<task>.<key>).`});let{binding:o}=i,a=t.owner;if(a===n)return r({de:`Aufgabe "${n}" liest ihren eigenen Wert.`,en:`Task "${n}" reads its own value.`});let l=Mo(e).find(u=>u.key===a),d=Wr(l?.blocks),c=i.tasks.has(a)&&d?.templateKey===n&&(d.node===void 0||d.node===e.id);return a!==o.input&&!c?r({de:`"${a}" ist weder die Eingabe der Aktion "${o.key}" noch eine ihrer Aufgaben, die "${n}" per 'blocks' zur\xFCckh\xE4lt \u2014 der Wert st\xFCnde nicht fest, wenn die Aufgabe \xF6ffnet.`,en:`"${a}" is neither the input of the action "${o.key}" nor one of its tasks that holds "${n}" through 'blocks' \u2014 the value would not be settled when the task opens.`}):Wr(l?.result)?.kind!=="record"?{code:zr.notRecord,reason:{de:`"${a}" hat kein Ergebnis vom Typ 'record' \u2014 Vorgaben sind Felder einer Eingabe.`,en:`"${a}" has no result of kind 'record' \u2014 inputs are fields of an input task.`}}:null}s(wJ,"taskInputRefusal");function kJ(e,n){if(n.scope!=="task")return;let t=Mo(e).find(i=>i.key===n.owner),r=Wr(t?.result);if(r?.kind==="record")return(Array.isArray(r.fields)?r.fields:[]).map(Wr).find(i=>i?.writes===n.key)??void 0}s(kJ,"writerField");function bJ(e,n,t){let r=String(n.key);if(n.inputs===void 0)return[];if(!Array.isArray(n.inputs))return[pa(`${t}.inputs`,zr.shape,{de:"'inputs' ist eine Liste von Adressen.",en:"'inputs' is a list of addresses."})];let i=[],o=new Set;for(let[a,l]of n.inputs.entries()){if(!we(l))continue;let d=de(l);if(o.has(d)){i.push(pa(`${t}.inputs.${a}`,zr.shape,{de:`${d} steht zweimal in 'inputs'.`,en:`${d} is listed twice in 'inputs'.`}));continue}o.add(d);let c=wJ(e,r,l);c!==null&&i.push(pa(`${t}.inputs.${a}`,c.code,c.reason))}return i}s(bJ,"inputIssues");function vJ(e,n,t,r){let i=t,o=Array.isArray(i.inputs)?i.inputs.filter(we).map(de):[];if(!we(r)||!o.includes(de(r)))return{code:zr.prefillNotDeclared,reason:{de:"Die Vorbelegung der Teilnehmenden ist keine der Vorgaben ('inputs') der Aufgabe.",en:"The participants' prefill is none of the task's inputs ('inputs')."}};let a=s(c=>({code:zr.prefillType,reason:c}),"prefillType"),l=JN(i),d=Cl(e,r);if(d===void 0)return null;if(rt(d)==="staffUser")return l.length===1?null:a({de:"Eine Personenliste belegt nur vor, wenn 'feedback.tasks' genau eine Feedback-Art nennt \u2014 sonst w\xE4re offen, wer welche Art gibt.",en:"A list of persons prefills only when 'feedback.tasks' names exactly one feedback kind \u2014 otherwise who gives which kind would be open."});if(d==="taskAssignment"){let u=td(kJ(n,r)?.tasks).filter(p=>!l.includes(p));return u.length===0?null:a({de:`Die Zuordnung ordnet ${u.map(p=>`"${p}"`).join(", ")} zu, die 'feedback.tasks' nicht nennt.`,en:`The assignment assigns ${u.map(p=>`"${p}"`).join(", ")}, which 'feedback.tasks' does not name.`})}return a({de:`Vorbelegt werden Teilnehmende nur aus Personen ('person') oder einer Zuordnung ('assignment'), nicht aus "${d}".`,en:`Participants are prefilled only from persons ('person') or an assignment ('assignment'), not from "${d}".`})}s(vJ,"participantPrefillRefusal");function xJ(e,n,t,r){let i=dk(t)?.prefill;if(i===void 0)return[];let o=vJ(e,n,t,i);return o===null?[]:[pa(`${r}.result.participants.prefill`,o.code,o.reason)]}s(xJ,"prefillIssues");function SJ(e,n){return HN(e).some(t=>td(t.tasks).includes(n))}s(SJ,"belongsToOptionalAction");function AJ(e,n,t){let r=n.key,i=Mo(e).find(c=>c.key===t),o=s(c=>({code:zr.feedbackTasks,reason:c}),"feedbackTasks");if(i===void 0)return[o({de:`"${t}" ist keine Aufgabe dieses Knotens.`,en:`"${t}" is no task of this node.`})];let a=[];i.feedback!==!0&&a.push(o({de:`"${t}" ist keine Feedback-Aufgabe ('feedback: true').`,en:`"${t}" is no feedback task ('feedback: true').`})),HN(e).some(c=>td(c.tasks).includes(t))&&a.push(o({de:`"${t}" steht in den Aufgaben einer optionalen Aktion \u2014 eine Personenzeile entsteht nur beim Buchen.`,en:`"${t}" is among an optional action's tasks \u2014 a person row exists only through a booking.`}));let l=Mo(e).find(c=>c.key!==r&&JN(c).includes(t));l!==void 0&&a.push(o({de:`"${t}" wird auch von "${String(l.key)}" angelegt \u2014 jede Feedback-Art geh\xF6rt zu genau einem Termin.`,en:`"${t}" is also created by "${String(l.key)}" \u2014 each feedback kind belongs to exactly one appointment.`}));let d=["when","blocks"].filter(c=>i[c]!==void 0);return d.length>0&&a.push(o({de:`"${t}" tr\xE4gt ${d.map(c=>`'${c}'`).join(", ")} \u2014 eine Personenzeile entsteht nur beim Buchen und h\xE4lt nur ihre Runde.`,en:`"${t}" carries ${d.map(c=>`'${c}'`).join(", ")} \u2014 a person row exists only through a booking and holds only its round.`})),i.optional!==void 0&&a.push({code:zr.feedbackOptional,reason:{de:`"${t}" ist optional \u2014 eine Personenzeile h\xE4lt ihre Runde und damit die Pause, sie kann nicht \xFCbersprungen werden.`,en:`"${t}" is optional \u2014 a person row holds its round and with it the pause; it cannot be skipped.`}}),a}s(AJ,"participantFeedbackRefusals");function EJ(e,n,t){let r=dk(n);if(r===null||r.feedback===void 0)return[];let i=String(n.key),o=`${t}.result.participants.feedback`,a=Wr(r.feedback),l=a?.tasks,d=[],c=s((p,h,w=zr.feedbackTasks)=>d.push(pa(p,w,h)),"fail");if(!Array.isArray(l)||l.length===0||l.some(p=>typeof p!="string")||new Set(l).size!==l.length)return c(`${o}.tasks`,{de:"'feedback.tasks' nennt mindestens eine Feedback-Aufgabe, jede einmal.",en:"'feedback.tasks' names at least one feedback task, each once."}),d;let u=a?.dueDaysAfterEnd;(typeof u!="number"||!Number.isInteger(u)||u<0||u>lk)&&c(`${o}.dueDaysAfterEnd`,{de:`'feedback.dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${lk}.`,en:`'feedback.dueDaysAfterEnd' is a whole number from 0 to ${lk}.`}),SJ(e,i)||c(o,{de:`Aufgabe "${i}" legt Personenzeilen an, geh\xF6rt aber zu keiner optionalen Aktion \u2014 Personenzeilen geh\xF6ren zur Runde einer Aktion.`,en:`Task "${i}" creates person rows but belongs to no optional action \u2014 person rows belong to an action's round.`});for(let p of l)for(let h of AJ(e,n,p))c(`${o}.tasks`,h.reason,h.code);return d}s(EJ,"feedbackIssues");function TJ(e,n){let t=QN(e,n)?.personTasks??new Set;return Mo(e).filter(r=>r.feedback===!0&&typeof r.key=="string"&&t.has(r.key)).map(r=>r.key)}s(TJ,"assignableFeedbackTasks");function $J(e,n,t){let r=Wr(n.result);if(r?.kind!=="record"||!Array.isArray(r.fields))return[];let i=TJ(e,String(n.key)),o=new Map(Mo(e).map(l=>[l.key,l])),a=[];for(let[l,d]of r.fields.entries()){let c=Wr(d);if(c?.type!=="assignment")continue;let u=td(c.tasks).filter(p=>o.get(p)?.feedback===!0&&!i.includes(p));u.length!==0&&a.push(pa(`${t}.result.fields.${l}.tasks`,zr.recordAssignment,{de:`Feld "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} legt kein Termin derselben optionalen Aktion an ('participants.feedback.tasks') \u2014 die Zuordnung h\xE4tte keine Zeile, die sie erh\xE4lt.`,en:`Field "${String(c.key)}": ${u.map(p=>`"${p}"`).join(", ")} is created by no appointment of the same optional action ('participants.feedback.tasks') \u2014 the assignment would have no row to receive it.`}))}return a}s($J,"assignmentIssues");function ZN(e,n){let t=[];for(let r of Mo(n)){if(typeof r.key!="string")continue;let i=`nodes.${n.id}.tasks.${r.key}`;t.push(...bJ(n,r,i)),t.push(...xJ(e,n,r,i)),t.push(...EJ(n,r,i)),t.push(...$J(n,r,i))}return t}s(ZN,"taskInputIssues");var Tt={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 $t(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:`${n} ${t.de}`,en:`${n} ${t.en}`},severity:"error"}}s($t,"issue");function RJ(e,n,t){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===t&&a===n}).map(i=>({nodeId:r.id,key:String(i.key)})))}s(RJ,"blockersOf");function XN(e){let{graph:n,node:t,task:r}=e,i=r.familyRequest;if(i===void 0)return[];let o=typeof r.key=="string"?r.key:"?",a=`nodes.${t.id}.tasks.${o}`,l={de:`Task "${o}" auf Knoten \u201E${_e(n,t.id,"de")}\u201C (${t.id})`,en:`Task "${o}" on node "${_e(n,t.id,"en")}" (${t.id})`},d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[$t(`${a}.familyRequest`,Tt.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($t(`${a}.familyRequest.${c[0]}`,Tt.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($t(`${a}.familyRequest`,Tt.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($t(`${a}.familyRequest`,Tt.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($t(`${a}.kind`,Tt.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($t(`${a}.${k}`,Tt.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($t(`${a}.blocks`,Tt.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 RJ(n.nodes,t.id,o))d.push($t(`nodes.${k.nodeId}.tasks.${k.key}.blocks`,Tt.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($t(`${a}.params.dueInDays`,Tt.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($t(`${a}.familyRequest.fields`,Tt.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(!we(k))continue;let y=de(k);if(w.has(y)){d.push($t(`${a}.familyRequest.fields`,Tt.fields,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} mehrfach.`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} more than once.`}));continue}w.add(y),un(k)||d.push($t(`${a}.familyRequest.fields`,Tt.unknownField,{de:`${l.de}: 'familyRequest.fields' nennt ${je(n,k,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`,en:`${l.en}: 'familyRequest.fields' names ${je(n,k,"en")} \u2014 only a field of a form ($node.<form>.admission.<field>) can be requested.`}))}return d}s(XN,"familyRequestIssues");function eC(e){let n=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"&&n.has(a));return o.length<=1?[]:[$t(`nodes.${e.id}.optionalActions.${i}.tasks`,Tt.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(eC,"familyRequestActionIssues");function nC(e,n){let t=e.nodes,r=new Map;for(let a of t)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)un(l)&&r.set(de(l),l);if(r.size===0)return[];let i=s(a=>{let l=Ur(n,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(un):!we(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return t.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(de(y)));return k.length===0?[]:[{...$t(`nodes.${a.id}.requiresOneOf`,Tt.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(nC,"familyRequestDeadlockWarnings");var ck={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,view:!0,familyRequest:!0,optional:!0,inputs:!0,params:!0},uk={appointment:s((e,n)=>({de:`Aufgabe "${e}" an ${n.de}: \`appointment\` (Terminaufgabe) gibt es nicht mehr \u2014 ein Termin hat keine Leitung, die sie hielte. Was die Teilnehmenden nach dem Termin festhalten, ist je Person eine R\xFCckmeldung (\`result.participants.feedback\` der Terminvereinbarung).`,en:`Task "${e}" on ${n.en}: \`appointment\` (appointment task) no longer exists \u2014 an appointment has no lead to hold it. What the participants record after the appointment is one feedback per person (\`result.participants.feedback\` of the booking task).`}),"appointment")};function IJ(e){let n=Je(e);return new Map((typeof n.workItemTemplates=="function"?n.workItemTemplates(e):[]).map(t=>[t.key,t]))}s(IJ,"intrinsicTemplatesOf");function tC(e,n,t){if(t!==void 0&&typeof t!="string")return null;let r=t??n,i=e.nodes.find(l=>l.id===r);if(i===void 0)return null;let o=i,a=Je(i);return{node:o,composedKeys:new Set((Array.isArray(o.tasks)?o.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:IJ(i),refuse:s(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}s(tC,"resolveBlocksTargetNode");function OJ(e){let n=new Map;for(let r of nr(e.nodes)){let i=n.get(r.source)??[];i.push(r.target),n.set(r.source,i)}let t=new Map;return r=>{let i=t.get(r);if(i!==void 0)return i;let o=new Set,a=[...n.get(r)??[]];for(;a.length>0;){let l=a.shift();o.has(l)||(o.add(l),a.push(...n.get(l)??[]))}return t.set(r,o),o}}s(OJ,"reachability");function rC(e){let n=[],t=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;t.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("::");n.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=t.get(o);l!==void 0&&t.has(l)&&i(l,[...a,o]),r.set(o,"done")},"walk");for(let o of t.keys())i(o,[]);return n}s(rC,"checkBlocksCycles");function _J(e){let{requiresOneOf:n,optionalActions:t}=e;if(!Array.isArray(n)||!Array.isArray(t))return new Set;let r=new Set(n.filter(o=>typeof o=="string")),i=new Set;for(let o of t)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(_J,"tasksOfRequiresOneOf");function iC(e){if(typeof e!="object"||e===null)return!1;let{de:n,en:t}=e;return typeof n=="string"&&n.trim().length>0&&typeof t=="string"&&t.trim().length>0}s(iC,"isFilledBilingual");var PJ=["blocks","gatesNode","locksEvidence","completableIf"];function NJ(e,n){let t={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},r=[];e.feedback!==!0&&r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackNotTrue] ${t.de}: 'feedback' kennt nur true; erhalten ${JSON.stringify(e.feedback)}.`,en:`[workItems/feedbackNotTrue] ${t.en}: 'feedback' only knows true; got ${JSON.stringify(e.feedback)}.`}));let i=e.result;if(e.kind!=="task"||typeof i?.kind!="string"||!Qy({kind:i.kind,writes:i.writes})){let a=e.kind==="task"&&i?.writes!==void 0,l={de:e.kind!=="task"?`kind ${String(e.kind)}`:`Ergebnis ${String(i?.kind)}${a?" mit writes":""}`,en:e.kind!=="task"?`kind ${String(e.kind)}`:`result ${String(i?.kind)}${a?" with writes":""}`};r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackNeedsProse] ${t.de} ist eine Feedback-Aufgabe und schlie\xDFt daher mit Freitext, einer Empfehlung oder einer Auswahl ohne 'writes' \u2014 ein Wert, den ein sp\xE4terer Schritt liest, k\xE4me von einem wom\xF6glich weitergeleiteten Link; erhalten ${l.de}.`,en:`[workItems/feedbackNeedsProse] ${t.en} is a feedback task, so it closes with free text, a recommendation or a choice without 'writes' \u2014 a value a later step reads would come from a link that may have been forwarded; got ${l.en}.`}))}let o=["blocks","gatesNode","completableIf","locksEvidence","familyRequest"].filter(a=>e[a]!==void 0);return o.length>0&&r.push(En(`${n.base}.feedback`,{de:`[workItems/feedbackSteersProcess] ${t.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] ${t.en} is a feedback task; its answer comes from a page without application data, so it may not depend on ${o.join(", ")}.`})),r}s(NJ,"feedbackTaskIssues");function CJ(e,n){let t=[],r={de:`Task "${n.key}" (Knoten "${n.nodeId}")`,en:`Task "${n.key}" (node "${n.nodeId}")`},i=e.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!iC(i.skipLabel))&&t.push(En(`${n.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"&&t.push(En(`${n.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"||!Qy({kind:a.kind,writes:a.writes}))&&t.push(En(`${n.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=PJ.filter(d=>e[d]!==void 0);return l.length>0&&t.push(En(`${n.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.`})),n.requiredByRule&&t.push(En(`${n.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.`})),t}s(CJ,"optionalTaskIssues");function En(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(En,"issue");function oC(e,n){let t=[],r=OJ(e),i=new Set(ua(e).map(o=>o.key));t.push(...nC(e,n));for(let o of e.nodes){let a=o,l=YN(a);t.push(...eC(a));let d=_J(a);t.push(...ZN(e,a));let c=new Map((Array.isArray(a.tasks)?a.tasks:[]).filter(u=>typeof u.key=="string").map(u=>[u.key,{feedback:u.feedback===!0}]));for(let u of Array.isArray(a.tasks)?a.tasks:[]){let p=typeof u.key=="string"?u.key:"?",h=`nodes.${o.id}.tasks.${p}`,w=u.kind,k=u.result,y=u.blocks,b=typeof y?.node=="string"&&y.node!==o.id?y.node:void 0;if(typeof y?.templateKey=="string"){let P=typeof y.node=="string"?y.node:o.id,A=e.nodes.find(oe=>oe.id===P),U=(Array.isArray(A?.tasks)?A.tasks:[]).find(oe=>oe.key===y.templateKey)?.blocks;typeof U?.node=="string"&&U.node!==P&&t.push(En(`${h}.blocks.templateKey`,{de:`[workItems/blocksCrossNodeTask] Task "${p}" auf Knoten "${o.id}" h\xE4lt "${y.templateKey}" auf Knoten "${P}" 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 "${p}" on node "${o.id}" holds back "${y.templateKey}" on node "${P}" \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(b!==void 0){let P=b;e.nodes.some(A=>A.id===P)&&!r(o.id).has(P)&&t.push(En(`${h}.blocks.node`,{de:`[workItems/blocksTargetNotAfter] Task "${p}" auf Knoten "${o.id}" blockiert Knoten "${P}", 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 "${p}" on node "${o.id}" blocks node "${P}", 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.`})),(k===void 0||!Ms(k.kind))&&t.push(En(`${h}.blocks.node`,{de:`[workItems/crossNodeBlocksNeedsResult] Task "${p}" auf Knoten "${o.id}" blockiert einen anderen Knoten ("${P}"), 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 "${p}" on node "${o.id}" blocks another node ("${P}") 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(p)&&t.push(En(`${h}.blocks.node`,{de:`[optionalAction/crossNodeBlocks] Task "${p}" 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 "${p}" 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 P of vP(String(w),k,{channelKeys:i,nodeTasks:c,...n?.billingItemKeys!==void 0?{billingItemKeys:n.billingItemKeys}:{},...n?.offerProgram!==void 0?{offerProgram:n.offerProgram}:{}}))t.push(En(`${h}.${P.field}`,{de:`${P.code} ${P.message.de} (Task "${p}" auf Knoten "${o.id}").`,en:`${P.code} ${P.message.en} (task "${p}" on node "${o.id}").`}));let E=u.when,T=s((P,A,M)=>{!we(A)||un(A)||t.push(En(P,{de:`[workItems/evidenceNotFormField] ${M} auf Task "${p}" (Knoten "${o.id}") nennt ${je(e,A,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`,en:`[workItems/evidenceNotFormField] ${M} on task "${p}" (node "${o.id}") names ${je(e,A,"en")} \u2014 the condition and evidence of a task are fields of a form ($node.<form>.admission.<field>).`}))},"notFormField");E!==void 0?(T(`${h}.when`,E,"'when'"),u.onConditionReturn!=="respawn"&&u.onConditionReturn!=="stayClosed"&&t.push(En(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] Task "${p}" (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 "${p}" (node "${o.id}") has a condition but no 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 what happens when the condition returns must be decided.`}))):u.onConditionReturn!==void 0&&t.push(En(`${h}.onConditionReturn`,{de:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${p}" (Knoten "${o.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`,en:`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' without 'when' on task "${p}" (node "${o.id}") \u2014 without a condition nothing returns.`}));let R=u.reads;if(R!==void 0)if(!Array.isArray(R))t.push(En(`${h}.reads`,{de:`[workItems/readsUnknownField] 'reads' auf Task "${p}" (Knoten "${o.id}") muss eine Liste von Feldadressen sein.`,en:`[workItems/readsUnknownField] 'reads' on task "${p}" (node "${o.id}") must be a list of field addresses.`}));else for(let[P,A]of R.entries())T(`${h}.reads.${P}`,A,"'reads'");let D=u.locksEvidence,L=s((P,A)=>t.push(En(`${h}.locksEvidence`,{de:`[workItems/${P}] Task "${p}" (Knoten "${o.id}") ${A.de}`,en:`[workItems/${P}] Task "${p}" (node "${o.id}") ${A.en}`})),"lockIssue");D!==void 0&&D!==!0&&L("locksEvidenceNotTrue",{de:`tr\xE4gt 'locksEvidence' ${JSON.stringify(D)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`,en:`carries 'locksEvidence' ${JSON.stringify(D)} \u2014 only 'true' is allowed; without a lock the field is dropped.`}),D===!0&&(R===void 0&&E===void 0&&L("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."}),(k===void 0||!Ms(k.kind))&&L("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(p)&&L("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."})),t.push(...XN({graph:e,node:a,task:u,onTrigger:l,specCtx:n}));let _=Object.keys(u).filter(P=>!Object.hasOwn(ck,P)&&!Object.hasOwn(uk,P));_.length>0&&t.push(En(`${h}.${_[0]}`,{de:`[workItems/unknownKey] Task "${p}" (Knoten "${o.id}") tr\xE4gt ${_.map(P=>`'${P}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(ck).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`,en:`[workItems/unknownKey] Task "${p}" (node "${o.id}") carries ${_.map(P=>`'${P}'`).join(", ")} \u2014 not a field of a task. Allowed: ${Object.keys(ck).join(", ")}. (Checklists no longer exist: text goes in 'description', several work steps are several tasks.)`}));let v=u.description;v!==void 0&&!iC(v)&&t.push(En(`${h}.description`,{de:`[workItems/descriptionInvalid] 'description' auf Task "${p}" (Knoten "${o.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(v)}.`,en:`[workItems/descriptionInvalid] 'description' on task "${p}" (node "${o.id}") needs text in both languages ({ de, en }), got ${JSON.stringify(v)}.`})),u.feedback!==void 0&&t.push(...NJ(u,{key:p,nodeId:o.id,base:h})),u.optional!==void 0&&t.push(...CJ(u,{key:p,nodeId:o.id,base:h,requiredByRule:d.has(p)}))}}return t}s(oC,"checkNodeTasks");function sC(e){let n=e.indexOf(":"),t=n===-1?"":e.slice(0,n),r=n===-1?"":e.slice(n+1).trim();if(t==="artifact"&&r.length>0)return{kind:t,key:r};let i=ti(r);return t==="field"&&i!==null?{kind:t,address:i}:ae("INVALID",{de:`Dokument-Verweis "${e}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel> (auch der Slot eines anderen Knotens) oder field:$node.<Formular>.admission.<Feld>.`,en:`Document reference "${e}" is invalid \u2014 expected artifact:<slot key> (another node's slot too) or field:$node.<form>.admission.<field>.`})}s(sC,"parseTaskDocumentRef");function fk(e){return e.kind==="artifact"?`artifact:${e.key}`:`field:${de(e.address)}`}s(fk,"taskDocumentId");function pi(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(pi,"issue");function aC(e){return Array.isArray(e.tasks)?e.tasks:[]}s(aC,"tasksOf");function rd(e){let n=new Map;for(let t of e){let{id:r,artifacts:i}=t;for(let o of Array.isArray(i)?i:[])typeof o?.key=="string"&&n.set(o.key,[...n.get(o.key)??[],{nodeId:r,slot:o}])}return n}s(rd,"artifactSlotDeclarations");function DJ(e){return e.flatMap(n=>{let{id:t,artifacts:r}=n;return(Array.isArray(r)?r:[]).filter(i=>!wp(i?.type)).map(i=>({nodeId:String(t),slotKey:String(i?.key),type:JSON.stringify(i?.type??null)}))})}s(DJ,"unknownArtifactSlotTypes");function lC(e){let n=[];for(let{nodeId:t,slotKey:r,type:i}of DJ(e.nodes))n.push(pi(`nodes.${t}.artifacts.${r}.type`,{de:`[artifact/unknownType] Knoten "${t}" deklariert den Dokument-Slot \u201E${r}" mit der Art ${i} \u2014 erlaubt sind ${na.join(", ")}.`,en:`[artifact/unknownType] Node "${t}" declares the document slot "${r}" with the type ${i} \u2014 allowed are ${na.join(", ")}.`}));for(let[t,r]of rd(e.nodes))for(let i of r.slice(1))n.push(pi(`nodes.${i.nodeId}.artifacts`,{de:`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${t}", 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 "${t}", which "${r[0].nodeId}" already declares \u2014 every slot key belongs to exactly one node.`}));return n}s(lC,"checkArtifactSlotKeys");function FJ(e,n,t,r=rd(e.nodes)){let i=r.get(n)?.[0]?.nodeId;return i===void 0?{reason:"unknown"}:Ys(e,i,t)?null:{reason:"notBefore",owner:i}}s(FJ,"slotLinkRefusal");function dC(e){if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let t of e){let r=typeof t=="object"&&t!==null?t:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)n.push({kind:"artifact",key:r.key});else if(r.kind==="field"&&i==="address,kind")n.push({kind:"field",address:r.address});else return null}return n}s(dC,"authoredRefs");function cC(e){let n=[],t=rd(e.nodes);for(let r of e.nodes)for(let i of aC(r)){if(i.documents===void 0)continue;let o=typeof i.key=="string"?i.key:"?",a=`nodes.${r.id}.tasks.${o}.documents`,l={de:`Task "${o}" (Knoten "${r.id}")`,en:`Task "${o}" (node "${r.id}")`},d=dC(i.documents);if(d===null){n.push(pi(a,{de:`[workItems/documentsInvalid] 'documents' auf ${l.de} muss eine nicht leere Liste von { kind: 'artifact', key } (Dokument-Slot eines Knotens) oder { kind: 'field', address } (Dateifeld eines Formulars) sein, erhalten ${JSON.stringify(i.documents)} \u2014 ein { kind: 'document', address } schreibt \`plexus-cli offer upgrade\` auf den Slot um.`,en:`[workItems/documentsInvalid] 'documents' on ${l.en} must be a non-empty list of { kind: 'artifact', key } (document slot of a node) or { kind: 'field', address } (file field of a form), got ${JSON.stringify(i.documents)} \u2014 \`plexus-cli offer upgrade\` rewrites a { kind: 'document', address } onto its slot.`}));continue}let c=new Set;for(let u of d){if(u.kind!=="artifact"&&!we(u.address))continue;let p=u.kind==="artifact"?fk(u):fk({kind:"field",address:u.address});if(c.has(p)&&n.push(pi(a,{de:`[workItems/documentsDuplicate] ${l.de} verweist zweimal auf ${p}.`,en:`[workItems/documentsDuplicate] ${l.en} refers to ${p} twice.`})),c.add(p),u.kind==="artifact"){let h=FJ(e,u.key,r.id,t);h?.reason==="unknown"?n.push(pi(a,{de:`[workItems/documentsUnknownArtifact] ${l.de} verweist auf das Dokument "${u.key}", aber kein Knoten deklariert einen solchen Slot.`,en:`[workItems/documentsUnknownArtifact] ${l.en} refers to the document "${u.key}", but no node declares such a slot.`})):h?.reason==="notBefore"&&n.push(pi(a,{de:`[workItems/documentsNotBefore] ${l.de} verweist auf das Dokument "${u.key}" des Knotens "${h.owner}", der nicht auf jedem Weg vor "${r.id}" liegt \u2014 auf einem Weg an ihm vorbei g\xE4be es das Dokument nie.`,en:`[workItems/documentsNotBefore] ${l.en} refers to the document "${u.key}" of node "${h.owner}", which does not lie on every path before "${r.id}" \u2014 on a path around it the document would never exist.`}))}u.kind==="field"&&!un(u.address)&&n.push(pi(a,{de:`[workItems/documentsInvalid] ${l.de}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${je(e,u.address,"de")}.`,en:`[workItems/documentsInvalid] ${l.en}: a field document names a field of a form ($node.<form>.admission.<field>), not ${je(e,u.address,"en")}.`}))}}return n}s(cC,"checkTaskDocuments");function uC(e,n){let t=[];for(let r of e.nodes)for(let i of aC(r)){let o=dC(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"||!un(d.address))continue;let c=Ur(n,d.address);if(c==null)continue;let u={de:je(e,d.address,"de"),en:je(e,d.address,"en")},p=Js("taskDocument",Hs(c));if(p==="repeated"){t.push(pi(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"&&t.push(pi(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 t}s(uC,"checkTaskDocumentFields");var mk=["form","artifact","field"],ha=["coverLetter","contract"],fC=/^[A-Za-z0-9_.-]+$/;function LJ(e){return ha.includes(e)}s(LJ,"isArtifactPart");function ma(e){return ae("INVALID",{de:`Ansichts-Adresse "${e}" ist ung\xFCltig \u2014 erwartet form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${ha.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`View address "${e}" is invalid \u2014 expected form:<form node>#<view>, artifact:<slot>[#${ha.join("|")}] or field:$node.<form>.admission.<field>.`})}s(ma,"invalid");function hk(e){let n=e.indexOf(":");if(n===-1)return ma(e);let t=e.slice(0,n),r=e.slice(n+1);if(t==="field"){let l=ti(r);return l===null?ma(e):{kind:t,address:l}}let i=r.indexOf("#"),o=i===-1?r:r.slice(0,i),a=i===-1?null:r.slice(i+1);return fC.test(o)?t==="form"?a!==null&&fC.test(a)?{kind:t,form:o,view:a}:ma(e):t==="artifact"?a===null?{kind:t,slot:o}:LJ(a)?{kind:t,slot:o,part:a}:ma(e):ma(e):ma(e)}s(hk,"parseViewAddress");function pC(e){let n=qJ(e);if(n===null)return null;let t=MJ(n);return t!==null&&JSON.stringify(pk(t))===JSON.stringify(pk(e))?t:null}s(pC,"viewAddressOf");function MJ(e){try{return hk(e)}catch{return null}}s(MJ,"tryParseViewAddress");function qJ(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.kind==="form"&&typeof n.form=="string"&&typeof n.view=="string")return`form:${n.form}#${n.view}`;if(n.kind==="artifact"&&typeof n.slot=="string")return n.part===void 0?`artifact:${n.slot}`:typeof n.part=="string"?`artifact:${n.slot}#${n.part}`:null;if(n.kind==="field"&&n.address!==null&&typeof n.address=="object"){let t=n.address;return typeof t.scope!="string"||typeof t.key!="string"?null:`field:${de(t)}`}return null}s(qJ,"spellingOf");function pk(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([n],[t])=>n<t?-1:n>t?1:0).map(([n,t])=>[n,pk(t)]))}s(pk,"canonical");function mC(e){switch(e.kind){case"form":return`form:${e.form}#${e.view}`;case"artifact":return e.part===void 0?`artifact:${e.slot}`:`artifact:${e.slot}#${e.part}`;case"field":return`field:${de(e.address)}`}}s(mC,"formatViewAddress");var gk=["form","documents"],KJ=/^[a-z][a-zA-Z0-9_-]*$/;function jJ(e){let n=new Map,t=s(r=>{for(let i of[...r.fields,...(r.groups??[]).flatMap(o=>o.fields)])n.set(i.key,i.type==="docRef"?"document":"other");for(let i of r.repeated??[]){n.set(i.key,"other");for(let o of i.itemTemplate)n.set(`${i.key}[].${o.key}`,o.type==="docRef"?"row":"other")}r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(jJ,"fieldPlaces");function hC(e,n,t){let r=[],i=new Set;return e.forEach((o,a)=>{if(typeof o!="string"||!KJ.test(o)){r.push({severity:"error",path:`${t(a)}.key`,code:"view.invalid-key",message:{de:`${n.de}: '${String(o)}' ist kein g\xFCltiger Schl\xFCssel (Kleinbuchstabe am Anfang, dann Buchstaben, Ziffern, - oder _).`,en:`${n.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:`${t(a)}.key`,code:"view.duplicate-key",message:{de:`${n.de}: Der Schl\xFCssel '${o}' kommt doppelt vor.`,en:`${n.en}: the key '${o}' occurs twice.`}}),i.add(o)}),r}s(hC,"keyIssues");function VJ(e,n,t){return e==="document"?null:e===void 0?{severity:"error",path:t,code:"view.unknown-field",message:{de:`Ansicht: Das Formular hat kein Feld '${n}'.`,en:`View: the form has no field '${n}'.`}}:e==="row"?{severity:"error",path:t,code:"view.field-in-row",message:{de:`Ansicht: Das Dateifeld '${n}' liegt in einem wiederholten Block und kann nicht einzeln genannt werden.`,en:`View: the file field '${n}' sits in a repeated block and cannot be named on its own.`}}:{severity:"error",path:t,code:"view.not-a-document",message:{de:`Ansicht: Das Feld '${n}' enth\xE4lt keine Datei.`,en:`View: the field '${n}' holds no file.`}}}s(VJ,"fieldIssue");function BJ(e,n,t){let r=[];gk.includes(e.key)&&r.push({severity:"error",path:`${n}.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:`${n}.groups`,code:"view.empty",message:{de:`Ansicht '${e.key}' hat keine Gruppen.`,en:`View '${e.key}' has no groups.`}}),r.push(...hC(i.map(a=>a.key),{de:`Gruppe der Ansicht '${e.key}'`,en:`Group of view '${e.key}'`},a=>`${n}.groups[${a}]`));let o=new Set;return i.forEach((a,l)=>{let d=`${n}.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=VJ(t.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(BJ,"viewIssues");function UJ(e){if(!Array.isArray(e))return"views";for(let[n,t]of e.entries()){let r=t?.groups;if(!Array.isArray(r))return`views[${n}].groups`;for(let[i,o]of r.entries()){let a=o?.fields;if(!Array.isArray(a)||a.some(l=>typeof l!="string"))return`views[${n}].groups[${i}].fields`}}return null}s(UJ,"malformedAt");function gC(e){let n=e.views;if(n===void 0)return[];let t=UJ(n);if(t!==null)return[{severity:"error",path:t,code:"view.malformed",message:{de:`${t} 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:`${t} 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=jJ(e);return[...hC(n.map(i=>i.key),{de:"Ansicht",en:"View"},i=>`views[${i}]`),...n.flatMap((i,o)=>BJ(i,`views[${o}]`,r))]}s(gC,"formViewIssues");function ga(e,n){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:n,severity:"error"}}s(ga,"issue");function yC(e,n,t,r,i){let o=pC(e);if(o===null)return[ga(n,{de:`[view/invalid] 'view' auf ${t.de} ist keine Ansichts-Adresse \u2014 erwartet { kind: ${mk.join(" | ")}, \u2026 }: form:<Formularknoten>#<Ansicht>, artifact:<Slot>[#${ha.join("|")}] oder field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] 'view' on ${t.en} is no view address \u2014 expected { kind: ${mk.join(" | ")}, \u2026 }: form:<form node>#<view>, artifact:<slot>[#${ha.join("|")}] or field:$node.<form>.admission.<field>.`})];let a=mC(o);switch(o.kind){case"artifact":return r.has(o.slot)?[]:[ga(n,{de:`[view/unknownSlot] ${t.de} nennt "${a}", aber kein Knoten dieses Graphen hat den Dokument-Slot "${o.slot}".`,en:`[view/unknownSlot] ${t.en} names "${a}", but no node of this graph has the document slot "${o.slot}".`})];case"form":case"field":{let l=o.kind==="form"?o.form:o.address.scope==="node"?o.address.owner:null;if(l===null)return[ga(n,{de:`[view/invalid] ${t.de} nennt "${a}" \u2014 ein Dateifeld liegt in einem Formular: field:$node.<Formular>.admission.<Feld>.`,en:`[view/invalid] ${t.en} names "${a}" \u2014 a file field lives in a form: field:$node.<form>.admission.<field>.`})];let d=i?.formViewKeysByFormNode;if(d===void 0)return[];let c=d.get(l);return c===void 0?[ga(n,{de:`[view/unknownForm] ${t.de} nennt "${a}", aber kein Formularknoten hei\xDFt so.`,en:`[view/unknownForm] ${t.en} names "${a}", but no form node has that id.`})]:o.kind==="field"?[]:c.has(o.view)||gk.includes(o.view)?[]:[ga(n,{de:`[view/unknownView] ${t.de} nennt "${a}", aber das Formular "${o.form}" hat keine Ansicht "${o.view}".`,en:`[view/unknownView] ${t.en} names "${a}", but the form "${o.form}" has no view "${o.view}".`})]}}}s(yC,"viewIssues");function wC(e,n){let t=[],r=new Set(rd(e.nodes).keys());for(let i of e.nodes){if(i.view!==void 0){let o={de:`Knoten "${i.id}"`,en:`node "${i.id}"`};i.type!=="decision"?t.push(ga(`nodes.${i.id}.view`,{de:`[view/invalid] ${o.de}: 'view' am Knoten gilt nur f\xFCr eine Entscheidung; eine Aufgabe tr\xE4gt ihre eigene.`,en:`[view/invalid] ${o.en}: 'view' on a node applies to a decision only; a task carries its own.`})):t.push(...yC(i.view,`nodes.${i.id}.view`,o,r,n))}for(let o of Array.isArray(i.tasks)?i.tasks:[]){if(o.view===void 0)continue;let a=String(o.key);t.push(...yC(o.view,`nodes.${i.id}.tasks.${a}.view`,{de:`Task "${a}" (Knoten "${i.id}")`,en:`Task "${a}" (node "${i.id}")`},r,n))}}return t}s(wC,"checkTaskViews");var Lt="traeger",kC={de:"Tr\xE4ger",en:"Provider"};function ya(e){let n=e.inputs?.[Lt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(ya,"traegerKeyOfNode");var Kp={name:"input.traeger.name",address:"input.traeger.anschrift"},Bwe=Object.values(Kp);var bC="governedDocument",qo="prepareDocument",id="prepareDocument:revision",Ar="releaseApproval",Ko="documentResponse",Yi="coverLetterResponse",jp="confirmCoverLetter",Vp="requestCoverLetterRevision",wa="coverLetterConfirmation",Yr="responseCheck",Bp="returnSigned";var vC="requestApproval";var xC="issueDocument",SC="correctInPlace",AC="rescindAndReissue",Up="requestChange";var ka="releaseArtifact",ht="signingRecovery",Gp="resendESignature",jo="switchToPaper";var od=new Set([qo,id]),EC=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingCoverLetter","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],zp=["upload","resolver","template","none"],Vo=1,Bo=366,mi="responseDueInDays";function Uo(e){let n=e.inputs?.[wa];return n?.kind==="literal"&&n.value===!0}s(Uo,"coverLetterConfirmationOf");function sd(e){let n=e.inputs?.[mi];return n?.kind==="literal"&&ad(n.value)?n.value:void 0}s(sd,"responseDueInDaysForVocabulary");function ad(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Vo&&e<=Bo}s(ad,"isValidResponseDueInDays");var Wp=["generatedAt","responseDueInDays","countersignature"],Go=["release","none"],Yp=["confirm","signedUpload","signedUploadChecked","eSignature"];var GJ={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"}}},TC={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"}}},$C={...TC,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},zJ={...$C,kind:"eSignature",issuesBy:"provider"},hi={confirm:GJ,signedUpload:TC,signedUploadChecked:$C,eSignature:zJ};function gi(e){let n=e.responseStrategy;if(typeof n=="string"&&n in hi)return hi[n];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(gi,"responseStrategyOf");function Hp(e){if(e.type!==bC||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in hi?hi[n].acceptEvent==="contractEvent":!1}s(Hp,"isFamilySignedContractNode");function va(e){return e.label}s(va,"governedDocTitle");function yk(e){return e.approval==="release"?vC:xC}s(yk,"submitActionId");function RC(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[yk(e)],gatesNode:!0,advancesNode:!0}}s(RC,"producerTemplate");function WJ(e){return e.titles?.respond??e.label}s(WJ,"responseTitle");var ba={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Jp(e){let n=gi(e),t=[];if(e.production!=="none"&&t.push(RC(e,qo,e.titles?.prepare??ba),RC(e,id,e.titles?.revise??ba)),e.approval==="release"&&t.push({key:Ar,recipient:"internal",title:e.titles?.approve??ba,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Ko,recipient:"external",title:WJ(e),unlocks:n.producesResponseArtifact?[n.checksReturn?Bp:n.acceptOutcomeId,n.declineOutcomeId,Up]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...sd(e)!==void 0?{dueInDays:sd(e)}:{}}),Uo(e)){let r=va(e);t.push({key:Yi,recipient:"external",title:{de:`${r.de}: Angebot best\xE4tigen`,en:`${r.en}: confirm offer`},unlocks:[jp,Vp,n.declineOutcomeId],advancesNode:!0,...sd(e)!==void 0?{dueInDays:sd(e)}:{}})}if(n.checksReturn&&t.push({key:Yr,recipient:"internal",title:e.titles?.check??ba,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=va(e);t.push({key:ht,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Gp,jo],gatesNode:!1,advancesNode:!1})}return t}s(Jp,"governedDocIntrinsicTemplates");function YJ(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(YJ,"governedDocSlot");function Qp(e){return YJ(e).key}s(Qp,"governedDocSlotKey");var tr="processFooter";var Zp="countersign",wk="countersign",IC="countersigned",OC="countersigning",_C="countersigned";var PC={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},ld=["scan","eSignature"],Xp="service_provider:1",NC=["countersigning","awaitingSignature","signatureStalled","done"],CC={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function DC(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(DC,"traegerSignatoryMissingReason");function rr(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(rr,"issue");function em(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&we(r)&&r.scope==="node"&&r.owner===n})}s(em,"countersignersOf");function dd(e){return e.signing==="eSignature"}s(dd,"isElectronic");function HJ(e,n){if(n===void 0||n.sendable||!dd(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[rr(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(HJ,"countersignProviderIssues");function JJ(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return Hp(r)||i.push("sourceNotCheckedContract"),em(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(JJ,"countersignContractRefusals");function FC(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(FC,"validDueInDays");function QJ(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!ld.includes(o))return[rr(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?.[ht];if(!dd(e))return a===void 0?[]:[rr(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 a===void 0&&l.push(rr(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(...ZJ(e,n,t),...XJ(e,n,t),...HJ(e,t?.signingProvider)),l}s(QJ,"signingIssues");function MC(e,n){let t=e.contract;if(!(!we(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(MC,"contractNodeOf");function ZJ(e,n,t){let r=MC(e,n),i=r===void 0?null:ya(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[rr(e,"signing",DC(o.name))]}s(ZJ,"traegerSignatoryIssues");function XJ(e,n,t){let r=MC(e,n);if(r===void 0)return[];let i=t?.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(rr(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(Xp)||l.push(rr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${Xp}/ \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:${Xp}/ \u2014 the provider would find no signature field for the school.`}));return l}s(XJ,"traegerAnchorIssues");var kk=100;async function e6(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(kk+1);t.length>kk&&F(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${kk} rows`);let r=t.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)===ht)?"signatureStalled":r.some(o=>i(o)===Zp)?"countersigning":dd(n.node)?"awaitingSignature":"done"}s(e6,"countersignCurrentState");var LC={[OC]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:en(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("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."))}},qC={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:IC,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:LC,progressEvents:qn(LC),notificationEvents:s(()=>[{id:_C,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:wk,kind:"internal",label:PC,surface:tr,availableIn:["countersigning"]},...dd(e)?[{id:jo,kind:"internal",surface:tr,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:Zp,recipient:"internal",title:e.titles?.countersign??ba,unlocks:[wk],advancesNode:!0,...FC(e)!==void 0?{dueInDays:FC(e)}:{}},...dd(e)?[{key:ht,recipient:"internal",title:CC,unlocks:[jo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:NC,currentState:e6,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id;e.assign?.[Zp]===void 0&&r.push(rr(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.`})),Ci(e.titles?.countersign)||r.push(rr(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(rr(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(...QJ(e,n,t));let d=e.contract;if(!we(d))return r;let c=JJ(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(p=>d.scope==="node"&&p.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(rr(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=em(n,u.id).filter(h=>h.id!==e.id);r.push(rr(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 n6(e){return Hp(e)?ya(e):null}s(n6,"traegerSignerOf");var t6=s(e=>e.type==="end"&&No(e)==="approved","isApprovedEnd");function KC(e){let n=[];for(let t of e.nodes){let r=n6(t);if(r===null)continue;let i=em(e,t.id).map(u=>u.id),o=H_(e,t.id,new Set(i),t6);if(o===null)continue;let a=t.label?.de||t.id,l=t.label?.en||t.id,d={de:`Einen Knoten \u201EUnterschrift (intern)\u201C (countersign) mit contract: $node.${t.id}.contract auf jeden Weg zu einem Ende mit Ergebnis approved setzen.`,en:`Place an "Internal signature" node (countersign) with contract: $node.${t.id}.contract on every path to an end with outcome approved.`},c=i.length===0?{de:`[countersign/missingForContract] \u201E${a}\u201C (${t.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}" (${t.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 (${t.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}" (${t.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}`};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}`,reason:c,severity:"error"})}return n}s(KC,"checkCountersignCoverage");var r6=[{key:"blocks",why:{de:"sie h\xE4lt nichts zur\xFCck, sie ist mit dem Ausl\xF6sen erledigt",en:"it holds nothing back, it is done with the press"}},{key:"when",why:{de:"sie entsteht bei jedem Ausl\xF6sen",en:"it is created on every press"}},{key:"optional",why:{de:"wer ausl\xF6st, beantwortet sie immer",en:"whoever presses always answers it"}},{key:"familyRequest",why:{de:"sie fragt nicht die Familie",en:"it does not ask the family"}},{key:"feedback",why:{de:"sie beantwortet die ausl\xF6sende Person, nicht ein Link",en:"the presser answers it, not a link"}},{key:"completableIf",why:{de:"sie wird beim Ausl\xF6sen erledigt, eine Vorbedingung w\xFCrde jedes Ausl\xF6sen ablehnen",en:"it is completed at the press, a precondition would refuse every press"}},{key:"locksEvidence",why:{de:"eine offene Korrektur w\xFCrde jedes Ausl\xF6sen ablehnen",en:"an open correction would refuse every press"}}];function jC(e){let{nodeId:n,bindingKey:t,binding:r}=e,i=[],o=`nodes.${n}.optionalActions.${t}.input`,a=s((u,p=o)=>{i.push({layer:"GRAPH",kind:"nodeRule",path:p,severity:"error",reason:{de:`[optionalAction/input] Optionale Aktion "${t}" auf Knoten "${n}": ${u.de}`,en:`[optionalAction/input] Optional action "${t}" on node "${n}": ${u.en}`}})},"push");if(r.input===void 0)return r.submitLabel!==void 0&&a({de:"'submitLabel' beschriftet das Absenden des Eingabedialogs \u2014 ohne 'input' \xF6ffnet das Ausl\xF6sen keinen Dialog.",en:"'submitLabel' names the input dialog's submit button \u2014 without 'input' the press opens no dialog."},`nodes.${n}.optionalActions.${t}.submitLabel`),i;let l=r.input;if(typeof l!="string"||l.trim().length===0)return a({de:"'input' muss der Schl\xFCssel einer ihrer Aufgaben sein.",en:"'input' must be the key of one of its tasks."}),i;let d=Array.isArray(r.tasks)?r.tasks:[];if(!d.includes(l))return a({de:`Die Eingabe "${l}" ist keine ihrer Aufgaben ('tasks') \u2014 die Eingabe geh\xF6rt zur Runde der Aktion.`,en:`The input "${l}" is none of its tasks ('tasks') \u2014 the input belongs to the action's round.`}),i;let c=s(u=>{let p=e.templates.find(h=>h.key===u);return p!==void 0&&p.optional===void 0&&p.blocks===void 0},"holdsNode");d.some(u=>u!==l&&c(u))||a({de:`Neben der Eingabe "${l}" hat die Aktion keine Aufgabe, die den Schritt zur\xFCckh\xE4lt (weder 'optional' noch hinter 'blocks') \u2014 die Runde w\xE4re mit dem Ausl\xF6sen schon erledigt.`,en:`Besides the input "${l}" the action has no task that holds the step (neither 'optional' nor behind 'blocks') \u2014 the round would be done with the press.`});for(let u of i6({nodeId:n,binding:r,templates:e.templates,input:l}))a(u);return i}s(jC,"optionalActionInputIssues");function i6(e){let{nodeId:n,binding:t,templates:r,input:i}=e,o=r.find(u=>u.key===i);if(o===void 0)return[];let a=[];o.result?.kind!=="record"&&a.push({de:`Die Eingabe "${i}" braucht ein Ergebnis der Art 'record' \u2014 nur dessen Werte lesen die anderen Aufgaben der Runde.`,en:`The input "${i}" needs a result of kind 'record' \u2014 only its values are read by the round's other tasks.`});let l=o.assign?.group;typeof t.trigger!="string"?a.push({de:"Mit einer Eingabe braucht die Aktion ein 'trigger'-Team \u2014 die Eingabe ist eine Aufgabe dieses Teams.",en:"With an input the action needs a 'trigger' team \u2014 the input is a task of that team."}):l!==void 0&&l!==t.trigger&&a.push({de:`Die Eingabe "${i}" geh\xF6rt dem Team "${String(l)}", ausgel\xF6st wird die Aktion vom Team "${t.trigger}" \u2014 wer ausl\xF6st, beantwortet die Eingabe, also ist es dasselbe Team.`,en:`The input "${i}" belongs to the team "${String(l)}", the action is pressed by the team "${t.trigger}" \u2014 whoever presses answers the input, so it is the same team.`});let d=o.result,c=d?.fields;for(let u of Array.isArray(c)?c:[])u.evidence===!0&&a.push({de:`Das Feld "${String(u.key)}" der Eingabe "${i}" verlangt eine Datei ('evidence') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(u.key)}" of the input "${i}" demands a file ('evidence') \u2014 the press carries values only.`}),u.suggest!==void 0&&a.push({de:`Das Feld "${String(u.key)}" der Eingabe "${i}" tr\xE4gt einen Vorschlag ('suggest') \u2014 eine Abweichung verlangt eine Begr\xFCndung, das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The field "${String(u.key)}" of the input "${i}" carries a suggestion ('suggest') \u2014 a departure demands a reason, the press carries values only.`});d?.textRequired===!0&&a.push({de:`Die Eingabe "${i}" verlangt einen Text ('textRequired') \u2014 das Ausl\xF6sen tr\xE4gt nur Werte.`,en:`The input "${i}" demands a text ('textRequired') \u2014 the press carries values only.`});for(let{key:u,why:p}of r6)o[u]!==void 0&&a.push({de:`Die Eingabe "${i}" tr\xE4gt '${u}' \u2014 ${p.de}.`,en:`The input "${i}" carries '${u}' \u2014 ${p.en}.`});for(let u of r){let p=u.blocks;p?.templateKey!==i||p.node!==void 0&&p.node!==n||a.push({de:`"${String(u.key)}" h\xE4lt die Eingabe "${i}" per 'blocks' zur\xFCck \u2014 sie ist beim Anlegen der Runde schon erledigt, es gibt nichts zur\xFCckzuhalten.`,en:`"${String(u.key)}" holds the input "${i}" back through 'blocks' \u2014 it is already done when the round is created, there is nothing to hold back.`})}return a}s(i6,"optionalActionInputRefusals");function o6(e){let n="error",t=new Map;for(let a of nr(e.nodes)){let l=t.get(a.source)??[];l.push({id:a.id,target:a.target}),t.set(a.source,l)}let r=[],i=new Set,o=Np(e.nodes.map(a=>a.id),a=>(t.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:n}));return r}s(o6,"checkAcyclic");function s6(e){let n=[],t=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))t.has(l.to)||n.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))&&n.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 n}s(s6,"checkNextTargets");function a6(e){let n=[];for(let t of e.nodes){let r=t.next;if(!r)continue;let i=Cw(t),o=new Set(i?i.map(a=>a.id):[ta]);for(let a of Object.keys(r))o.has(a)||n.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${t.id}.next.${a}`,reason:{de:`${t.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:`${t.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 n}s(a6,"checkNextOutcomesKnown");function l6(e){let n=[],t=new Set(nr(e.nodes).map(o=>o.target)),r=e.nodes.filter(o=>!t.has(o.id));return r.length===0?n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein Start-Knoten",en:"No start node"},severity:"error"}):r.length>1&&n.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&&n.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:{de:"Kein End-Knoten",en:"No end node"},severity:"warning"}),n}s(l6,"checkStartEnd");function d6(e){let n=new Map;for(let r of nr(e.nodes))n.set(r.source,(n.get(r.source)??0)+1);let t=[];for(let r of e.nodes)r.type!=="end"&&(n.get(r.id)??0)===0&&t.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 t}s(d6,"checkNoOutgoingEdge");function c6(e){return e.nodes.filter(n=>!Oy(n.id)).map(n=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.id`,reason:{de:`[graph/nodeIdFormat] Knoten "${n.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${kr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,en:`[graph/nodeIdFormat] Node "${n.id}": a node id is an identifier without a dot (${kr.source}), e.g. "reviewSubmitted". Export a bundle from before the change again.`},severity:"error"}))}s(c6,"checkNodeIdFormat");function u6(e){let n=new Set(e.nodes.map(r=>r.id)),t=[];for(let r of nr(e.nodes))n.has(r.source)||t.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"}),n.has(r.target)||t.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 t}s(u6,"checkEdgeEndpoints");function f6(e){let n=[];for(let t of e.nodes)for(let r of t.tasks??[]){let i=r.result;i===null||typeof i!="object"||!(yp in i)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.tasks.${r.key}.result.${yp}`,reason:{de:`[graph/retiredField] Aufgabe "${r.key}": \`primaryHostTeams\` hei\xDFt jetzt \`primaryParticipantTeams\` \u2014 der alte Name wird nicht mehr gelesen, die Teilnehmer-Auswahl zeigt die Teams nicht oben. Bitte umbenennen.`,en:`[graph/retiredField] Task "${r.key}": \`primaryHostTeams\` is now called \`primaryParticipantTeams\` \u2014 the old name is no longer read, so the participant picker does not list the teams first. Please rename it.`},severity:"warning"})}return n}s(f6,"checkRetiredFieldWarnings");var p6=new Set(["countersignature"]);function m6(e){let n=[],t=s((o,a)=>{n.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&&t("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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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&&t(`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(cw[o.type]??{}))c in a&&t(`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:[]){if(c===null||typeof c!="object")continue;let u=String(c.key),p=c.assign;p!==null&&typeof p=="object"&&"userId"in p&&t(`nodes.${o.id}.tasks.${u}.assign.userId`,{de:`Aufgabe "${u}" an ${l.de}: \`assign.userId\` gibt es nicht mehr \u2014 eine Aufgabe nennt ihr Team (\`assign.group\`), nie eine feste Person.`,en:`Task "${u}" on ${l.en}: \`assign.userId\` no longer exists \u2014 a task names its team (\`assign.group\`), never a fixed person.`});for(let[h,w]of Object.entries(uk))h in c&&t(`nodes.${o.id}.tasks.${u}.${h}`,w(u,l))}for(let c of uw[o.type]??[])c in a&&t(`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(p_[o.type]??{}))c in a&&t(`nodes.${o.id}.${c}`,{de:`${l.de}: ${u.de}`,en:`${l.en}: ${u.en}`});a.adoptForm===!0&&t(`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"&&p6.has(u)&&t(`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 n}s(m6,"checkRetiredDataFields");function xa(e,n){return n?.wiring&&n.layout?{wiring:n.wiring,layout:n.layout}:null}s(xa,"resolveLayoutContext");function h6(e,n){let t=xa(e,n);if(!t)return e.nodes.some(o=>(Je(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 ${n?.wiring?"vorhanden":"fehlt"}, Layout ${n?.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 ${n?.wiring?"present":"missing"}, layout ${n?.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=Je(i)?.progressEvents;if(a)for(let l of a){let d=Qs(t.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 '${t.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 '${t.layout.id}') \u2014 the engine throws when mirroring`},severity:"error"});continue}let c;try{c=fp(t.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 '${t.layout.id}'`,en:`${i.type} '${i.id}': event '${l}' points to unknown bus '${d.bus}' in layout '${t.layout.id}'`},severity:"error"});continue}Bl(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(h6,"checkProgressEventMappings");function g6(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.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),Bl(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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(g6,"checkProgressBoardCoverage");function y6(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)if(!(!i.boards||i.boards.length===0))for(let o of i.boards)for(let a of Ye){let l=new Map;for(let d of o.columns){if(!Ci(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.${t.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(y6,"checkProgressBoardDistinctLabels");function w6(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses)for(let o of i.states){let a=pp(i,o.id);o.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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(w6,"checkProgressTerminalSemantics");function k6(e,n){let t=xa(e,n);if(!t)return[];let r=[];for(let i of t.layout.buses){let o=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Bl(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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??[])Bl(i,a)?o.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${t.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.${t.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.${t.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(k6,"checkProgressSeatStates");var nm={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 b6(e){return e==="both"?{de:`${nm.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:`${nm.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:`${nm.de}, oder den Zustand in die Spalte des Nachfolgers legen.`,en:`${nm.en}, or move the state into the successor's column.`}}s(b6,"passThroughRemedy");function v6(e,n){let t=xa(e,n);if(!t)return[];let{layout:r,wiring:i}=t;if(!r.buses.some(b=>b.key==="process"))return[];let o=tP(r);if(!o)return[];let a=new Map(e.nodes.map(b=>[b.id,b])),l=s(b=>Je(b).progressEvents??[],"eventsOf"),d=s(b=>Object.values(b.next??{}).map(E=>E.to),"routesOf"),c=s((b,E)=>{let T=a.get(b);if(!T||E.has(b))return null;if(l(T).length>0)return[T];if(BC[T.type]!==!1)return null;let R=d(T);if(R.length===0)return null;let D=[];for(let L of R){let _=c(L,new Set([...E,b]));if(!_)return null;D.push(..._)}return D},"firstProgressNodes"),u=s((b,E)=>{let T=[];for(let R of l(b)){let D=Qs(i,b,R);if(!D||D.bus!==E.bus||D.state===E.state)return null;T.push(D.state)}return[...new Set(T)].join("' / '")},"overwrites"),p=s((b,E)=>{let T=d(b);if(T.length===0)return null;let R=[];for(let D of T){let L=c(D,new Set([b.id]));if(!L)return null;for(let _ of L){let v=u(_,E);if(v===null)return null;R.push({de:`'${_.id}' (${_.type}) mit '${v}'`,en:`'${_.id}' (${_.type}) with '${v}'`})}}return[...new Map(R.map(D=>[D.de,D])).values()]},"submitOverwrittenBy"),h=new Map;for(let b of e.nodes)for(let E of l(b)){let T=Qs(i,b,E);if(!T||T.bus!=="process")continue;let R=b.type==="form"&&E===Rf?p(b,T):null,D=R?{de:`'${b.id}'.${E} erreicht ihn, und ${R.map(L=>L.de).join(", ")} \xFCberschreibt ihn in derselben Transaktion`,en:`'${b.id}'.${E} reaches it, and ${R.map(L=>L.en).join(", ")} overwrites it in the same transaction`}:null;h.set(T.state,[...h.get(T.state)??[],D])}let w=fp(r,"process"),k=new Map;for(let[b,E]of h){if(!E.every(R=>R!==null))continue;let T=[...new Map(E.map(R=>[R.de,R])).values()];k.set(b,{de:T.map(R=>R.de).join("; "),en:T.map(R=>R.en).join("; ")})}let y=[];for(let b of o.columns){if(b.states.length===0||!b.states.every(R=>k.has(R)))continue;let E=b.states.map(R=>{let D=w.holdsSeat?.includes(R)===!0,L=k.get(R);return{de:`Zustand '${R}'${D?" (steht in holdsSeat, belegt aber nie einen Platz)":""}: ${L.de}`,en:`State '${R}'${D?" (is in holdsSeat, but never takes a seat)":""}: ${L.en}`}}),T=b6(o.audience);y.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${o.id}.columns.${b.id}`,reason:{de:`[progress/passThroughState] Spalte \u201E${b.label.de}" ('${b.id}', Board '${o.id}') bleibt immer leer \u2014 ${E.map(R=>R.de).join("; ")}. ${T.de}`,en:`[progress/passThroughState] Column "${b.label.en}" ('${b.id}', board '${o.id}') always stays empty \u2014 ${E.map(R=>R.en).join("; ")}. ${T.en}`},severity:"warning"})}return y}s(v6,"checkProgressPassThroughColumns");function x6(e){let n=["workItems","workitems","work_items","taskTemplates"],t=[];for(let r of e.nodes){let i=r;for(let o of n){let a=i[o];a!=null&&t.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 t}s(x6,"checkMisnamedTasksKey");function S6(e){let n=[];for(let t of e.nodes){let r=t,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)&&n.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=Je(t),d=new Map((typeof l.workItemTemplates=="function"?l.workItemTemplates(t):[]).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||!Jl.has(p)){n.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: ${[...Jl].join(", ")}.`,en:`[workItems/invalidKind] Task "${u}" on node "${r.id}" has kind ${JSON.stringify(c.kind)}; composable kinds are: ${[...Jl].join(", ")}.`},severity:"error"});continue}p==="task"&&c.gatesNode!==void 0&&n.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:tC(e,r.id,h.node);if(h!==void 0&&w===null)n.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,b=w.node.id,E=y?o:w.composedKeys,T=y?d:w.intrinsicByKey,R=w.node.assign??{};p==="approval"&&n.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 D=h.templateKey,L=[...new Set([...E,...T.keys()])].filter(v=>!y||v!==u).join(", "),_={de:L||"keine",en:L||"none"};if(typeof D!="string"||y&&D===u||!E.has(D)&&!T.has(D))n.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(D)} auf Knoten "${b}"; zul\xE4ssige Ziele: ${_.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(D)} on node "${b}"; allowed targets: ${_.en}.`},severity:"error"});else if(w.refuse(D)!==null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.blocks.templateKey`,reason:w.refuse(D),severity:"error"});else{let v=T.get(D);h.except!==void 0&&n.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"}),v!==void 0&&v.recipient!=="external"&&v.verdictResolved!==!0&&R[D]===void 0&&n.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 "${D}" (Knoten "${b}") zur\xFCck, aber der Knoten weist "${D}" keiner Gruppe zu \u2014 ohne 'assign.${D}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${D}' erg\xE4nzen oder das 'blocks' entfernen.`,en:`[workItems/blocksUnwiredTarget] Task "${u}" on node "${r.id}" holds back "${D}" (node "${b}"), but the node assigns "${D}" to no group \u2014 without 'assign.${D}' this row is never created: no team receives the held-back work, and nobody except the responsible person can do it. Either add 'assign.${D}' or remove the 'blocks'.`},severity:"error"})}}{let y=c.completableIf;if(typeof y=="string"&&y.trim().length>0){let b=y.trim().replace(/^!/,"").trim();a.has(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.completableIf`,reason:{de:`[workItems/unknownExport] completableIf "${y}" verweist auf unbekannten Node-Export "${b}"; bekannt: ${[...a].join(", ")||"keine"}.`,en:`[workItems/unknownExport] completableIf "${y}" refers to unknown node export "${b}"; known: ${[...a].join(", ")||"none"}.`},severity:"error"})}}let k=c.params;if(k?.commentRequired!==void 0&&n.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 b of y)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.tasks.${u}.${b}`,reason:{de:`[workItems/approvalOnlyField] '${b}' gilt nur f\xFCr die Art 'approval' (Task "${u}" ist '${p}').`,en:`[workItems/approvalOnlyField] '${b}' only applies to the kind 'approval' (task "${u}" is '${p}').`},severity:"error"});continue}k?.onReject!==void 0&&k.onReject!=="spawnRevision"&&n.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)&&n.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 n.push(...rC(e)),n}s(S6,"checkWorkItemTemplates");var A6=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 E6(e){let n=[];for(let t of e.nodes){let r=t,i=Je(t),o=Array.isArray(r.tasks)?r.tasks.length:0,a=i.workItemTemplates?.(t)??[];if(o+a.length>0){let b=BC[r.type];b===void 0?n.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"}):b||n.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?.(t)??[];if(l.length===0&&a.length===0)continue;let d=new Map(l.map(b=>[b.id,b]));for(let b of l)A6.has(b.id)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}`,reason:{de:`[capability/reservedActionId] Knotentyp "${r.type}" deklariert die Action "${b.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 "${b.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??[SP]);for(let b of l)if(b.availableIn!==void 0)for(let E of b.availableIn)c.has(E)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}.availableIn`,reason:{de:`[capability/unknownActionState] Action "${b.id}" auf Knotentyp "${r.type}" ist f\xFCr Zustand "${E}" deklariert \u2014 der Typ kennt nur: ${[...c].join(", ")}.`,en:`[capability/unknownActionState] Action "${b.id}" on node type "${r.type}" is declared for state "${E}" \u2014 the type only knows: ${[...c].join(", ")}.`},severity:"error"});let u=Cw(t),p=new Set(u?u.map(b=>b.id):[ta]);for(let b of l){if(b.external===void 0)continue;let E=xP(b.external.event),T={de:"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)",en:"has no label (the recipient would get an empty button)"},R=E?b.kind==="advance"?{de:`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${b.external.event}") \u2014 solche Aktionen sind "internal"`,en:`is declared as "advance", but does not resolve the node (event "${b.external.event}") \u2014 such actions are "internal"`}:b.outcome!==void 0?{de:`nennt das Outcome "${b.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${b.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`,en:`names the outcome "${b.outcome}", but does not resolve the node (event "${b.external.event}") \u2014 an outcome would claim a second, silent routing vocabulary`}:b.label===void 0?T:null:b.kind!=="advance"?{de:`ist als "${b.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`,en:`is declared as "${b.kind}" (external actions resolve the node and must be "advance")`}:b.outcome===void 0?{de:"nennt kein Outcome",en:"names no outcome"}:p.has(b.outcome)?b.label===void 0?T:null:{de:`verweist auf das unbekannte Outcome "${b.outcome}" (deklariert: ${[...p].join(", ")||"keine"})`,en:`refers to the unknown outcome "${b.outcome}" (declared: ${[...p].join(", ")||"none"})`};R!==null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}.external`,reason:{de:`[capability/externalActionNeedsOutcome] Externe Aktion "${b.id}" auf Knotentyp "${r.type}" ${R.de}.`,en:`[capability/externalActionNeedsOutcome] External action "${b.id}" on node type "${r.type}" ${R.en}.`},severity:"error"})}for(let b of a){let E=b.unlocks;if(E.length===0&&b.verdictResolved!==!0&&b.informational!==!0){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${b.key}.unlocks`,reason:{de:`[capability/emptyUnlocks] Intrinsisches Template "${b.key}" auf Knoten "${r.id}" schaltet keine Action frei (B5).`,en:`[capability/emptyUnlocks] Intrinsic template "${b.key}" on node "${r.id}" unlocks no action (B5).`},severity:"error"});continue}for(let T of E)d.get(T)===void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.workItemTemplates.${b.key}.unlocks`,reason:{de:`[capability/danglingUnlock] Template "${b.key}" auf Knoten "${r.id}" schaltet unbekannte Action "${T}" frei; deklariert: ${[...d.keys()].join(", ")||"keine"}.`,en:`[capability/danglingUnlock] Template "${b.key}" on node "${r.id}" unlocks the unknown action "${T}"; declared: ${[...d.keys()].join(", ")||"none"}.`},severity:"error"})}let h=new Set(a.map(b=>b.key));for(let b of Object.keys(r.assign??{}))h.has(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.assign.${b}`,reason:{de:`[capability/unknownAssignKey] assign-Key "${b}" auf Knoten "${r.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...h].join(", ")||"keine"}.`,en:`[capability/unknownAssignKey] assign key "${b}" on node "${r.id}" is not an intrinsic template of this node type; known: ${[...h].join(", ")||"none"}.`},severity:"error"});for(let[b,E]of Object.entries(r.assign??{})){if(E===void 0)continue;let T=`nodes.${r.id}.assign.${b}`,R={de:`Team der Vorlage "${b}" (Knoten "${r.id}")`,en:`team of the template "${b}" (node "${r.id}")`};n.push(...q_(E,T,R));for(let[D,L]of(Array.isArray(E)?E:[]).entries()){let _=L?.when;_==null||!we(_)||un(_)||n.push({layer:"GRAPH",kind:"nodeRule",path:`${T}.${D}.when`,severity:"error",reason:{de:`[assign/conditionNotFormField] ${R.de}, Zeile ${D+1}: die Bedingung nennt ${je(e,_,"de")} \u2014 ein Team wird nach einem Ja/Nein-Feld eines Formulars gew\xE4hlt ($node.<formular>.admission.<feld>).`,en:`[assign/conditionNotFormField] ${R.en}, row ${D+1}: the condition names ${je(e,_,"en")} \u2014 a team is chosen by a yes/no field of a form ($node.<form>.admission.<field>).`}})}}let w=l.filter(b=>b.teamAssignable===!0).map(b=>b.id);for(let b of Object.keys(r.actionTeams??{}))w.includes(b)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actionTeams.${b}`,reason:{de:`[capability/unknownActionTeam] Knoten "${r.id}" nennt ein Team f\xFCr "${b}", 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 "${b}", but this action cannot be given to a team here; possible: ${w.join(", ")||"none"}.`},severity:"error"});let k=new Set;for(let b of a)if(b.recipient==="external"||(r.assign??{})[b.key]!==void 0)for(let T of b.unlocks)k.add(T);let y=i.strictActionCoverage===!0;for(let b of l){if(k.has(b.id)||b.superUserOnly===!0)continue;let E=a.find(R=>R.unlocks.includes(b.id)),T=E!==void 0?{de:` Fehlt die Zuweisung assign.${E.key}?`,en:` Is the assignment assign.${E.key} missing?`}:{de:"",en:""};n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.actions.${b.id}`,reason:{de:`[capability/superUserOnly] Action "${b.id}" auf Knoten "${r.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${T.de}`,en:`[capability/superUserOnly] Action "${b.id}" on node "${r.id}" is unlocked by no wired work item \u2014 only the responsible person (super user) can perform it.${T.en}`},severity:y?"error":"warning"})}}return n}s(E6,"checkNodeCapabilityWiring");function T6(e){let n=new Set(qO()),t=[];for(let r of e.nodes)n.has(r.type)||t.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: ${[...n].join(", ")}.`,en:`[graph/unknownNodeType] Node "${r.id}" has the unknown type "${String(r.type)}". Registered types: ${[...n].join(", ")}.`},severity:"error"});return t}s(T6,"checkKnownNodeTypes");function $6(e,n){let t=[],r=s((a,l)=>{t.push({layer:"GRAPH",kind:"nodeRule",path:a,reason:l,severity:"error"})},"push"),i=YI(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(t.push(...j6(l,d)),d.length===0)continue;let c=Je(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 b=y.key,E=typeof b=="string"&&b.trim().length>0?b:void 0,T=E??"?",R=`nodes.${l.id}.optionalActions.${T}`,D=typeof y.action=="string"?y.action:void 0;if(y.when!==void 0){let L=s(_=>r(`${R}.when`,{de:`[optionalAction/when] Optionale Aktion "${T}" auf Knoten "${l.id}": ${_.de}`,en:`[optionalAction/when] Optional action "${T}" on node "${l.id}": ${_.en}`}),"conditionFinding");if(typeof y.when!="string"||y.when.trim()==="")L({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 _ of Fp(y.when,i,n))L(_)}if((D===void 0||!u.has(D))&&r(`${R}.action`,{de:`[optionalAction/kindNotDeclared] Optionale Aktion "${T}" 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 "${T}" 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(", ")}.`)}),E===void 0?r(`${R}.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(E)&&r(`${R}.key`,{de:`[optionalAction/duplicateKey] Doppelter Aktions-Key "${E}" auf Knoten "${l.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`,en:`[optionalAction/duplicateKey] Duplicate action key "${E}" on node "${l.id}" \u2014 the projected trigger actions would collide.`}),w.add(E)),o(y.label)||r(`${R}.label`,{de:`[optionalAction/missingLabel] Optionale Aktion "${T}" auf Knoten "${l.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`,en:`[optionalAction/missingLabel] Optional action "${T}" on node "${l.id}" without a label \u2014 the trigger button would be unlabeled.`}),D==="spawnTasks"){y.except!==void 0&&r(`${R}.except`,{de:`[optionalAction/exceptRetired] Optionale Aktion "${T}" 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 "${T}" 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'.`}),t.push(...jC({nodeId:l.id,bindingKey:T,binding:y,templates:p}));let L=Array.isArray(y.tasks)?y.tasks:void 0;if(L===void 0||L.length===0)r(`${R}.tasks`,{de:`[optionalAction/tasksEmpty] Optionale Aktion "${T}" auf Knoten "${l.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`,en:`[optionalAction/tasksEmpty] Optional action "${T}" on node "${l.id}" references no task templates \u2014 the trigger would create nothing.`});else{let _=new Set,v=new Set(L.filter(P=>typeof P=="string"));for(let P of L){let A=typeof P=="string"?P:void 0;if(A===void 0||A.length===0){r(`${R}.tasks`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${l.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`,en:`[optionalAction/unknownTaskRef] Optional action "${T}" on node "${l.id}" contains an empty or invalid template reference.`});continue}if(_.has(A)){r(`${R}.tasks.${A}`,{de:`[optionalAction/duplicateTaskRef] Template "${A}" ist in der Aktion "${T}" auf Knoten "${l.id}" doppelt referenziert.`,en:`[optionalAction/duplicateTaskRef] Template "${A}" is referenced twice in the action "${T}" on node "${l.id}".`});continue}_.add(A);let M=h.get(A);if(M===void 0){r(`${R}.tasks.${A}`,{de:`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${l.id}" referenziert das Template "${A}", das node.tasks nicht deklariert. Vorhanden: ${[...h.keys()].join(", ")||"keine"}.`,en:`[optionalAction/unknownTaskRef] Optional action "${T}" on node "${l.id}" references the template "${A}", which node.tasks does not declare. Present: ${[...h.keys()].join(", ")||"none"}.`});continue}let U=k.get(A);U!==void 0&&U!==T?r(`${R}.tasks.${A}`,{de:`[optionalAction/taskDoublyBound] Template "${A}" auf Knoten "${l.id}" ist bereits von der Aktion "${U}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`,en:`[optionalAction/taskDoublyBound] Template "${A}" on node "${l.id}" is already referenced by the action "${U}" \u2014 a template belongs to at most one optional action.`}):k.set(A,T);let oe=M.blocks?.templateKey;typeof oe=="string"&&!v.has(oe)&&r(`${R}.tasks.${A}`,{de:`[optionalAction/taskRefBlocks] Template "${A}" auf Knoten "${l.id}" tr\xE4gt 'blocks' auf "${oe}", das nicht zur selben Aktion "${T}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`,en:`[optionalAction/taskRefBlocks] Template "${A}" on node "${l.id}" carries 'blocks' on "${oe}", which does not belong to the same action "${T}" \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===A&&(re!==void 0&&v.has(re)||r(`${R}.tasks.${A}`,{de:`[optionalAction/taskRefBlocks] Template "${A}" auf Knoten "${l.id}" ist Ziel eines 'blocks' von ${re!==void 0?`"${re}"`:"einem Template"} au\xDFerhalb der Aktion "${T}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`,en:`[optionalAction/taskRefBlocks] Template "${A}" on node "${l.id}" is the target of a 'blocks' from ${re!==void 0?`"${re}"`:"a template"} outside the action "${T}" \u2014 a template outside may never hold back a reference (its spawn belongs to the trigger, not to onEnter).`}))}}}}}}return t}s($6,"checkOptionalActions");function R6(e){return typeof e=="number"?"number":typeof e=="boolean"?"boolean":"string"}s(R6,"literalValueType");function I6(e,n){let t=[],r=n?.notificationTemplates;for(let i of e.nodes){let o=i,a=GP(i,Je(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)||t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${o.id}.notifications.${c}`,reason:{de:`[notification/unknownEvent] Knoten "${o.id}" bindet eine Benachrichtigung 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 notification 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)){t.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}) eine Benachrichtigung verschicken \u2014 es ist ${u===void 0?"keine gebunden":"eine gebunden, aber abgeschaltet"}.`,en:`[notification/missingBinding] Node "${o.id}" must send a notification 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"){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/internalAudienceUnsupported] Knoten "${o.id}": das Ereignis "${c.id}" richtet sich an die Schule, und Benachrichtigungen an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 die gebundene Benachrichtigung "${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 notifications to the school cannot be delivered yet \u2014 the bound notification "${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){t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/unknownTemplate] Knoten "${o.id}": die Benachrichtigung "${u.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,en:`[notification/unknownTemplate] Node "${o.id}": the notification "${u.templateId}" is not in the catalog. Known: ${[...r.keys()].sort().join(", ")||"(none)"}.`},severity:"error"});continue}h.audience!==void 0&&h.audience!==c.audience&&t.push({layer:"GRAPH",kind:"nodeRule",path:p,reason:{de:`[notification/audienceMismatch] Die Benachrichtigung "${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 notification "${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=KP(c),k=new Set(h.params.map(y=>y.key));for(let y of Object.keys(u.args??{}))k.has(y)||t.push({layer:"GRAPH",kind:"nodeRule",path:`${p}.args.${y}`,reason:{de:`[notification/unknownArg] Die Benachrichtigung "${h.id}" hat kein Argument "${y}" \u2014 erwartet werden: ${h.params.map(b=>b.key).join(", ")||"(keine)"}.`,en:`[notification/unknownArg] The notification "${h.id}" has no argument "${y}" \u2014 expected: ${h.params.map(b=>b.key).join(", ")||"(none)"}.`},severity:"error"});for(let y of h.params){let b=u.args?.[y.key],E=`${p}.args.${y.key}`;if(b!==void 0&&"literal"in b){let R=R6(b.literal);y.type!==void 0&&!Gw(R,y.type)&&t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/argTypeMismatch] "${y.key}" erwartet ${Hl(y.type).de}, festgelegt ist aber ${JSON.stringify(b.literal)} (${R}).`,en:`[notification/argTypeMismatch] "${y.key}" expects ${Hl(y.type).en}, but ${JSON.stringify(b.literal)} (${R}) is set.`},severity:"error"});continue}if(b!==void 0){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unsupportedArg] "${y.key}" ist an ${JSON.stringify(b)} gebunden \u2014 ein Argument einer Benachrichtigung kann nur ein Festwert ({ literal }) sein oder automatisch aus ${VC(w,"de")} kommen.`,en:`[notification/unsupportedArg] "${y.key}" is bound to ${JSON.stringify(b)} \u2014 a notification argument can only be a fixed value ({ literal }) or come automatically from ${VC(w,"en")}.`},severity:"error"});continue}let T=jP(y,w.get(y.key)??[]);if(!(T.status==="resolved"||T.status==="unused")){if(T.status==="sometimes"){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unresolvedArg] Die Benachrichtigung "${h.id}" braucht "${y.key}" immer, ${T.source.source} liefert es aber nur manchmal. In notifications.${c.id}.args.${y.key} einen Festwert benennen \u2014 oder eine Benachrichtigung w\xE4hlen, die ohne "${y.key}" auskommt.`,en:`[notification/unresolvedArg] The notification "${h.id}" always needs "${y.key}", but ${T.source.source} provides it only sometimes. Name a fixed value in notifications.${c.id}.args.${y.key} \u2014 or choose a notification that works without "${y.key}".`},severity:"error"});continue}if(T.status==="ambiguous"){t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/ambiguousArg] "${y.key}" hat mehrere passende Quellen \u2014 ${T.matches.map(R=>R.source).join(", ")}. In notifications.${c.id}.args.${y.key} einen Festwert setzen.`,en:`[notification/ambiguousArg] "${y.key}" has several matching sources \u2014 ${T.matches.map(R=>R.source).join(", ")}. Set a fixed value in notifications.${c.id}.args.${y.key}.`},severity:"error"});continue}t.push({layer:"GRAPH",kind:"nodeRule",path:E,reason:{de:`[notification/unresolvedArg] Die Benachrichtigung "${h.id}" braucht "${y.key}"${y.type!==void 0?` (${Hl(y.type).de})`:""}, und der Knoten hat daf\xFCr ${T.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${T.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`,en:`[notification/unresolvedArg] The notification "${h.id}" needs "${y.key}"${y.type!==void 0?` (${Hl(y.type).en})`:""}, and the node has ${T.rejected.length===0?"no source for it":`only unsuitable sources for it: ${T.rejected.map(R=>`${R.source} (${R.type})`).join(", ")}`}.`},severity:"error"})}}}}return t}s(I6,"checkNotificationBindings");function O6(e){return xN(e).map(n=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:n,severity:"error"}))}s(O6,"checkAssignmentRules");function VC(e,n){let t=[...e.keys()].sort();return t.length===0?n==="de"?"(nichts)":"(nothing)":t.join(", ")}s(VC,"describeCandidates");function _6(e,n){return EN(e,n?.teamKeys).map(t=>({layer:"GRAPH",kind:"nodeRule",path:t.path,reason:t.reason,severity:"error"}))}s(_6,"checkChannels");function P6(e){return JI(e).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}s(P6,"checkStaffInputs");function N6(e,n){let t=[];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=>{t.push({layer:"GRAPH",kind:"nodeRule",path:o,reason:c,severity:"error"})},"issue");if(!DN(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(!we(c))continue;let u=de(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),!un(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=Ur(n,c);p!=null&&Js("nodeReads",Hs(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 t}s(N6,"checkReadinessReads");function C6(e,n){let t=[];for(let r of e.nodes){if(r.type!=="setFlag")continue;let i=QO(r),o=Jf(r);if(i===null||o===null)continue;let a=n?.formFlagKeysByFormNode?.get(i);if(a===void 0||a.has(o))continue;let l=[...a].sort();t.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.inputs.${Pn.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 t}s(C6,"checkSetFlagKeys");function D6(e,n){let t=n?.readinessFormFieldsByFormNode,r=n?.readinessPartyConditionKeysByFormNode;if(t===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(!we(a)||!Sr(a))continue;let l=t.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=ik(l,d);if(c.size===0)continue;let u=o.reads,p=(Array.isArray(u)?u:[]).filter(y=>un(y)&&y.owner===a.owner),h=ik(l,[...p.map(y=>y.path),...MN(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(D6,"checkReadinessPartyConditions");function bk(e){let n=Object.keys(e.inputs??{});if(n.length===0)return[];let t=e.generatorStamp,r=e.production,i=e.templateStamp;if(e.type==="governedDocument"&&(r==="resolver"&&!Array.isArray(t?.inputSchema?.fields)||r==="template"&&!Array.isArray(i?.fields)))return[];let a=new Set(ea(e).map(l=>l.id));return n.filter(l=>!a.has(l))}s(bk,"undeclaredInputKeys");function F6(e,n){return e.nodes.flatMap(t=>[...M6(e,t,ea(t),n),...L6(e,t,n)])}s(F6,"checkUnknownResources");function L6(e,n,t){let r=[],i=new Set((Je(n).workItemTemplates?.(n)??[]).map(a=>a.key)),o=new Set((n.tasks??[]).filter(a=>a.familyRequest!==void 0).map(a=>String(a.key)));for(let a of dp(n)){if(a.leaf==="assign{}"&&!i.has(a.owner)||a.leaf==="tasks[].assign.group"&&a.missing&&o.has(a.owner))continue;let l=zs[a.leaf],d=`nodes.${n.id}.${a.path}`,c=s(h=>h==="de"?`Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.id}), ${l.what.de} \u201E${a.owner}\u201C`:`node "${_e(e,n.id,"en")}" (${n.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=t?.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(L6,"referenceIssues");function M6(e,n,t,r){let i=[];for(let o of t){if(!Qf(o.type))continue;let a=Bs[o.type].existence;if(a.check!=="generic")continue;let l=r?.[a.catalog];if(l===void 0)continue;let d=n.inputs?.[o.id];if(d?.kind!=="literal"||typeof d.value!="string"||l.has(d.value))continue;let c=Bs[o.type].label;i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${n.id}.inputs.${o.id}`,reason:{de:`[inputs/unknownResource] Knoten \u201E${_e(e,n.id,"de")}\u201C (${n.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,n.id,"en")}" (${n.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(M6,"unknownResourceIssues");function q6(e){let n=[];for(let t of e.nodes)for(let r of bk(t))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${r}`,reason:{de:`[inputs/undeclared] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.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,t.id,"en")}" (${t.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 n}s(q6,"checkUndeclaredInputs");function K6(e){let n=[];for(let t of e.nodes){let r=new Set;for(let i of ea(t)){if(!r.has(i.id)){r.add(i.id);continue}n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.${i.id}`,reason:{de:`[inputs/duplicateSlot] Knoten \u201E${_e(e,t.id,"de")}\u201C (${t.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,t.id,"en")}" (${t.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 n}s(K6,"checkDuplicateSlots");function UC(e,n,t){let r=[],i=T6(e);if(i.length>0)return i;r.push(...c6(e)),r.push(...l6(e)),r.push(...u6(e)),r.push(...d6(e)),r.push(...o6(e)),r.push(...s6(e)),r.push(...a6(e)),r.push(...m6(e)),r.push(...f6(e)),r.push(...aP(e,n)),r.push(...h6(e,n)),r.push(...g6(e,n)),r.push(...y6(e,n)),r.push(...VN(e,n?.layout)),r.push(...w6(e,n)),r.push(...k6(e,n)),r.push(...v6(e,n)),r.push(...Z_(e,t)),r.push(...uP(e)),r.push(...gP(e)),r.push(...dP(e)),r.push(...cP(e)),r.push(...q6(e)),r.push(...F6(e,t)),r.push(...K6(e)),r.push(...x6(e)),r.push(...S6(e)),r.push(...oC(e,t)),r.push(...cC(e)),r.push(...lC(e)),r.push(...uC(e,t)),r.push(...wC(e,t)),r.push(...E6(e)),r.push(...I6(e,t)),r.push(...$6(e,t)),r.push(...O6(e)),r.push(...N6(e,t)),r.push(...D6(e,t)),r.push(...C6(e,t)),r.push(..._6(e,t)),r.push(...P6(e)),r.push(...KC(e));for(let o of e.nodes){let a=Je(o);a.validate&&r.push(...a.validate(o,e,t))}return r}s(UC,"checkGraph");function j6(e,n){let t=e.requiresOneOf;if(t===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(t)||t.length===0||t.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=n.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of t){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(j6,"checkRequiresOneOf");function V6(e){return e.nodes.flatMap(n=>bk(n).map(t=>({nodeId:n.id,key:t,binding:n.inputs?.[t]?.kind==="binding"})))}s(V6,"undeclaredInputCells");function GC(e,n){let t=V6(e).filter(o=>n.bindings||!o.binding);if(t.length===0)return{graph:e,dropped:t};let r=new Map;for(let o of t)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:t}}s(GC,"dropUndeclaredInputs");function vk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(vk,"isObject");function zC(e){return vk(e)&&e.type==="governedDocument"&&("template"in e||"cockpitFields"in e)}s(zC,"oldShape");function WC(e){return(e?.nodes??[]).some(zC)}s(WC,"needsTemplateStampMove");function B6(e){let n=e.generatorStamp?.inputSchema?.fields;if(e.production==="resolver")return Array.isArray(n)?n:null;let t=e.templateStamp?.fields;return e.production==="template"&&Array.isArray(t)?t:null}s(B6,"stampedFields");function U6(e){let n=String(e.id);if("template"in e&&"templateStamp"in e)return{unmoved:{nodeId:n,reason:"templateAndStamp"}};let t={...e},r=[];if("template"in e){let{template:i}=e;if(delete t.template,vk(i))t.templateStamp={fields:Array.isArray(i.fields)?i.fields:[],...i.localeField===void 0?{}:{localeField:i.localeField}};else return{unmoved:{nodeId:n,reason:"templateNotObject"}}}if("cockpitFields"in e){let i=Array.isArray(e.cockpitFields)?e.cockpitFields.filter(l=>typeof l=="string"):[];delete t.cockpitFields;let o=vk(e.inputs)?{...e.inputs}:{},a=B6(t);if(a===null&&i.length>0)return{unmoved:{nodeId:n,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:n,key:l,reason:"unknownKey"});else{if(c.type==="party"||c.type==="personList")continue;c.processSource!==void 0?r.push({nodeId:n,key:l,reason:"processSource"}):d?r.push({nodeId:n,key:l,reason:"cellExists"}):o[l]={kind:"cockpit"}}}t.inputs=o}return{node:t,reports:r}}s(U6,"moveNode");function YC(e){let n=[],t=[],r=[],i=e.nodes.map(o=>{if(!zC(o))return o;let a=U6(o);return"unmoved"in a?(r.push(a.unmoved),o):(n.push(String(o.id)),t.push(...a.reports),a.node)});return n.length===0?{graph:e,moved:n,reports:t,unmoved:r}:{graph:{...e,nodes:i},moved:n,reports:t,unmoved:r}}s(YC,"moveTemplateStampAndCockpit");var HC=If,G6="applicant.applicationSubmitted";function tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(tm,"isObject");function JC(e){return tm(e)&&e.type==="form"&&typeof e.id=="string"&&!At(e)}s(JC,"isCreatingFormNode");function z6(e){return tm(e.notifications)&&HC in e.notifications}s(z6,"hasSubmittedBinding");function xk(e){let n={toBind:[],alreadyBound:[],malformed:[]};for(let t of e?.nodes??[])JC(t)&&(t.notifications!==void 0&&!tm(t.notifications)?n.malformed.push(t.id):z6(t)?n.alreadyBound.push(t.id):n.toBind.push(t.id));return n}s(xk,"submitReceiptInventory");function QC(e){let{toBind:n}=xk(e);if(n.length===0)return{graph:e,bound:[]};let t=new Set(n),r=e.nodes.map(i=>{if(!JC(i)||!t.has(i.id))return i;let o=tm(i.notifications)?i.notifications:{};return{...i,notifications:{...o,[HC]:{templateId:G6}}}});return{graph:{...e,nodes:r},bound:n}}s(QC,"bindSubmitReceipt");var zo=["park","advance"],ir="whenNothingOwed",ZC={park:{de:"Jemand schaut drauf",en:"Someone looks at it"},advance:{de:"Durchreichen",en:"Pass through"}};function XC(e){let n=e.inputs?.[ir],t=n?.kind==="literal"?n.value:void 0;return Sk(t)?t:null}s(XC,"reviewModeOrNull");function Sk(e){return zo.includes(e)}s(Sk,"isReviewMode");function Ak(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ak,"isObject");function eD(e){return Ak(e)&&e.type==="review"&&!(Ak(e.inputs)&&ir in e.inputs)}s(eD,"lacksMode");function nD(e){return(e?.nodes??[]).some(eD)}s(nD,"needsReviewMode");function tD(e){let n=[],t=e.nodes.map(r=>{if(!eD(r))return r;n.push(r.id);let i=Ak(r.inputs)?r.inputs:{};return{...r,inputs:{...i,[ir]:{kind:"literal",value:"park"}}}});return{graph:{...e,nodes:t},set:n}}s(tD,"setReviewModePark");function rm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(rm,"isObject");function rD(e){let{notifications:n,bound:t}=Ep(e.notifications,{tasks:[]},e);return{next:n,bound:t}}s(rD,"bindingsFor");function iD(e){let n={toBind:[],malformed:[]};for(let t of e?.nodes??[])if(!(!rm(t)||typeof t.id!="string"||ia(t).length===0)){if(t.notifications!==void 0&&!rm(t.notifications)){n.malformed.push(t.id);continue}for(let r of rD(t).bound)n.toBind.push(`${t.id}.${r}`)}return n}s(iD,"appointmentLetterInventory");function oD(e){let n=[],t=!1,r=e.nodes.map(i=>{if(!rm(i)||typeof i.id!="string"||ia(i).length===0||i.notifications!==void 0&&!rm(i.notifications))return i;let{next:o,bound:a}=rD(i);return a.length===0?i:(t=!0,n.push(...a.map(l=>`${i.id}.${l}`)),{...i,notifications:o})});return t?{graph:{...e,nodes:r},bound:n}:{graph:e,bound:[]}}s(oD,"bindAppointmentLetters");function Sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Sa,"isObject");var sD=["id","label","dataFlow"],aD=["audience","populates","stages","expectedOutcomes"];function lD(e){return Array.isArray(e.assignmentRules)&&e.assignmentRules.some(n=>Sa(n)&&typeof n.slot=="string")}s(lD,"carriesStringSlots");function dD(e){return(e.nodes??[]).some(n=>Sa(n)&&n.type==="form"&&aD.some(t=>t in n))}s(dD,"carriesRetiredFormNodeKey");var W6=[{key:"generatorPin",editor:!0,holds:vO,what:{de:"Generator als `resolver`",en:"generator as `resolver`"}},{key:"setFlagProperties",editor:!0,holds:t_,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:l_,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:g_,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:uO,what:{de:"Entscheidungsausg\xE4nge ohne Bedeutung",en:"decision outcomes without a meaning"}},{key:"startNodeOutcomes",editor:!0,holds:hO,what:{de:"ein Start-Knoten mit eigenen Ausg\xE4ngen",en:"a start node with its own outcomes"}},{key:"templateParameters",editor:!0,holds:WC,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:"paymentSettlement",editor:!0,holds:S_,what:{de:"Zahlungsknoten mit \u201EAbrechnung\u201C (`inputs.settlement`) statt \u201EZahlungsweg\u201C (`inputs.mode`)",en:'payment node with "Settlement" (`inputs.settlement`) instead of "Payment mode" (`inputs.mode`)'}},{key:"documentRef",editor:!0,holds:D_,what:{de:"Dokument eines anderen Knotens als `document:$node.<Knoten>.document` statt als Slot `artifact:<Slot>`",en:"another node's document as `document:$node.<node>.document` instead of the slot `artifact:<slot>`"}},{key:"formView",editor:!0,holds:$_,what:{de:"Ansicht einer Aufgabe als `formView` statt als Ansichts-Adresse `view`",en:"a task's view as `formView` instead of the view address `view`"}},{key:"nodeAssignString",editor:!0,holds:N_,what:{de:"Team einer Knoten-Aufgabe als Text (`assign.<Vorlage>`) statt als Regelliste",en:"a node task's team as text (`assign.<template>`) instead of a rule list"}},{key:"reviewWithoutMode",editor:!0,holds:nD,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=>ap(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=>sD.some(n=>n in e),"holds"),what:{de:"`graph.id` / `graph.label` / `graph.dataFlow`",en:"`graph.id` / `graph.label` / `graph.dataFlow`"}},{key:"assignmentSlotString",editor:!1,holds:lD,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:dD,what:{de:"Formularknoten mit `audience` / `populates` / `stages` / `expectedOutcomes`",en:"form nodes with `audience` / `populates` / `stages` / `expectedOutcomes`"}}];function cD(e){if(!Sa(e)||!Array.isArray(e.nodes))return[];let n=e;return W6.filter(t=>t.holds(n)).map(({key:t,what:r,editor:i})=>({key:t,what:r,editor:i}))}s(cD,"legacyGraphShapes");function uD(e,n){let t=n.answers??{},r=[],i=[],o=e,a=sD.filter(A=>A in o);if(a.length>0){let A={...o};for(let M of a)delete A[M],r.push({message:`graph.${M}: deleted (read by nothing)`});o=A}if(dD(o)&&(o={...o,nodes:o.nodes.map(A=>{if(!Sa(A)||A.type!=="form")return A;let M=aD.filter(oe=>oe in A);if(M.length===0)return A;let U={...A};for(let oe of M)delete U[oe];return r.push({nodeId:String(A.id),message:`form node: deleted ${M.map(oe=>`\`${oe}\``).join(", ")} (read by nothing)`}),U})}),lD(o)){let A=o.assignmentRules.map((M,U)=>{if(!Sa(M)||typeof M.slot!="string")return M;let oe=jf(M.slot);return oe===null?(i.push({code:"assignment/slotUnknown",answer:"edit",message:`assignmentRules[${U}].slot "${M.slot}" is neither \`responsible\` nor \`team:<key>\` \u2014 edit it by hand`}),M):(r.push({message:`assignmentRules[${U}].slot "${M.slot}" \u2192 ${JSON.stringify(oe)}`}),{...M,slot:oe})});o={...o,assignmentRules:A}}let l=xO(o);o=l.graph;for(let A of l.moved)r.push({nodeId:A,message:"generator / template pin moved into its input"});for(let A of l.unmoved)i.push({code:`generatorPin/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the generator or template pin cannot be moved (${A.reason}) \u2014 edit the node by hand`});let d=r_(o);o=d.graph;for(let A of d.moved)r.push({nodeId:A,message:"setFlag `target` / `flagKey` / `value` moved into its inputs"});for(let A of d.unmoved)i.push({code:`setFlag/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the setFlag properties cannot be moved (${A.reason}) \u2014 edit the node by hand`});let c=d_(o);o=c.graph;for(let A of c.moved)r.push({nodeId:A,message:"scalar settings moved into inputs"});for(let A of c.unmoved)i.push({code:`scalar/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`\`${A.key}\` cannot be moved into an input (${A.reason}) \u2014 edit the node by hand`});let u=y_(o);o=u.graph;for(let A of u.moved)r.push({nodeId:A,message:"payment note moved into `inputs.reason` / retired sample document deleted"});for(let A of u.unmoved)i.push({code:`nodeConfig/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`\`${A.key}\` cannot be moved into an input (${A.reason}) \u2014 edit the node by hand`});let p=YC(o);o=p.graph;for(let A of p.moved){let M=o.nodes.find(Q=>Sa(Q)&&Q.id===A),U=M?.inputs?.documentTemplate,oe=U?.kind==="literal"&&typeof U.value=="string"?U.value:null;r.push({nodeId:A,message:M!==void 0&&"templateStamp"in M&&oe!==null?`template parameters moved onto \`templateStamp\` / cockpit list into cells \u2014 the record \`${oe}\` 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 A of p.reports)r.push({nodeId:A.nodeId,message:`cockpit field \`${A.key??""}\` deleted (${A.reason}: ${A.reason==="unknownKey"?"the stamp declares no such parameter":A.reason==="processSource"?"the case fills it itself":"the input already holds a cell"})`});for(let A of p.unmoved)i.push({code:`templateStamp/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.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":A.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=gO(o);o=h.graph;for(let A of h.moved)r.push({nodeId:A,message:"start node: own `outcomes` / `event` / `effect` deleted (the node type declares its outcome)"});for(let A of h.unmoved)i.push({code:`eventTrigger/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`the start node cannot be reduced to its type's outcome (${A.reason}) \u2014 edit the node by hand`});let w=fO(o,t.semantics);o=w.graph;for(let A of w.written){if(A.source==="formerDefault"){r.push({nodeId:A.nodeId,message:`outcome \`${A.outcomeId}\`: semantic "${A.semantic}" (DEFAULT \u2014 the meaning it ran with; the retired id parser knew no other)`,defaulted:{answer:"semantic",answerKey:`${A.nodeId}.${A.outcomeId}`,value:A.semantic}});continue}r.push({nodeId:A.nodeId,message:`outcome \`${A.outcomeId}\`: semantic "${A.semantic}" (${A.source==="answer"?"answered":"the meaning the retired id parser gave this id"})`})}for(let A of w.refused)i.push({code:A.answer===void 0?"outcome/formerMeaningNotAllowed":"outcome/semanticNotAllowed",nodeId:A.nodeId,answer:"semantic",answerKey:`${A.nodeId}.${A.outcomeId}`,candidates:A.allowed,message:A.answer===void 0?`${A.nodeType} outcome \`${A.outcomeId}\` ran as "${zy(A.outcomeId)??""}", which a ${A.nodeType} outcome may no longer carry \u2014 say which one it is`:`${A.nodeType} outcome \`${A.outcomeId}\`: "${A.answer}" is not a meaning a ${A.nodeType} outcome may carry`});for(let A of w.invalid)i.push({code:"outcome/semanticInvalid",nodeId:A.nodeId,answer:"edit",candidates:St,message:`outcome \`${A.outcomeId}\` carries the semantic "${A.value}", which is no meaning \u2014 edit it`});let k=kO(o,n.selection,t.waitlistPolicy);o=k.graph;for(let A of k.moved){let M=A.policy.waitlistOrder;r.push({nodeId:A.nodeId,message:`waitlist policy into inputs: ${Y6(A.policy)} (${A.source==="answer"?"answered":A.source==="manifest"?"from manifest `selection`":"DEFAULT \u2014 the manifest stated no `selection.waitlistOrder`; the former code default it ran with"})`,...A.source==="formerDefault"?{defaulted:{answer:"waitlistPolicy",answerKey:A.nodeId,value:M}}:{}})}for(let A of k.refused)i.push({code:`waitlist/${A.reason}`,nodeId:A.nodeId,answer:"waitlistPolicy",answerKey:A.nodeId,candidates:Xt,message:"manifest `selection` is malformed \u2014 say the queue order of this waitlist"});let y=A_(o);o=y.graph;for(let A of y.moved)r.push({nodeId:A,message:"payment: `inputs.settlement` \u2192 `inputs.mode` (separate \u2192 manual)"});for(let A of y.refused)i.push({code:`collectPayment/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.reason==="bothCells"?"the payment node carries both `inputs.settlement` and `inputs.mode` \u2014 delete `settlement` by hand":"`inputs.settlement` is no literal online | separate \u2014 set `inputs.mode` by hand"});let b=R_(o);o=b.graph;for(let A of b.moved)r.push({nodeId:A.split(".")[0],message:`\`formView\` \u2192 \`view\` (${A})`});for(let A of b.refused){let M=A.taskKey===void 0?"the node":`task "${A.taskKey}"`;i.push({code:`view/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:A.reason==="bothFields"?`${M} carries both \`formView\` and \`view\` \u2014 delete \`formView\` by hand`:`${M}'s \`formView\` is no { form, key } \u2014 set \`view\` by hand`})}let E=C_(o);o=E.graph;for(let A of E.moved)r.push({nodeId:A.nodeId,message:`\`assign.${A.templateKey}\`: team \u2192 rule list`});for(let A of E.refused)i.push({code:"assign/shape",nodeId:A.nodeId,answer:"edit",message:`\`assign.${A.templateKey}\` is neither a team key nor a rule list \u2014 set it by hand`});let T=F_(o);o=T.graph;for(let A of T.moved)r.push({nodeId:A.split(".")[0],message:`documents: \`document:$node.<node>.document\` \u2192 \`artifact:<slot>\` (${A})`});for(let A of T.refused)i.push({code:`workItems/${A.reason}`,nodeId:A.nodeId,answer:"edit",message:`task "${A.taskKey}" links a document whose node declares no single slot \u2014 name the slot as \`artifact:<slot>\` by hand`});if(k_(o)){let A=b_(o,t.payee);o=A.graph;for(let M of A.set)r.push({nodeId:M.nodeId,message:`online payment: payee "${M.payee}" (answered)`});for(let M of A.refused)i.push({code:"collectPayment/payeeMissing",nodeId:M,answer:"payee",answerKey:M,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 A of xk(o).malformed)i.push({code:"submitReceipt/notificationsMalformed",nodeId:A,answer:"edit",message:"the form node's `notifications` is no record \u2014 edit it by hand"});let R=QC(o);o=R.graph;for(let A of R.bound)r.push({nodeId:A,message:"submit receipt bound to `notifications.submitted` (`applicant.applicationSubmitted`, sent by code before)"});let D=tD(o);o=D.graph;for(let A of D.set)r.push({nodeId:A,message:"review: `whenNothingOwed` = park (every review parked before the input existed)"});for(let A of iD(o).malformed)i.push({code:"appointmentLetters/notificationsMalformed",nodeId:A,answer:"edit",message:"the node's `notifications` is no record \u2014 edit it by hand"});let L=oD(o);o=L.graph;for(let A of L.bound){let M=A.indexOf(".");r.push({nodeId:A.slice(0,M),message:`appointment letter bound to \`notifications.${A.slice(M+1)}\` (the standard letter, sent by code before)`})}let _=ap(o).filter(A=>!A.hasTeam);for(let A of _)i.push({code:"task/userWithoutTeam",nodeId:A.nodeId,answer:"edit",message:`task \`${A.taskKey}\` names a fixed person and no team \u2014 give it a team (\`assign.group\`) by hand`});let v=L_(o);o=v.graph;for(let A of v.dropped.filter(M=>M.hasTeam))r.push({nodeId:A.nodeId,message:`task \`${A.taskKey}\`: \`assign.userId\` deleted (the team holds the row)`});let P=GC(o,{bindings:!0});o=P.graph;for(let A of P.dropped){if(!A.binding){r.push({nodeId:A.nodeId,message:`input \`${A.key}\` deleted (no slot of the node declares it)`});continue}r.push({nodeId:A.nodeId,message:`input \`${A.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:`${A.nodeId}.${A.key}`,value:"deleted"}})}return{graph:o,changes:r,refusals:i}}s(uD,"upgradeGraph");function Y6(e){return`waitlistOrder=${e.waitlistOrder}`}s(Y6,"formatPolicy");function yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(yi,"isObject");var fD="admission.generic",pD=Object.keys(Mf).filter(e=>e!=="label");function mD(e){return yi(e.smartforms)?Object.entries(e.smartforms):[]}s(mD,"smartformEntries");function H6(e){let n=[];mD(e.index).some(([,i])=>yi(i)&&"outcomeFnRef"in i)&&n.push({de:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml",en:"`smartforms.<slug>.outcomeFnRef` in bundle.yaml"});let t=Object.keys(e.manifest).filter(i=>Object.hasOwn(_l,i));if(t.length>0){let i=t.map(o=>`\`${o}\``).join(", ");n.push({de:`manifest.json mit ${i}`,en:`manifest.json with ${i}`})}Object.values(e.smartforms??{}).some(i=>pD.some(o=>o in i))&&n.push({de:"Formulardateien mit `id` / `outcomeIds` / `schoolSlug`",en:"form files with `id` / `outcomeIds` / `schoolSlug`"});let r=e.workflow;return r!==void 0&&(yi(r.progressWiring)&&"layoutId"in r.progressWiring&&n.push({de:"`progressWiring.layoutId`",en:"`progressWiring.layoutId`"}),n.push(...cD(r.graph).map(i=>i.what))),n}s(H6,"legacyBundleShapes");function om(e,n){let t=H6(e);t.length!==0&&ae("BUNDLE_NEEDS_UPGRADE",{de:`offer: ${n} stammt aus einem \xE4lteren Bundle-Format (${t.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: ${n} is in an older bundle format (${t.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(om,"assertBundleCurrent");function im(e){let n=s(t=>Array.isArray(t)?t.map(n):yi(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(im,"canonical");function hD(e,n={}){let t=[],r=[],i=e.index,o=mD(i);if(o.some(([,u])=>yi(u)&&Object.keys(u).length>0)){let u={};for(let[p,h]of o){if(!yi(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!==fD){r.push({file:"bundle.yaml",code:"index/smartformEntry",answer:"edit",message:`smartforms.${p} carries ${Object.keys(h).map(y=>`\`${y}\``).join(", ")} \u2014 only \`outcomeFnRef: ${fD}\` is known; edit the entry to {} by hand`}),u[p]=h;continue}t.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,t.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?t.push({file:"manifest.json",message:"`progressLayout` deleted (the bundle has no workflow it could belong to)"}):l.progressLayout===void 0?(l={...l,progressLayout:p},t.push({file:"manifest.json",message:"`progressLayout` moved to workflow.json `progressLayout`"})):im(l.progressLayout)===im(p)?t.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(_l,u)?_l[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}t.push({file:"manifest.json",message:`\`${u}\` deleted (${h.en})`})}if(l!==void 0){if(yi(l.progressWiring)&&"layoutId"in l.progressWiring){let{layoutId:p,...h}=l.progressWiring;l={...l,progressWiring:h},t.push({file:"workflow.json",message:"`progressWiring.layoutId` deleted (the layout is the workflow's own)"})}let u=l.graph;if(yi(u)&&Array.isArray(u.nodes)){let p=uD(u,{selection:d,answers:n});l={...l,graph:p.graph},t.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 pD)if(y in h){if(y==="outcomeIds"){let b=Array.isArray(h.outcomes)?h.outcomes.map(E=>yi(E)?E.id:void 0):[];if(im([...Array.isArray(h.outcomeIds)?h.outcomeIds:[]].map(String).sort())!==im(b.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],t.push({file:k,message:`\`${y}\` deleted (${Mf[y].en})`})}u[p]=w}c=u}return{bundle:{index:i,manifest:a,...c!==void 0?{smartforms:c}:{},...l!==void 0?{workflow:l}:{}},changes:t,refusals:r}}s(hD,"upgradeOfferBundle");var J6={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},fve={createManifest:tt.workflow.createManifestInternal,publishManifest:tt.workflow.publishManifestInternal,publishOfferInternal:tt.workflow.publishOfferInternalInternal,publishOfferExternal:tt.workflow.publishOfferExternalInternal,getOfferPublishState:tt.workflow.getOfferPublishStateInternal,upsertCustomField:tt.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:tt.admission.upsertDerivedAttributeRuleInternal,createSmartForm:tt.forms.createSmartFormInternal,getSmartFormBySlug:tt.forms.getSmartFormBySlugInternal,saveSmartFormDraft:tt.forms.saveSmartFormDraftInternal,publishSmartForm:tt.forms.publishSmartFormInternal,createWorkflow:tt.workflow.createWorkflowInternal,getWorkflowGraph:tt.workflow.getWorkflowGraphInternal,saveWorkflowDraft:tt.workflow.saveWorkflowDraftInternal,publishWorkflow:tt.workflow.publishWorkflowInternal};function Ek(e,n){for(let[t,r]of Object.entries(e.smartforms??{})){(r===null||typeof r!="object"||Array.isArray(r))&&ae("INVALID",{de:`offer: ${n}: smartforms.${t} muss eine leere Zuordnung ({}) sein.`,en:`offer: ${n}: smartforms.${t} 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: ${n}: smartforms.${t} 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: ${n}: smartforms.${t} 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(Ek,"assertSmartformEntries");function gD(e){let n=s(t=>Array.isArray(t)?t.map(n):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(r=>[r,n(t[r])])):t,"sort");return JSON.stringify(n(e))}s(gD,"canonicalJson");function yD(e,n){return n==null?!0:gD(e)!==gD(n)}s(yD,"changed");async function wD(e,n,t,r={},i=J6){let{index:o}=n;om({index:o,manifest:n.manifest,...n.smartforms!==void 0?{smartforms:n.smartforms}:{},...n.workflow!==void 0?{workflow:n.workflow}:{}},`bundle of ${o.slugs.manifest}`),Ek(o,`bundle of ${o.slugs.manifest}`);let a=Lf(n.manifest);a.length>0&&ae("INVALID",{de:`offer: manifest.json von ${o.slugs.manifest} ist ung\xFCltig:
11277
11277
  - ${a.join(`
11278
11278
  - `)}`,en:`offer: manifest.json of ${o.slugs.manifest} is invalid:
11279
11279
  - ${a.join(`
11280
11280
  - `)}`});let l=[],d=o.tenant,c=!1,u=[];if(!t.dryRun){for(let y of o.customFields??[])await e.mutation(i.upsertCustomField,{client:d,key:y.key,label:y.label,data:y.data}),u.push(`field:${y.key}`);for(let y of o.derivedAttributes??[])await e.mutation(i.upsertDerivedAttributeRule,{client:d,key:y.key,type:y.type,expression:y.expression}),u.push(`derived:${y.key}`)}(o.customFields?.length??0)+(o.derivedAttributes?.length??0)>0&&l.push({step:"catalog",action:"scaffolded",detail:u.join(", ")||"(dry-run)"});let h=(await e.mutation(i.createManifest,{client:d,slug:o.slugs.manifest,label:o.label,...o.sortOrder!==void 0?{sortOrder:o.sortOrder}:{}})).offerVersionId;if(!t.dryRun&&r.afterManifestPublish){let y=await r.afterManifestPublish(h);l.push({step:"link",action:"scaffolded",...y?{detail:y}:{}})}(o.contractTemplates?.length??0)>0&&ae("INVALID",{de:"Das Angebot deklariert contractTemplates[], die beim Anwenden noch nicht unterst\xFCtzt werden. Entfernen Sie diese Eintr\xE4ge.",en:"The offer declares contractTemplates[], which are not yet supported when applying. Remove these entries."});let w={};if(n.smartforms!==void 0)for(let[y,b]of Object.entries(n.smartforms)){let{label:E,...T}=b;Ci(E)||ae("INVALID",{de:`[i18n/missingTranslation] SmartForm "${y}": \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`,en:`[i18n/missingTranslation] SmartForm "${y}": \`label\` must be a bilingual text ({ de, en }).`});let R=E,L=(await e.mutation(i.createSmartForm,{client:d,slug:y,label:R,offerVersionId:h})).smartFormDefinitionId;w[y]=L;let _=await e.query(i.getSmartFormBySlug,{client:d,offerVersionId:h,slug:y}),v=yD({definition:T},_?.def?{definition:_.def.definition}:void 0);v&&!t.dryRun&&await e.mutation(i.saveSmartFormDraft,{smartFormDefinitionId:L,definition:T}),v&&(c=!0),l.push({step:`smartform:${y}`,action:v?"created":"unchanged"})}let k;if(n.workflow!==void 0){o.slugs.workflow||ae("INVALID",{de:"Das B\xFCndel enth\xE4lt einen Workflow, aber slugs.workflow fehlt.",en:"The bundle contains a workflow, but slugs.workflow is missing."}),k=(await e.mutation(i.createWorkflow,{client:d,offerVersionId:h})).workflowDefinitionId;let E=await e.query(i.getWorkflowGraph,{workflowDefinitionId:k}),T={graph:Ds(n.workflow.graph),progressLayout:n.workflow.progressLayout??E?.progressLayout,progressWiring:n.workflow.progressWiring??E?.progressWiring},R=E?{graph:Ds(E.graph),progressLayout:E.progressLayout,progressWiring:E.progressWiring}:void 0,D=yD(T,R);D&&!t.dryRun&&await e.mutation(i.saveWorkflowDraft,{workflowDefinitionId:k,graph:n.workflow.graph,...n.workflow.progressLayout!==void 0?{progressLayout:n.workflow.progressLayout}:{},...n.workflow.progressWiring!==void 0?{progressWiring:n.workflow.progressWiring}:{}}),D&&(c=!0),l.push({step:"workflow",action:D?"created":"unchanged"})}if(t.publish){let y=t.publishStage??"external",b=await e.query(i.getOfferPublishState,{client:d,offerKey:o.slugs.manifest});b===null&&ae("NOT_FOUND",{de:`Der Mandant \u201E${d}\u201C hat keine Angebotsfamilie \u201E${o.slugs.manifest}\u201C zum Ver\xF6ffentlichen. Pr\xFCfen Sie den Mandanten und den Manifest-Slug.`,en:`Tenant \u201C${d}\u201D has no offer family \u201C${o.slugs.manifest}\u201D to publish. Check the tenant and the manifest slug.`});let E=y==="internal"?b.draftDiffersFromInternal:b.draftDiffersFromExternal,T=t.dryRun&&c||E;if(T&&!t.dryRun){let R=y==="external"&&b.internalCandidateMatchesDraft;if(!R){for(let D of Object.values(w))await e.mutation(i.publishSmartForm,{smartFormDefinitionId:D});k!==void 0&&await e.mutation(i.publishWorkflow,{workflowDefinitionId:k})}if(r.beforeOfferPublish){let D=await r.beforeOfferPublish(h,k);l.push({step:"pre-publish",action:"scaffolded",...D?{detail:D}:{}})}y==="internal"?await e.mutation(i.publishOfferInternal,{offerVersionId:h}):R?await e.mutation(i.publishOfferExternal,{offerVersionId:h}):await e.mutation(i.publishManifest,{offerVersionId:h}),l.push({step:y==="internal"?"offer:internal":"offer",action:"published",...R?{detail:"promoted the tested candidate"}:{}})}else l.push({step:y==="internal"?"offer:internal":"offer",action:T?"published":"already-live"})}return{steps:l,offerVersionId:h,...k!==void 0?{workflowDefinitionId:k}:{},...Object.keys(w).length>0?{smartFormDefIds:w}:{}}}s(wD,"applyOfferSteps");var cd="bundle.yaml",$k="manifest.json",ud="smartforms",Rk="workflow.json";function Aa(e){return JSON.parse(he(e,"utf8"))}s(Aa,"readJson");function Pe(e){return JSON.stringify(Tk(e),null,2)+`
11281
- `}s(Pe,"canonicalJson");function Tk(e){return Array.isArray(e)?e.map(Tk):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Tk(e[n])])):e}s(Tk,"sortKeys");function qe(e){let n=Y.resolve(e),t=Y.join(n,cd);if(!Ae(t))throw new Error(`offer: no ${cd} in ${n}`);let r=Pi.load(he(t,"utf8"));bD(r,t);let i=Y.join(n,Rk),o,a=Object.keys(r.smartforms??{});if(a.length>0){o={};for(let c of a){let u=Y.join(n,ud,`${c}.json`);if(!Ae(u))throw new Error(`offer: bundle.yaml declares smartform "${c}" but ${ud}/${c}.json is missing`);o[c]=Aa(u)}}let l=Aa(Y.join(n,$k)),d=Ae(i)?Aa(i):void 0;return om({index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}},t),Ek(r,t),{dir:n,index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}}}s(qe,"readBundle");function kD(e){let n=Y.resolve(e),t=Y.join(n,cd);if(!Ae(t))throw new Error(`offer: no ${cd} in ${n}`);let r=Pi.load(he(t,"utf8"));bD(r,t);let i=Object.keys(r.smartforms??{}),o;if(i.length>0){o={};for(let l of i){let d=Y.join(n,ud,`${l}.json`);if(!Ae(d))throw new Error(`offer: bundle.yaml declares smartform "${l}" but ${ud}/${l}.json is missing`);o[l]=Aa(d)}}let a=Y.join(n,Rk);return{dir:n,index:r,manifest:Aa(Y.join(n,$k)),...o?{smartforms:o}:{},...Ae(a)?{workflow:Aa(a)}:{}}}s(kD,"readRawBundle");function sm(e,n,t,r){Ae(e)&&Pe(r(he(e,"utf8")))===Pe(n)||ze(e,t,"utf8")}s(sm,"writeIfChanged");function Rt(e){if(Ln(e.dir,{recursive:!0}),sm(Y.join(e.dir,cd),e.index,Pi.dump(e.index,{lineWidth:100,sortKeys:!1}),n=>Pi.load(n)),sm(Y.join(e.dir,$k),e.manifest,Pe(e.manifest),JSON.parse),e.smartforms!==void 0){let n=Y.join(e.dir,ud);Ln(n,{recursive:!0});for(let[t,r]of Object.entries(e.smartforms))sm(Y.join(n,`${t}.json`),r,Pe(r),JSON.parse)}e.workflow!==void 0&&sm(Y.join(e.dir,Rk),e.workflow,Pe(e.workflow),JSON.parse)}s(Rt,"writeBundle");function bD(e,n){let t=[];if(e?.module||t.push("module"),e?.tenant||t.push("tenant"),e?.label||t.push("label"),e?.slugs?.manifest||t.push("slugs.manifest"),t.length>0)throw new Error(`offer: ${n} is missing required keys: ${t.join(", ")}`)}s(bD,"assertIndex");function vD(e,n,t={}){let r=new Map;return{slots:bN(e,n,t.slots??e.map(o=>o.slot),{person:s(o=>`person:${o}`,"person"),creator:s(()=>(t.creator===void 0&&ae("INVALID",{de:"[assignment/noCreator] Die zutreffende Zeile weist die anlegende Person zu, aber es wurde kein --creator angegeben (ein Selbststart hat keine).",en:"[assignment/noCreator] The matching row assigns the creating person, but no --creator was given (a self-start has none)."}),`creator:${t.creator}`),"creator"),rotation:s((o,{slot:a})=>{let l=t.rotationPrevious?.[a]??null,d=pN({pool:o.configKeys,mode:o.mode,previous:l,eligible:new Set(o.configKeys.filter(c=>!(t.left??[]).includes(c))),openCounts:new Map(o.configKeys.map(c=>[c,t.openCounts?.[c]??0]))});return d===null&&ae("INVALID",{de:`[assignment/rotationEmpty] Platz \u201E${a}\u201C: alle aus dem Pool sind ausgeschieden`,en:`[assignment/rotationEmpty] slot '${a}': everyone in the pool has left`}),r.set(a,{pool:[...o.configKeys],mode:o.mode,previous:l,picked:d}),`person:${d}`},"rotation")}).map(o=>{let a=r.get(o.slot);return{slot:o.slot,row:o.ruleIndex+1,assign:o.assign,value:o.value.kind==="queue"?"queue":o.value.value,...a!==void 0?{rotation:a}:{}}})}}s(vD,"simulateRules");function xD(e,n){let t={};for(let r of n??[]){let i=r.lastIndexOf("=");if(i<=0||i===r.length-1)throw new Error(`assignment simulate: ${e} takes <key>=<value>, got '${r}'`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`assignment simulate: ${e} names '${o}' twice`);t[o]=r.slice(i+1)}return t}s(xD,"parsePairs");function Q4(e){let n={};for(let[t,r]of Object.entries(xD("--open",e))){let i=Number(r);if(!Number.isInteger(i)||i<0)throw new Error(`assignment simulate: --open ${t}=${r} is no count`);n[t]=i}return n}s(Q4,"parseCounts");function Z4(e,n){if(e===void 0==(n===void 0))throw new Error("assignment simulate: pass exactly one of --env-json '<json>' or --env-file <path>");let t=e??he(n,"utf8"),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("assignment simulate: the environment must be a JSON object");return r}s(Z4,"parseEnv");var Ik=class extends xe{static{s(this,"AssignmentSimulateCommand")}static paths=[["assignment","simulate"]];static usage=$.Usage({category:"Admission",description:"Evaluate an offer bundle's assignment rule over an application's environment ($env), offline",details:`
11281
+ `}s(Pe,"canonicalJson");function Tk(e){return Array.isArray(e)?e.map(Tk):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,Tk(e[n])])):e}s(Tk,"sortKeys");function qe(e){let n=Y.resolve(e),t=Y.join(n,cd);if(!Ae(t))throw new Error(`offer: no ${cd} in ${n}`);let r=Pi.load(he(t,"utf8"));bD(r,t);let i=Y.join(n,Rk),o,a=Object.keys(r.smartforms??{});if(a.length>0){o={};for(let c of a){let u=Y.join(n,ud,`${c}.json`);if(!Ae(u))throw new Error(`offer: bundle.yaml declares smartform "${c}" but ${ud}/${c}.json is missing`);o[c]=Aa(u)}}let l=Aa(Y.join(n,$k)),d=Ae(i)?Aa(i):void 0;return om({index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}},t),Ek(r,t),{dir:n,index:r,manifest:l,...o?{smartforms:o}:{},...d?{workflow:d}:{}}}s(qe,"readBundle");function kD(e){let n=Y.resolve(e),t=Y.join(n,cd);if(!Ae(t))throw new Error(`offer: no ${cd} in ${n}`);let r=Pi.load(he(t,"utf8"));bD(r,t);let i=Object.keys(r.smartforms??{}),o;if(i.length>0){o={};for(let l of i){let d=Y.join(n,ud,`${l}.json`);if(!Ae(d))throw new Error(`offer: bundle.yaml declares smartform "${l}" but ${ud}/${l}.json is missing`);o[l]=Aa(d)}}let a=Y.join(n,Rk);return{dir:n,index:r,manifest:Aa(Y.join(n,$k)),...o?{smartforms:o}:{},...Ae(a)?{workflow:Aa(a)}:{}}}s(kD,"readRawBundle");function sm(e,n,t,r){Ae(e)&&Pe(r(he(e,"utf8")))===Pe(n)||ze(e,t,"utf8")}s(sm,"writeIfChanged");function Rt(e){if(Ln(e.dir,{recursive:!0}),sm(Y.join(e.dir,cd),e.index,Pi.dump(e.index,{lineWidth:100,sortKeys:!1}),n=>Pi.load(n)),sm(Y.join(e.dir,$k),e.manifest,Pe(e.manifest),JSON.parse),e.smartforms!==void 0){let n=Y.join(e.dir,ud);Ln(n,{recursive:!0});for(let[t,r]of Object.entries(e.smartforms))sm(Y.join(n,`${t}.json`),r,Pe(r),JSON.parse)}e.workflow!==void 0&&sm(Y.join(e.dir,Rk),e.workflow,Pe(e.workflow),JSON.parse)}s(Rt,"writeBundle");function bD(e,n){let t=[];if(e?.module||t.push("module"),e?.tenant||t.push("tenant"),e?.label||t.push("label"),e?.slugs?.manifest||t.push("slugs.manifest"),t.length>0)throw new Error(`offer: ${n} is missing required keys: ${t.join(", ")}`)}s(bD,"assertIndex");function vD(e,n,t={}){let r=new Map;return{slots:bN(e,n,t.slots??e.map(o=>o.slot),{person:s(o=>`person:${o}`,"person"),creator:s(()=>(t.creator===void 0&&ae("INVALID",{de:"[assignment/noCreator] Die zutreffende Zeile weist die anlegende Person zu, aber es wurde kein --creator angegeben (ein Selbststart hat keine).",en:"[assignment/noCreator] The matching row assigns the creating person, but no --creator was given (a self-start has none)."}),`creator:${t.creator}`),"creator"),rotation:s((o,{slot:a})=>{let l=t.rotationPrevious?.[a]??null,d=pN({pool:o.configKeys,mode:o.mode,previous:l,eligible:new Set(o.configKeys.filter(c=>!(t.left??[]).includes(c))),openCounts:new Map(o.configKeys.map(c=>[c,t.openCounts?.[c]??0]))});return d===null&&ae("INVALID",{de:`[assignment/rotationEmpty] Platz \u201E${a}\u201C: alle aus dem Pool sind ausgeschieden`,en:`[assignment/rotationEmpty] slot '${a}': everyone in the pool has left`}),r.set(a,{pool:[...o.configKeys],mode:o.mode,previous:l,picked:d}),`person:${d}`},"rotation")}).map(o=>{let a=r.get(o.slot);return{slot:o.slot,row:o.ruleIndex+1,assign:o.assign,value:o.value.kind==="queue"?"queue":o.value.value,...a!==void 0?{rotation:a}:{}}})}}s(vD,"simulateRules");function xD(e,n){let t={};for(let r of n??[]){let i=r.lastIndexOf("=");if(i<=0||i===r.length-1)throw new Error(`assignment simulate: ${e} takes <key>=<value>, got '${r}'`);let o=r.slice(0,i);if(Object.hasOwn(t,o))throw new Error(`assignment simulate: ${e} names '${o}' twice`);t[o]=r.slice(i+1)}return t}s(xD,"parsePairs");function Q6(e){let n={};for(let[t,r]of Object.entries(xD("--open",e))){let i=Number(r);if(!Number.isInteger(i)||i<0)throw new Error(`assignment simulate: --open ${t}=${r} is no count`);n[t]=i}return n}s(Q6,"parseCounts");function Z6(e,n){if(e===void 0==(n===void 0))throw new Error("assignment simulate: pass exactly one of --env-json '<json>' or --env-file <path>");let t=e??he(n,"utf8"),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("assignment simulate: the environment must be a JSON object");return r}s(Z6,"parseEnv");var Ik=class extends xe{static{s(this,"AssignmentSimulateCommand")}static paths=[["assignment","simulate"]];static usage=$.Usage({category:"Admission",description:"Evaluate an offer bundle's assignment rule over an application's environment ($env), offline",details:`
11282
11282
  The environment carries every key the rule reads ($env): offer
11283
11283
  {key,title}, unit {key,name} (key = the unit's configKey), stage
11284
11284
  {key,name,gradeLevel|null}, run {key,name,startDate|null}, applicant
11285
11285
  {language: 'de'|'en'|null (null = no applicant account), channel:
11286
11286
  'self-service'|'staff'}. A missing key fails loud, exactly like a start.
11287
- `,examples:[["Portal application to an offer",`$0 assignment simulate --dir ~/scratch/kindergarten-r17 --env-json '{"applicant":{"language":"de","channel":"self-service"}}'`],["The next pick of a \u201EReihum\u201C row whose last start took 'finanzen'","$0 assignment simulate --dir <bundle> --env-file env.json --rotation-previous team:finanzen=finanzen"],["A leastLoaded rotation with open-task counts","$0 assignment simulate --dir <bundle> --env-file env.json --open finanzen=3 --open finanzen_2=1"]]});dir=f.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=f.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=f.String("--env-file",{description:"\u2026or a file holding it"});creator=f.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=f.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=f.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=f.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let n=qe(this.dir),t=yN(n.workflow?.graph,`bundle ${this.dir}`),r=Z4(this.envJson,this.envFile),i=vD(t,r,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:xD("--rotation-previous",this.rotationPrevious),openCounts:Q4(this.open),left:this.left??[]});return this.print(i,o=>o.slots.map(a=>({slot:a.slot,row:`#${a.row}`,value:a.value,rotation:a.rotation===void 0?"":`${a.rotation.mode} [${a.rotation.pool.join(", ")}] after ${a.rotation.previous??"\u2014"} \u2192 ${a.rotation.picked}`}))),0}},SD=[Ik];import{createHash as X4}from"node:crypto";var Ok=/^[a-z0-9][a-z0-9-]*$/;function Ea(e){return Ok.test(e)}s(Ea,"isFileKey");function Wo(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":/[\u0000-\u001f]/.test(e)?"must not contain control characters":null}s(Wo,"fileNameDefect");var TD={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword",".odt":"application/vnd.oasis.opendocument.text",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png"},am={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function Ta(e){return X4("sha256").update(e).digest("hex")}s(Ta,"sha256Hex");function _k(e,n=TD){let t=Y.resolve(e),r;try{r=he(t)}catch{throw new Error(`File not found: ${e}`)}let i=n[Y.extname(t).toLowerCase()];if(i===void 0)throw new Error(`${e}: unsupported file type \u2014 allowed: ${Object.keys(n).join(", ")}.`);return{bytes:r,filename:Y.basename(t),mimeType:i,sha256:Ta(r),sizeBytes:r.length}}s(_k,"readLocalFile");var e6={tenantFile:x.tenantFiles.platformGenerateUploadUrl,brandingAsset:x.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:x.branding.platformGenerateBrandingLogoUploadUrl};async function Yo(e,n,t,r,i){let{uploadUrl:o,uploadTicket:a}=await e.mutation(e6[i],{client:n}),l=await e.upload(o,t,r);return await e.mutation(x.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(Yo,"uploadStaged");async function $D(e,n,t,r){return await Yo(e,n,t,r,"tenantFile")}s($D,"uploadTenantFile");function Pk(e){let n=[...e].filter(([,t])=>"fileName"in t||"size"in t).map(([t])=>t);if(n.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${n.join(", ")}: the target deployment still answers fileName / size \u2014 it runs a release from before file references. Use a plexus-cli built from that release, or wait for the next release.`)}s(Pk,"requireFileRefNames");async function fd(e,n){let t=await e.query(x.tenantFiles.platformList,{client:n});return Pk(t.map(r=>[`files["${r.key}"]`,r])),t}s(fd,"listLibrary");function RD(e,n,t,r,i){let o=_k(Y.resolve(e,n),i);if(o.mimeType!==t)throw new Error(`${r}: ${n} is ${o.mimeType}, the entry declares ${t}.`);return o}s(RD,"readSnapshotEntry");function ID(e,n){let t=new Map,r=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=RD(n,d,c.mimeType,`files["${c.key}"]`,TD);return t.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),i=AD(e.tenant.brandingAssets,n,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=AD(l.brandingAssets,n,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...i.assets!==void 0?{brandingAssets:i.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:r},bytes:t,brandingBytes:i.bytes,legalEntityBrandingBytes:o}}s(ID,"resolveSnapshotFiles");function AD(e,n,t){let r=new Map,i=e;if(i===void 0)return{assets:void 0,bytes:r};let o={};for(let[a,l]of Object.entries(i)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=RD(n,d,c.mimeType,`${t}.brandingAssets.${a}`,am);r.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:r}}s(AD,"resolveSnapshotBranding");async function OD(e,n,t,r,i){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(n.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await t(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(Ta(d)!==l.sha256)throw new Error(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);i||(o[l.key]=await r(d,l.mimeType))}return a}s(OD,"stageChanged");async function _D(e,n,t,r,i){let o=new Map(Object.entries(await e.query(x.tenantFiles.platformFileHashes,{client:n})??{})),a=new Map(t.map(l=>[l.key,l]));return await OD(t.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>r(a.get(l)),(l,d)=>Yo(e,n,l,d,"tenantFile"),i)}s(_D,"stageFileContents");function PD(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(PD,"brandingHolder");async function lm(e,n,t){let r=await e.query(x.branding.platformBrandingAssets,{client:n,...t!==void 0?{legalEntity:t}:{}});return Pk(Object.entries(r??{}).map(([i,o])=>[`${PD(t)}.brandingAssets.${i}`,o])),r}s(lm,"listBrandingAssets");async function Nk(e,n,t,r,i,o){let a=new Map(Object.entries(await lm(e,n,o)??{}).map(([d,c])=>[d,c.sha256])),l=PD(o);return await OD(Object.entries(t??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,r,(d,c)=>Yo(e,n,d,c,"brandingAsset"),i)}s(Nk,"stageBrandingAssets");async function ND(e,n,t,r){if(e===null||n===void 0)throw new Error(`${t}: its stored object is gone \u2014 ${r}`);let i=await fetch(e);if(!i.ok)throw new Error(`download of ${t} failed (${i.status}).`);let o=new Uint8Array(await i.arrayBuffer());if(Ta(o)!==n)throw new Error(`download of ${t} does not match its sha256 ${n}.`);return o}s(ND,"downloadVerified");async function Ck(e){return await ND(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(Ck,"downloadLibraryFile");async function Dk(e,n,t){return await ND(n.url,n.sha256,t===void 0?`branding/${e}`:`branding/${t}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(Dk,"downloadBrandingAsset");function n6(e,n,t){let r=Object.keys(am).find(i=>am[i]===n);if(r===void 0)throw new Error(`export: branding/${e} is ${n}, which a snapshot cannot name (${Object.keys(am).join(", ")}).`);if(t===void 0)return Y.join("branding",`${e}${r}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t))throw new Error(`export: legal entity key "${t}" is not a safe directory name for its brand files.`);return Y.join("branding",t,`${e}${r}`)}s(n6,"brandingAssetPath");function CD(e,n,t){let r=Y.join(e,n);Ln(Y.dirname(r),{recursive:!0}),ze(r,t)}s(CD,"writeBeside");async function DD(e,n,t,r){Pk([...t.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(t.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(t.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,p])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,p]))]);let i=new Map((await fd(e,n)).map(c=>[c.key,c])),o=Y.dirname(r),a=[];for(let c of t.files){let u=i.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let p=Wo(c.filename);if(p!==null||!Ea(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${p??"bad key"}).`);let h=Y.join("files",c.key,c.filename);CD(o,h,await Ck(u)),a.push({...c,path:h})}let l=await ED(e,n,t.tenant.brandingAssets,o,void 0),d=[];for(let c of t.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await ED(e,n,c.brandingAssets,o,c.key)})}return{...t,tenant:{...t.tenant,...l!==void 0?{brandingAssets:l}:{}},...t.foundation!==void 0?{foundation:{...t.foundation,legalEntities:d}}:{},files:a}}s(DD,"writeSnapshotFiles");async function ED(e,n,t,r,i){if(t===void 0)return;let o=await lm(e,n,i)??{},a={};for(let[l,d]of Object.entries(t)){let c=o[l],u=n6(l,d.mimeType,i);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);CD(r,u,await Dk(l,c,i)),a[l]={...d,path:u}}return a}s(ED,"writeSnapshotBranding");var t6={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function FD(e){return t6[Y.extname(e).toLowerCase()]}s(FD,"guessImageContentType");async function r6(e,n){if(e===void 0==(n===void 0))throw new Error("Pass exactly one of --file <path> or --url <url>.");if(n!==void 0&&cn())throw new Error("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=Y.resolve(e),l;try{l=he(a)}catch{throw new Error(`File not found: ${e}`)}let d=FD(a);if(d===void 0)throw new Error(`Cannot infer an image content-type from "${Y.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let t=await fetch(n);if(!t.ok)throw new Error(`Fetch failed for ${n} (${t.status} ${t.statusText}).`);let r=new Uint8Array(await t.arrayBuffer()),i=t.headers.get("content-type")?.split(";")[0]?.trim(),o=i&&i.startsWith("image/")?i:FD(new URL(n).pathname);if(o===void 0)throw new Error(`Response for ${n} is not an image (content-type "${i??"unknown"}").`);return{bytes:r,contentType:o}}s(r6,"loadLogoBytes");function $a(){return f.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s($a,"legalEntityOption");function Ra(e){return e===void 0?{}:{legalEntity:e}}s(Ra,"ownerArgs");async function i6(e,n,t,r){return await Yo(e,n,t,r,"brandingLogo")}s(i6,"uploadLogo");var Fk=class extends C{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=$.Usage({category:"Branding",description:"Upload a tenant's portal logo",details:"Sets the external-portal logo for --tenant from a local --file or a remote --url. A one-off upload without the tenant's Branding admin UI. To move the logo with the rest of the config (export \u2192 apply, env \u2192 env), use `config apply` \u2014 it carries the file by hash (`tenant.brandingAssets.logo`).",examples:[["Upload the test tenant's logo to staging from a file","$0 --env staging --tenant test branding set-logo --file logo.png"],["Upload from an S3 URL","$0 --env staging --tenant test branding set-logo --url https://s3.example/logo.png"],["Upload a Tr\xE4ger's own logo (its units' portal pages and letters wear it)","$0 --env staging --tenant test branding set-logo --legal-entity test_seminare --file seminare.png"]]});file=f.String("--file",{description:"Local image file to upload"});url=f.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),{bytes:r,contentType:i}=await r6(this.file,this.url),o=await i6(n,t,r,i);return await n.mutation(x.branding.platformSetBrandingLogo,{client:t,...Ra(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:t,slot:"primary",contentType:i,bytes:r.length,storageId:o},a=>[{field:"tenant",value:a.tenant},{field:"slot",value:a.slot},{field:"contentType",value:a.contentType},{field:"bytes",value:String(a.bytes)},{field:"storageId",value:a.storageId}]),0}},Lk=class extends C{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=$.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n);return await n.mutation(x.branding.platformClearBrandingLogo,{client:t,...Ra(this.legalEntity),slot:"primary"}),this.print({tenant:t,slot:"primary",cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}};function LD(e){if(e!=="heading"&&e!=="body")throw new Error(`branding: --slot must be heading or body (got "${e}")`);return e}s(LD,"parseFontSlot");var Mk=class extends C{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=$.Usage({category:"Branding",description:"Upload a tenant's portal font file (WOFF2) for a slot",details:"Uploads --file as the font of --slot (heading|body). The backend checks the WOFF2 signature and the 2 MB cap and applies the file under the slot's configured family (`fonts.<slot>.family` \u2014 set it first with `branding set-theme` or `config apply`). A replaced file is deleted. `config apply` carries font files by hash too (`tenant.brandingAssets.fontHeading|fontBody`).",examples:[["Upload the test tenant's heading font to staging","$0 --env staging --tenant test branding set-font --slot heading --file heading.woff2"]]});slot=f.String("--slot",{required:!0,description:"heading | body"});file=f.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=$a();async execute(){let n=LD(this.slot),t=Y.resolve(this.file),r;try{r=he(t)}catch{throw new Error(`File not found: ${this.file}`)}let i=await this.caller(),o=this.requireTenant(i),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),{storageId:l}=await i.action(x.brandingFonts.platformSetBrandingFont,{client:o,...Ra(this.legalEntity),slot:n,bytes:a});return this.print({tenant:o,slot:n,bytes:r.length,storageId:l},d=>[{field:"tenant",value:d.tenant},{field:"slot",value:d.slot},{field:"bytes",value:String(d.bytes)},{field:"storageId",value:d.storageId}]),0}},qk=class extends C{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=$.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=f.String("--slot",{required:!0,description:"heading | body"});legalEntity=$a();async execute(){let n=LD(this.slot),t=await this.caller(),r=this.requireTenant(t);return await t.mutation(x.branding.platformClearBrandingFont,{client:r,...Ra(this.legalEntity),slot:n}),this.print({tenant:r,slot:n,cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}},Kk=class extends C{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=$.Usage({category:"Branding",description:"Set a tenant's portal theme tokens from a JSON file",details:"Replaces the branding THEME (colors/radius/logoSize/bannerDensity/filledHeader/websiteUrl/font families) wholesale from --file. Does NOT touch the uploaded logo or font files (see `branding set-logo` / `branding set-font`). The same brand tokens `config apply` writes, but surgical \u2014 it touches only branding, not the rest of the tenant config.",examples:[["Apply the test tenant's theme to staging","$0 --env staging --tenant test branding set-theme --file theme.json"],["Give a Tr\xE4ger its own theme (replaces the tenant's brand as a block for its units)","$0 --env staging --tenant test branding set-theme --legal-entity test_seminare --file seminare.json"]]});file=f.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Y.resolve(this.file),i;try{i=JSON.parse(he(r,"utf8"))}catch(o){throw new Error(`Cannot read branding JSON ${this.file}: ${xt(o)}`,{cause:o})}return await n.mutation(x.branding.platformUpdateBranding,{client:t,...Ra(this.legalEntity),branding:i}),this.print({tenant:t,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},jk=class extends C{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=$.Usage({category:"Branding",description:"Show a tenant's current branding + resolved logo and font-file URLs",details:"With --legal-entity <key>, that Tr\xE4ger's own brand \u2014 `branding: null` and no files means it has none, and its units wear the next brand up (a parent Tr\xE4ger's, else the tenant's)."});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.branding.platformGetBranding,{client:t,...Ra(this.legalEntity)});return this.print(r),0}},MD=[jk,Kk,Fk,Lk,Mk,qk];var Ia=s(()=>f.String("--output",{hidden:!0}),"retiredOutputOption"),kn=s(()=>f.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function Oa(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Oe(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return ln(e.context.stderr,"--output","--out"),e.retiredOutput}s(Oa,"resolveOut");function Cn(e,n){let t=Y.resolve(e);if(Ae(t)&&!n)throw new Oe(`${t} exists \u2014 pick another --out or pass --force.`);return t}s(Cn,"assertOutFree");function o6(e){try{return Cr(e)}catch{throw new Oe(`${e} is not a directory \u2014 --out names a directory here.`)}}s(o6,"entriesOf");function Vk(e,n){let t=Y.resolve(e);if(Ae(t)&&o6(t).length>0&&!n)throw new Oe(`${t} is not empty \u2014 pick another --out or pass --force.`);return t}s(Vk,"assertOutDirFree");function qD(e,n,t){let r=Cn(e,t),i=n.map(o=>Y.join(Y.dirname(r),o)).filter(o=>Ae(o));if(i.length>0&&!t)throw new Oe(`${i.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return r}s(qD,"assertSnapshotOutFree");function dm(e){(!Number.isSafeInteger(e)||e<0)&&ae("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(dm,"assertMoney");var Bk=["month","year","once","unit"];var s6=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function wi(e,n){return ae("CONFLICT",{de:e,en:n})}s(wi,"missing");var KD=s(e=>e!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(new Date(`${e}T00:00:00Z`).valueOf())&&new Date(`${e}T00:00:00Z`).toISOString().slice(0,10)===e,"isoDate");function jD(e,n,t){return{label:n,kind:"chosen",valueType:"choice",choices:t,resolve(r){let i=r.selections?.[e];return(!i||!t.includes(i))&&wi(`Die Auswahl f\xFCr \u201E${n.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${n.en}\u201D is missing or invalid.`),{value:i,explanation:{de:`${n.de}: ${i} (Vertragsauswahl)`,en:`${n.en}: ${i} (contract selection)`}}}}}s(jD,"chosen");function Uk(e,n){let t=e.enrollment,r=t?.contextDate??n;return(!t||!t.startDate||t.startDate>r||t.endDate&&t.endDate<r)&&wi("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),t}s(Uk,"enrollment");var a6={paymentFrequency:jD("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,n){let t=Uk(e,n).gradeLevel;return(!Number.isSafeInteger(t)||t<1)&&wi("Die Klassenstufe fehlt.","The grade level is missing."),{value:t,explanation:{de:`Klassenstufe ${t} am ${n}`,en:`Grade ${t} on ${n}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,n){let t=Uk(e,n).schoolYear;return(!Number.isSafeInteger(t)||t<1)&&wi("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:t,explanation:{de:`Schuljahr ${t}/${t+1}`,en:`School year ${t}/${t+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,n){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return s6(c)||wi("Der im Vertrag gew\xE4hlte Geschwisterrang fehlt oder ist keine ganze Zahl ab 1.","The sibling rank chosen on the contract is missing or not a whole number from 1."),{value:Number(c),explanation:{de:`Geschwisterrang ${c} (im Vertrag gew\xE4hlt)`,en:`Sibling rank ${c} (chosen on the contract)`}}}e.unavailable?.siblingRank&&ae("CONFLICT",e.unavailable.siblingRank);let t=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!t?.some(c=>c.partyId===e.partyId))&&wi("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),t.some(c=>!KD(c.firstEnrolledOn)||c.firstEnrolledOn>n)&&wi("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let r=t.find(c=>c.partyId===e.partyId),i=r.firstEnrolledOn,o=t.filter(c=>c.firstEnrolledOn===i);o.length>1&&o.some(c=>!KD(c.birthDate)||c.birthDate>n)&&wi("Geschwister wurden am selben Tag erstmals eingeschrieben, und f\xFCr die Reihenfolge fehlt ein g\xFCltiges Geburtsdatum.","Siblings first enrolled on the same day, and a valid birth date is missing to order them.");let a=s(c=>c.birthDate<r.birthDate||c.birthDate===r.birthDate&&c.partyId<r.partyId,"before"),l=t.filter(c=>c.firstEnrolledOn<i).length+o.filter(c=>c!==r&&a(c)).length+1,d=o.length>1?{de:`; gleicher Beginn wie ${o.length-1} Geschwister: \xE4lteste zuerst, bei gleichem Geburtsdatum nach Personen-ID`,en:`; same start as ${o.length-1} sibling${o.length>2?"s":""}: oldest first, then party ID for equal birth dates`}:{de:"",en:""};return{value:l,explanation:{de:`${l}. Kind von ${t.length} berechtigten Kindern am ${n}; erste Einschreibung am ${i}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${t.length} eligible children on ${n}; first enrollment on ${i}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,n){let t=Uk(e,n).programId;return t||wi("Das Programm fehlt.","The program is missing."),{value:t,explanation:{de:`Programm der Einschreibung am ${n}`,en:`Enrollment program on ${n}`}}}},admissionFeeTier:jD("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},l6=Object.fromEntries(Object.entries(a6).map(([e,n])=>[e,{...n,matchSchema:{parse(t){return c6(n,t),t}},matches:d6}])),fxe=Object.keys(l6);function d6(e,n){return"else"in n?!0:"eq"in n?e===n.eq:"in"in n?n.in.includes(e):typeof e=="number"&&(n.gte===void 0||e>=n.gte)&&(n.lte===void 0||e<=n.lte)}s(d6,"matchesPrice");function c6(e,n){let t=s(()=>ae("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!n||typeof n!="object"||Array.isArray(n))return t();let r=n,i=Object.keys(r).sort().join();if(i==="else"&&r.else===!0)return;let o=s(a=>e.valueType==="integer"?Number.isSafeInteger(a)&&Number(a)>=1:typeof a=="string"&&a.length>0&&(e.valueType!=="choice"||e.choices.includes(a)),"validValue");if(!(i==="eq"&&o(r.eq))&&!(i==="in"&&Array.isArray(r.in)&&r.in.length>0&&new Set(r.in).size===r.in.length&&r.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(i)&&Object.values(r).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(r.gte===void 0||r.lte===void 0||Number(r.gte)<=Number(r.lte))))return t()}s(c6,"validateMatch");function VD(e,n){if(Object.keys(n).some(t=>!["percent","amountMinor"].includes(t))&&ae("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."}),e==="percent"&&"percent"in n&&!("amountMinor"in n)){(!Number.isFinite(n.percent)||n.percent<0||n.percent>100)&&ae("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in n&&!("percent"in n))return dm(n.amountMinor);ae("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."})}s(VD,"validateRule");var u6=/^[a-z][a-z0-9_-]{0,63}$/;function BD(e){return u6.test(e)}s(BD,"isTemplateConfigKey");import{createHash as y6}from"node:crypto";import{inflateRawSync as w6}from"node:zlib";var UD=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,f6=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,p6=/^[#/]\s*/;function m6(e){let n=e.trim(),t=n.match(/^{{\s*([^{}]+?)\s*}}$/);if(t)return t[1]?.trim()??n;let r=n.match(/^<<\s*([^<>]+?)\s*>>$/);return r?r[1]?.trim()??n:n}s(m6,"innerTemplatePlaceholder");function cm(e){return m6(e).replace(p6,"")}s(cm,"normalizeTemplatePlaceholderKey");function um(e){return cm(e).toLowerCase()}s(um,"canonicalTemplatePlaceholderKey");function GD(e){let n=new Map;for(let t of h6(e))n.has(t.key)||n.set(t.key,t.placeholder);return Array.from(n.entries()).sort(([t],[r])=>t.localeCompare(r,"de")).map(([,t])=>t)}s(GD,"extractTemplatePlaceholders");function h6(e){let n=[];for(let t of e.matchAll(f6)){let r=cm(t[1]??t[2]??"");r&&n.push({key:um(r),placeholder:t[0].trim()})}return n}s(h6,"extractTemplatePlaceholderOccurrences");var zD=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function g6(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(n,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-f]+);/gi,(n,t)=>String.fromCodePoint(parseInt(t,16))).replace(/&amp;/g,"&")}s(g6,"templateXmlText");function WD(e){return e.map(g6).join(`
11288
- `)}s(WD,"templateTextFromParts");var k6="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function pd(e){let n=Y.resolve(e);if(!n.toLowerCase().endsWith(".docx"))throw new Error("Word templates must be a .docx file.");let t=new Uint8Array(await zt(n));return{file:n,bytes:t,sha256:y6("sha256").update(t).digest("base64"),placeholders:GD(b6(t)).map(cm)}}s(pd,"readLocalDocx");async function fm(e,n,t,r){let i=await e.query(x.templates.roleOptions,{client:n}),o=i.find(d=>d.key===r.role);if(o===void 0)throw new Error(`Unknown leaf role "${r.role}". Available: ${i.map(d=>d.key).join(", ")}`);let a=await HD(e,n,t),{templateId:l}=await e.action(x.templateFileActions.create,{client:n,name:r.name,roleId:o.id,storageId:a,filename:Y.basename(t.file),...r.configKey===void 0?{}:{configKey:r.configKey},...r.icon===void 0?{}:{icon:r.icon},...r.fileNamePattern===void 0?{}:{fileNamePattern:r.fileNamePattern}});return l}s(fm,"uploadDocumentTemplate");async function YD(e,n,t,r){let i=await HD(e,n,r);await e.action(x.templateFileActions.replaceFile,{client:n,templateId:t,storageId:i,filename:Y.basename(r.file)})}s(YD,"replaceDocumentTemplateFile");async function HD(e,n,t){let{uploadUrl:r,uploadTicket:i}=await e.mutation(x.templates.generateUploadUrl,{client:n}),o=await e.upload(r,t.bytes,k6);return await e.mutation(x.uploads.registerUpload,{uploadTicket:i,storageId:o}),o}s(HD,"stageDocx");function b6(e){let n=v6(e,t=>zD.test(t));if(!n.has("word/document.xml"))throw new Error("word/document.xml not found \u2014 the file is not a readable .docx.");return WD([...n.values()])}s(b6,"docxPlaceholderText");function v6(e,n){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Error("No ZIP central directory \u2014 the file is not a readable .docx."),i=-1;for(let d=e.length-22;d>=Math.max(0,e.length-22-65535);d--)if(t.getUint32(d,!0)===101010256){i=d;break}if(i<0)throw r;let o=t.getUint16(i+10,!0),a=t.getUint32(i+16,!0),l=new Map;for(let d=0;d<o;d++){if(a+46>e.length||t.getUint32(a,!0)!==33639248)throw r;let c=t.getUint16(a+10,!0),u=t.getUint32(a+20,!0),p=t.getUint16(a+28,!0),h=t.getUint16(a+30,!0),w=t.getUint16(a+32,!0),k=t.getUint32(a+42,!0),y=new TextDecoder().decode(e.subarray(a+46,a+46+p));if(a+=46+p+h+w,!n(y))continue;if(t.getUint32(k,!0)!==67324752)throw r;let b=k+30+t.getUint16(k+26,!0)+t.getUint16(k+28,!0),E=Buffer.from(e.subarray(b,b+u));l.set(y,(c===0?E:w6(E)).toString("utf8"))}return l}s(v6,"readZipEntries");function Dn(e,n,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t}: ${n} muss ein Objekt sein.`);return e}s(Dn,"record");function Ge(e,n,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t}: ${n} fehlt.`);return e.trim()}s(Ge,"text");function gt(e,n,t,r){let i=In(e);if(i==="not-localized"){let a=typeof e=="string"&&e.trim()!==""?e.trim():"\u2026";throw new Error(`${t}: ${n}: erwartet { "de": "\u2026", "en": "\u2026" } (${r} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(i.length>0)throw new Error(`${t}: ${n}.${i.join(` und ${n}.`)} ${i.length>1?"fehlen":"fehlt"} (${r} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let o=e;return{de:o.de.trim(),en:o.en.trim()}}s(gt,"localizedName");function Mt(e,n,t){if(!Array.isArray(e))throw new Error(`${t}: ${n} muss eine Liste sein.`);return e}s(Mt,"list");function pm(e,n){return Mt(e,"revenueAccounts",n).map((t,r)=>{let i=Dn(t,`revenueAccounts[${r}]`,n);return{code:Ge(i.code,`revenueAccounts[${r}].code`,n),name:Ge(i.name,`revenueAccounts[${r}].name`,n)}})}s(pm,"parseRevenueAccounts");function mm(e,n){return Mt(e,"billingItems",n).map((t,r)=>{let i=`billingItems[${r}]`,o=Dn(t,i,n),a=Ge(o.itemType,`${i}.itemType`,n),l=Ge(o.taxTreatment,`${i}.taxTreatment`,n);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new Error(`${n}: ${i}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new Error(`${n}: ${i}.itemType "${a}" ist unbekannt.`);if(o.minAmount!==void 0)throw new Error(`${n}: ${i}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=Dn(o.price,`${i}.price`,n),c=d.effectiveFrom===void 0?{}:{effectiveFrom:Ge(d.effectiveFrom,`${i}.price.effectiveFrom`,n)},u=Ge(d.currency,`${i}.price.currency`,n),p=d.tree===void 0?(()=>{let h=Ge(d.period,`${i}.price.period`,n);if(!["month","year","once","unit"].includes(h))throw new Error(`${n}: ${i}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new Error(`${n}: ${i}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:Dn(d.tree,`${i}.price.tree`,n),...c}})();return{key:Ge(o.key,`${i}.key`,n),name:gt(o.name,`${i}.name`,n,"Artikelnamen"),itemType:a,revenueAccount:Ge(o.revenueAccount,`${i}.revenueAccount`,n),taxTreatment:l,config:Dn(o.config??{},`${i}.config`,n),...o.programs===void 0?{}:{programs:Mt(o.programs,`${i}.programs`,n).map((h,w)=>Ge(h,`${i}.programs[${w}]`,n))},price:p}})}s(mm,"parseBillingItems");var Ie="catalog",x6=["sibling","stipend","promo","needsBased","singleParent"],S6=["percent","absolute"];function Gk(e,n){let t=new Set;for(let r of e){if(t.has(r))throw new Error(`${Ie}: ${n}: Schl\xFCssel "${r}" steht zweimal in der Datei.`);t.add(r)}}s(Gk,"uniqueKeys");function hm(e,n,t){if(!n.includes(e))throw new Error(`${Ie}: ${t} "${e}" ist unbekannt (${n.join(", ")}).`);return e}s(hm,"oneOf");function A6(e,n){let t=Dn(e,"Datei",Ie);if(t.plans!==void 0)throw new Error("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let r=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],i=Object.keys(t).filter(c=>!r.includes(c));if(i.length>0)throw new Error(`${Ie}: unbekannte Abschnitte ${i.join(", ")} (erlaubt: ${r.join(", ")}).`);let o=mm(t.billingItems??[],Ie).map((c,u)=>{let p=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new Error(`${Ie}: ${p}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new Error(`${Ie}: ${p}.effectiveFrom fehlt \u2014 der erste Tag, ab dem der Preis gilt (YYYY-MM-DD).`);return{...c,price:"tree"in c.price?{currency:c.price.currency,tree:c.price.tree,effectiveFrom:c.price.effectiveFrom}:{currency:c.price.currency,amount:c.price.amount,effectiveFrom:c.price.effectiveFrom,period:c.price.period}}}),a=Mt(t.grantTemplates??[],"grantTemplates",Ie).map((c,u)=>{let p=`grantTemplates[${u}]`,h=Dn(c,p,Ie);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new Error(`${Ie}: ${p}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new Error(`${Ie}: ${p}.retroactiveRevocation muss true oder false sein.`);let w=hm(Ge(h.scope,`${p}.scope`,Ie),["line","aggregate"],`${p}.scope`),k=hm(Ge(h.kind,`${p}.kind`,Ie),S6,`${p}.kind`),y=Dn(h.rule,`${p}.rule`,Ie);VD(k,y);let b=hm(Ge(h.pricePeriod,`${p}.pricePeriod`,Ie),["month","year","once","unit"],`${p}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||w!=="aggregate")throw new Error(`${Ie}: ${p}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);dm(h.floorTotal)}let E=Mt(h.eligibleItems,`${p}.eligibleItems`,Ie).map((T,R)=>Ge(T,`${p}.eligibleItems[${R}]`,Ie));if(E.length===0||new Set(E).size!==E.length)throw new Error(`${Ie}: ${p}.eligibleItems braucht eindeutige Artikel.`);return{key:Ge(h.key,`${p}.key`,Ie),name:gt(h.name,`${p}.name`,Ie,"Erm\xE4\xDFigungsnamen"),eligibleItems:E,scope:w,rule:y,pricePeriod:b,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:Ge(h.offeredFrom,`${p}.offeredFrom`,Ie)},...h.offeredUntil===void 0?{}:{offeredUntil:Ge(h.offeredUntil,`${p}.offeredUntil`,Ie)},reason:hm(Ge(h.reason,`${p}.reason`,Ie),x6,`${p}.reason`),kind:k,eligibility:Dn(h.eligibility,`${p}.eligibility`,Ie),retroactiveRevocation:h.retroactiveRevocation}}),l=Mt(t.documentTemplates??[],"documentTemplates",Ie).map((c,u)=>{let p=`documentTemplates[${u}]`,h=Dn(c,p,Ie),w=Ge(h.key,`${p}.key`,Ie);if(!BD(w))throw new Error(`${Ie}: ${p}.key "${w}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let k=Y.resolve(n,Ge(h.file,`${p}.file`,Ie));if(!k.toLowerCase().endsWith(".docx"))throw new Error(`${Ie}: ${p}.file muss eine .docx sein.`);return{key:w,name:gt(h.name,`${p}.name`,Ie,"Vorlagennamen"),file:k,role:Ge(h.role,`${p}.role`,Ie),...h.icon===void 0?{}:{icon:Ge(h.icon,`${p}.icon`,Ie)},...h.fileNamePattern===void 0?{}:{fileNamePattern:Ge(h.fileNamePattern,`${p}.fileNamePattern`,Ie)},...h.parameters===void 0?{}:{parameters:h.parameters===null?null:E6(h.parameters,`${p}.parameters`)}}});Gk(o.map(c=>c.key),"billingItems"),Gk(a.map(c=>c.key),"grantTemplates");for(let[c,u]of o.entries()){if(u.programs===void 0)throw new Error(`${Ie}: billingItems[${c}] (${u.key}) geh\xF6rt keinem Programm \u2014 "programs" nennen (die Programm-Schl\xFCssel, die den Artikel einzeln verkaufen; [] f\xFCr einen stillgelegten Artikel) oder den Artikel in ein Paket aufnehmen.`);if(u.programs!==void 0&&new Set(u.programs).size!==u.programs.length)throw new Error(`${Ie}: billingItems[${c}].programs: ein Programm steht zweimal.`)}Gk(l.map(c=>c.key),"documentTemplates");let d=pm(t.revenueAccounts??[],Ie);if(d.length+o.length+a.length+l.length===0)throw new Error(`${Ie}: die Datei deklariert nichts (${r.join(", ")}).`);return{revenueAccounts:d,billingItems:o,grantTemplates:a,documentTemplates:l}}s(A6,"parseCatalog");function zk(e){let n=Y.resolve(e);if(!Ae(n))throw new Error(`${Ie}: ${n} gibt es nicht.`);return A6(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(zk,"readCatalog");function E6(e,n){let t=Dn(e,n,Ie);return Mt(t.fields,`${n}.fields`,Ie),t}s(E6,"declaredParameters");function T6(e){return{revenueAccounts:e.revenueAccounts,billingItems:e.billingItems.map(n=>({key:n.key,name:n.name,itemType:n.itemType,revenueAccountCode:n.revenueAccount,taxTreatment:n.taxTreatment,config:n.config,price:n.price,programs:n.programs}))}}s(T6,"billingArgs");function $6(e){return{articlePrograms:e.billingItems.map(n=>({item:n.key,programs:n.programs??[]}))}}s($6,"planArgs");async function Wk(e,n,t,r=pd){let i=[],o=[],a=null;if(t.billingItems.length>0||t.revenueAccounts.length>0){a=T6(t);let u=await e.query(x.contractSetup.planBillingSetup,{client:n,...a});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail}),p.kind==="billingItem"&&p.action==="create"&&o.push(p.key)}let l=null;if(t.billingItems.length>0){l=$6(t);let u=await e.query(x.catalogPrograms.planProgramSetup,{client:n,...l,pendingItems:o});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail?.de??""});for(let p of t.billingItems)p.programs?.length===0&&i.push({step:"billingItemProgram",target:p.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(t.grantTemplates.length>0){d={grantTemplates:t.grantTemplates};let u=await e.query(x.contractSetup.planGrantSetup,{client:n,grantTemplates:t.grantTemplates,pendingItems:o});for(let p of u.rows)i.push({step:"grantTemplate",target:p.key,action:p.action,detail:p.detail})}let c=[];if(t.documentTemplates.length>0){let u=await e.query(x.templates.roleOptions,{client:n});for(let p of t.documentTemplates){let h=u.find(R=>R.key===p.role);if(h===void 0)throw new Error(`${Ie}: Vorlage ${p.key}: Rolle "${p.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(R=>R.key).join(", ")}).`);let w=await r(p.file),k=await e.query(x.templates.stateByConfigKey,{client:n,configKey:p.key});if(k!==null&&k.roleKey!==p.role)throw new Error(`${Ie}: Vorlage ${p.key} geh\xF6rt zur Rolle "${k.roleKey}", die Datei nennt "${p.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let y=k===null||k.sha256!==w.sha256,b=p.parameters!==void 0&&Pe(p.parameters)!==Pe(k?.parameters??null),E=[];k!==null&&(Is(k.name,p.name)||E.push(`Name ${k.name.de} / ${k.name.en||"\u2014"} \u2192 ${p.name.de} / ${p.name.en}`),p.icon!==void 0&&k.icon!==p.icon&&E.push(`Icon \u2192 ${p.icon}`),p.fileNamePattern!==void 0&&k.fileNamePattern!==p.fileNamePattern&&E.push("Dateinamensmuster")),c.push({declared:p,docx:w,roleId:h.id,state:k,upload:y,metadata:E,parametersChange:b});let T=b?[p.parameters===null?"Parameter entfernen":`Parameter (${p.parameters.fields.length} Felder)`]:[];i.push({step:"documentTemplate",target:p.key,action:k===null?"create":y||E.length>0||b?"update":"same",detail:k===null?[`${p.name.de} \xB7 ${Y.basename(p.file)}`,...T].join(", "):[...y?[`Datei ersetzen (${Y.basename(p.file)})`]:[],...E,...T].join(", ")})}}return{rows:i,billing:a,programs:l,grants:d,templates:c}}s(Wk,"planCatalog");async function JD(e,n,t,r=pd){let i=await Wk(e,n,t,r),o=[];if(i.billing!==null){let a=await e.mutation(x.contractSetup.applyBillingSetup,{client:n,...i.billing});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.programs!==null){let a=await e.mutation(x.catalogPrograms.applyProgramSetup,{client:n,...i.programs});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail?.de??""})}if(i.grants!==null){let a=await e.mutation(x.contractSetup.applyGrantSetup,{client:n,grantTemplates:i.grants.grantTemplates});for(let l of a.rows)o.push({step:"grantTemplate",target:l.key,action:l.action,detail:l.detail})}for(let a of i.templates){let{declared:l,state:d}=a;if(d===null)await fm(e,n,a.docx,{name:l.name,role:l.role,configKey:l.key,...l.icon===void 0?{}:{icon:l.icon},...l.fileNamePattern===void 0?{}:{fileNamePattern:l.fileNamePattern}});else if(a.upload&&await YD(e,n,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await e.mutation(x.templates.updateMetadata,{client:n,templateId:d.templateId,name:l.name,roleId:a.roleId,configKey:l.key,...c===null?{}:{icon:c},...u===null?{}:{fileNamePattern:u}})}a.parametersChange&&await e.mutation(x.templates.setParameters,{client:n,configKey:l.key,parameters:l.parameters??null}),o.push(i.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return o}s(JD,"applyCatalog");async function QD(e,n){let{unkeyed:t,...r}=await e.query(x.catalogExport.exportCatalog,{client:n});return{file:{revenueAccounts:r.revenueAccounts,billingItems:r.billingItems,grantTemplates:r.grantTemplates},unkeyed:t}}s(QD,"exportCatalog");var ZD={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},XD=["step","target","action","detail"],Yk=class extends C{static{s(this,"CatalogPlanCommand")}file=f.String("--file",ZD);static paths=[["catalog","plan"]];static usage=$.Usage({category:"Contracts",description:"Read-only: what `catalog apply` would write (revenue accounts, articles, price versions, program assignments, packages, tiers, Word templates)."});async execute(){let n=await this.caller(),t=await Wk(n,this.requireTenant(n),zk(this.file));return this.print(t.rows,r=>r,XD),0}},Hk=class extends C{static{s(this,"CatalogApplyCommand")}file=f.String("--file",ZD);static paths=[["catalog","apply"]];static usage=$.Usage({category:"Contracts",description:"Bring a catalog file onto the environment by stable key; a Word file is uploaded only when its SHA-256 differs. Idempotent."});async execute(){let n=await this.caller();return this.print(await JD(n,this.requireTenant(n),zk(this.file)),t=>t,XD),0}},Jk=class extends C{static{s(this,"CatalogExportCommand")}out=f.String("--out",{required:!0,description:"catalog.json to write (refused when it exists, unless --force)"});force=kn();static paths=[["catalog","export"]];static usage=$.Usage({category:"Contracts",description:"Read-only: write the tenant's catalog (revenue accounts, articles with price, floor and programs, packages, grant templates) as catalog.json \u2014 `catalog plan` on it reports `same` everywhere. Word templates are not exported."});async execute(){let n=Cn(this.out,this.force),t=await this.caller(),{file:r,unkeyed:i}=await QD(t,this.requireTenant(t));ze(n,`${JSON.stringify(r,null,2)}
11287
+ `,examples:[["Portal application to an offer",`$0 assignment simulate --dir ~/scratch/kindergarten-r17 --env-json '{"applicant":{"language":"de","channel":"self-service"}}'`],["The next pick of a \u201EReihum\u201C row whose last start took 'finanzen'","$0 assignment simulate --dir <bundle> --env-file env.json --rotation-previous team:finanzen=finanzen"],["A leastLoaded rotation with open-task counts","$0 assignment simulate --dir <bundle> --env-file env.json --open finanzen=3 --open finanzen_2=1"]]});dir=f.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=f.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=f.String("--env-file",{description:"\u2026or a file holding it"});creator=f.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=f.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=f.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=f.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let n=qe(this.dir),t=yN(n.workflow?.graph,`bundle ${this.dir}`),r=Z6(this.envJson,this.envFile),i=vD(t,r,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:xD("--rotation-previous",this.rotationPrevious),openCounts:Q6(this.open),left:this.left??[]});return this.print(i,o=>o.slots.map(a=>({slot:a.slot,row:`#${a.row}`,value:a.value,rotation:a.rotation===void 0?"":`${a.rotation.mode} [${a.rotation.pool.join(", ")}] after ${a.rotation.previous??"\u2014"} \u2192 ${a.rotation.picked}`}))),0}},SD=[Ik];import{createHash as X6}from"node:crypto";var Ok=/^[a-z0-9][a-z0-9-]*$/;function Ea(e){return Ok.test(e)}s(Ea,"isFileKey");function Wo(e){return e.trim()===""?"is empty":e==="."||e===".."?"is not a file name":/[/\\]/.test(e)?"must not contain a path separator":/[\u0000-\u001f]/.test(e)?"must not contain control characters":null}s(Wo,"fileNameDefect");var TD={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword",".odt":"application/vnd.oasis.opendocument.text",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png"},am={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function Ta(e){return X6("sha256").update(e).digest("hex")}s(Ta,"sha256Hex");function _k(e,n=TD){let t=Y.resolve(e),r;try{r=he(t)}catch{throw new Error(`File not found: ${e}`)}let i=n[Y.extname(t).toLowerCase()];if(i===void 0)throw new Error(`${e}: unsupported file type \u2014 allowed: ${Object.keys(n).join(", ")}.`);return{bytes:r,filename:Y.basename(t),mimeType:i,sha256:Ta(r),sizeBytes:r.length}}s(_k,"readLocalFile");var e4={tenantFile:x.tenantFiles.platformGenerateUploadUrl,brandingAsset:x.branding.platformGenerateBrandingAssetUploadUrl,brandingLogo:x.branding.platformGenerateBrandingLogoUploadUrl};async function Yo(e,n,t,r,i){let{uploadUrl:o,uploadTicket:a}=await e.mutation(e4[i],{client:n}),l=await e.upload(o,t,r);return await e.mutation(x.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}s(Yo,"uploadStaged");async function $D(e,n,t,r){return await Yo(e,n,t,r,"tenantFile")}s($D,"uploadTenantFile");function Pk(e){let n=[...e].filter(([,t])=>"fileName"in t||"size"in t).map(([t])=>t);if(n.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${n.join(", ")}: the target deployment still answers fileName / size \u2014 it runs a release from before file references. Use a plexus-cli built from that release, or wait for the next release.`)}s(Pk,"requireFileRefNames");async function fd(e,n){let t=await e.query(x.tenantFiles.platformList,{client:n});return Pk(t.map(r=>[`files["${r.key}"]`,r])),t}s(fd,"listLibrary");function RD(e,n,t,r,i){let o=_k(Y.resolve(e,n),i);if(o.mimeType!==t)throw new Error(`${r}: ${n} is ${o.mimeType}, the entry declares ${t}.`);return o}s(RD,"readSnapshotEntry");function ID(e,n){let t=new Map,r=(e.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=RD(n,d,c.mimeType,`files["${c.key}"]`,TD);return t.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),i=AD(e.tenant.brandingAssets,n,"tenant"),o=new Map,a=(e.foundation?.legalEntities??[]).map(l=>{if(l.brandingAssets===void 0)return l;let d=AD(l.brandingAssets,n,`foundation.legalEntities.${l.key}`);return o.set(l.key,d.bytes),{...l,brandingAssets:d.assets}});return{config:{...e,tenant:{...e.tenant,...i.assets!==void 0?{brandingAssets:i.assets}:{}},...e.foundation!==void 0?{foundation:{...e.foundation,legalEntities:a}}:{},files:r},bytes:t,brandingBytes:i.bytes,legalEntityBrandingBytes:o}}s(ID,"resolveSnapshotFiles");function AD(e,n,t){let r=new Map,i=e;if(i===void 0)return{assets:void 0,bytes:r};let o={};for(let[a,l]of Object.entries(i)){if(l.path===void 0){o[a]=l;continue}let{path:d,...c}=l,u=RD(n,d,c.mimeType,`${t}.brandingAssets.${a}`,am);r.set(a,u),o[a]={...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}return{assets:o,bytes:r}}s(AD,"resolveSnapshotBranding");async function OD(e,n,t,r,i){let o={},a={contents:o,changed:[],unavailable:[]};for(let l of e){if(n.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await t(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(Ta(d)!==l.sha256)throw new Error(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);i||(o[l.key]=await r(d,l.mimeType))}return a}s(OD,"stageChanged");async function _D(e,n,t,r,i){let o=new Map(Object.entries(await e.query(x.tenantFiles.platformFileHashes,{client:n})??{})),a=new Map(t.map(l=>[l.key,l]));return await OD(t.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),o,l=>r(a.get(l)),(l,d)=>Yo(e,n,l,d,"tenantFile"),i)}s(_D,"stageFileContents");function PD(e){return e===void 0?"tenant":`foundation.legalEntities.${e}`}s(PD,"brandingHolder");async function lm(e,n,t){let r=await e.query(x.branding.platformBrandingAssets,{client:n,...t!==void 0?{legalEntity:t}:{}});return Pk(Object.entries(r??{}).map(([i,o])=>[`${PD(t)}.brandingAssets.${i}`,o])),r}s(lm,"listBrandingAssets");async function Nk(e,n,t,r,i,o){let a=new Map(Object.entries(await lm(e,n,o)??{}).map(([d,c])=>[d,c.sha256])),l=PD(o);return await OD(Object.entries(t??{}).map(([d,c])=>({key:d,sha256:c.sha256,mimeType:c.mimeType,at:`${l}.brandingAssets.${d}`})),a,r,(d,c)=>Yo(e,n,d,c,"brandingAsset"),i)}s(Nk,"stageBrandingAssets");async function ND(e,n,t,r){if(e===null||n===void 0)throw new Error(`${t}: its stored object is gone \u2014 ${r}`);let i=await fetch(e);if(!i.ok)throw new Error(`download of ${t} failed (${i.status}).`);let o=new Uint8Array(await i.arrayBuffer());if(Ta(o)!==n)throw new Error(`download of ${t} does not match its sha256 ${n}.`);return o}s(ND,"downloadVerified");async function Ck(e){return await ND(e.url,e.sha256,`"${e.key}"`,"replace it with `files put` first.")}s(Ck,"downloadLibraryFile");async function Dk(e,n,t){return await ND(n.url,n.sha256,t===void 0?`branding/${e}`:`branding/${t}/${e}`,"upload it again with `branding set-logo` / `branding set-font` first.")}s(Dk,"downloadBrandingAsset");function n4(e,n,t){let r=Object.keys(am).find(i=>am[i]===n);if(r===void 0)throw new Error(`export: branding/${e} is ${n}, which a snapshot cannot name (${Object.keys(am).join(", ")}).`);if(t===void 0)return Y.join("branding",`${e}${r}`);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t))throw new Error(`export: legal entity key "${t}" is not a safe directory name for its brand files.`);return Y.join("branding",t,`${e}${r}`)}s(n4,"brandingAssetPath");function CD(e,n,t){let r=Y.join(e,n);Ln(Y.dirname(r),{recursive:!0}),ze(r,t)}s(CD,"writeBeside");async function DD(e,n,t,r){Pk([...t.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(t.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u]),...(t.foundation?.legalEntities??[]).flatMap(c=>Object.entries(c.brandingAssets??{}).map(([u,p])=>[`foundation.legalEntities.${c.key}.brandingAssets.${u}`,p]))]);let i=new Map((await fd(e,n)).map(c=>[c.key,c])),o=Y.dirname(r),a=[];for(let c of t.files){let u=i.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let p=Wo(c.filename);if(p!==null||!Ea(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${p??"bad key"}).`);let h=Y.join("files",c.key,c.filename);CD(o,h,await Ck(u)),a.push({...c,path:h})}let l=await ED(e,n,t.tenant.brandingAssets,o,void 0),d=[];for(let c of t.foundation?.legalEntities??[]){if(c.brandingAssets===void 0){d.push(c);continue}d.push({...c,brandingAssets:await ED(e,n,c.brandingAssets,o,c.key)})}return{...t,tenant:{...t.tenant,...l!==void 0?{brandingAssets:l}:{}},...t.foundation!==void 0?{foundation:{...t.foundation,legalEntities:d}}:{},files:a}}s(DD,"writeSnapshotFiles");async function ED(e,n,t,r,i){if(t===void 0)return;let o=await lm(e,n,i)??{},a={};for(let[l,d]of Object.entries(t)){let c=o[l],u=n4(l,d.mimeType,i);if(c===void 0||c.sha256!==d.sha256)throw new Error(`export: ${u} changed between two reads \u2014 rerun.`);CD(r,u,await Dk(l,c,i)),a[l]={...d,path:u}}return a}s(ED,"writeSnapshotBranding");var t4={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function FD(e){return t4[Y.extname(e).toLowerCase()]}s(FD,"guessImageContentType");async function r4(e,n){if(e===void 0==(n===void 0))throw new Error("Pass exactly one of --file <path> or --url <url>.");if(n!==void 0&&cn())throw new Error("Hosted agents cannot fetch arbitrary logo URLs. Upload the image to the chat and use --file <path>.");if(e!==void 0){let a=Y.resolve(e),l;try{l=he(a)}catch{throw new Error(`File not found: ${e}`)}let d=FD(a);if(d===void 0)throw new Error(`Cannot infer an image content-type from "${Y.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let t=await fetch(n);if(!t.ok)throw new Error(`Fetch failed for ${n} (${t.status} ${t.statusText}).`);let r=new Uint8Array(await t.arrayBuffer()),i=t.headers.get("content-type")?.split(";")[0]?.trim(),o=i&&i.startsWith("image/")?i:FD(new URL(n).pathname);if(o===void 0)throw new Error(`Response for ${n} is not an image (content-type "${i??"unknown"}").`);return{bytes:r,contentType:o}}s(r4,"loadLogoBytes");function $a(){return f.String("--legal-entity",{description:"A legal entity's config key \u2014 its own brand, which overrides the tenant's for its units"})}s($a,"legalEntityOption");function Ra(e){return e===void 0?{}:{legalEntity:e}}s(Ra,"ownerArgs");async function i4(e,n,t,r){return await Yo(e,n,t,r,"brandingLogo")}s(i4,"uploadLogo");var Fk=class extends C{static{s(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=$.Usage({category:"Branding",description:"Upload a tenant's portal logo",details:"Sets the external-portal logo for --tenant from a local --file or a remote --url. A one-off upload without the tenant's Branding admin UI. To move the logo with the rest of the config (export \u2192 apply, env \u2192 env), use `config apply` \u2014 it carries the file by hash (`tenant.brandingAssets.logo`).",examples:[["Upload the test tenant's logo to staging from a file","$0 --env staging --tenant test branding set-logo --file logo.png"],["Upload from an S3 URL","$0 --env staging --tenant test branding set-logo --url https://s3.example/logo.png"],["Upload a Tr\xE4ger's own logo (its units' portal pages and letters wear it)","$0 --env staging --tenant test branding set-logo --legal-entity test_seminare --file seminare.png"]]});file=f.String("--file",{description:"Local image file to upload"});url=f.String("--url",{description:"Fetch the logo image from this URL"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),{bytes:r,contentType:i}=await r4(this.file,this.url),o=await i4(n,t,r,i);return await n.mutation(x.branding.platformSetBrandingLogo,{client:t,...Ra(this.legalEntity),slot:"primary",storageId:o}),this.print({tenant:t,slot:"primary",contentType:i,bytes:r.length,storageId:o},a=>[{field:"tenant",value:a.tenant},{field:"slot",value:a.slot},{field:"contentType",value:a.contentType},{field:"bytes",value:String(a.bytes)},{field:"storageId",value:a.storageId}]),0}},Lk=class extends C{static{s(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=$.Usage({category:"Branding",description:"Remove a tenant's portal logo"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n);return await n.mutation(x.branding.platformClearBrandingLogo,{client:t,...Ra(this.legalEntity),slot:"primary"}),this.print({tenant:t,slot:"primary",cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}};function LD(e){if(e!=="heading"&&e!=="body")throw new Error(`branding: --slot must be heading or body (got "${e}")`);return e}s(LD,"parseFontSlot");var Mk=class extends C{static{s(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=$.Usage({category:"Branding",description:"Upload a tenant's portal font file (WOFF2) for a slot",details:"Uploads --file as the font of --slot (heading|body). The backend checks the WOFF2 signature and the 2 MB cap and applies the file under the slot's configured family (`fonts.<slot>.family` \u2014 set it first with `branding set-theme` or `config apply`). A replaced file is deleted. `config apply` carries font files by hash too (`tenant.brandingAssets.fontHeading|fontBody`).",examples:[["Upload the test tenant's heading font to staging","$0 --env staging --tenant test branding set-font --slot heading --file heading.woff2"]]});slot=f.String("--slot",{required:!0,description:"heading | body"});file=f.String("--file",{required:!0,description:"Local .woff2 file"});legalEntity=$a();async execute(){let n=LD(this.slot),t=Y.resolve(this.file),r;try{r=he(t)}catch{throw new Error(`File not found: ${this.file}`)}let i=await this.caller(),o=this.requireTenant(i),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),{storageId:l}=await i.action(x.brandingFonts.platformSetBrandingFont,{client:o,...Ra(this.legalEntity),slot:n,bytes:a});return this.print({tenant:o,slot:n,bytes:r.length,storageId:l},d=>[{field:"tenant",value:d.tenant},{field:"slot",value:d.slot},{field:"bytes",value:String(d.bytes)},{field:"storageId",value:d.storageId}]),0}},qk=class extends C{static{s(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=$.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (the family stays)"});slot=f.String("--slot",{required:!0,description:"heading | body"});legalEntity=$a();async execute(){let n=LD(this.slot),t=await this.caller(),r=this.requireTenant(t);return await t.mutation(x.branding.platformClearBrandingFont,{client:r,...Ra(this.legalEntity),slot:n}),this.print({tenant:r,slot:n,cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}},Kk=class extends C{static{s(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=$.Usage({category:"Branding",description:"Set a tenant's portal theme tokens from a JSON file",details:"Replaces the branding THEME (colors/radius/logoSize/bannerDensity/filledHeader/websiteUrl/font families) wholesale from --file. Does NOT touch the uploaded logo or font files (see `branding set-logo` / `branding set-font`). The same brand tokens `config apply` writes, but surgical \u2014 it touches only branding, not the rest of the tenant config.",examples:[["Apply the test tenant's theme to staging","$0 --env staging --tenant test branding set-theme --file theme.json"],["Give a Tr\xE4ger its own theme (replaces the tenant's brand as a block for its units)","$0 --env staging --tenant test branding set-theme --legal-entity test_seminare --file seminare.json"]]});file=f.String("--file",{required:!0,description:"Branding theme JSON"});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Y.resolve(this.file),i;try{i=JSON.parse(he(r,"utf8"))}catch(o){throw new Error(`Cannot read branding JSON ${this.file}: ${xt(o)}`,{cause:o})}return await n.mutation(x.branding.platformUpdateBranding,{client:t,...Ra(this.legalEntity),branding:i}),this.print({tenant:t,applied:!0},o=>[{field:"tenant",value:o.tenant},{field:"applied",value:String(o.applied)}]),0}},jk=class extends C{static{s(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=$.Usage({category:"Branding",description:"Show a tenant's current branding + resolved logo and font-file URLs",details:"With --legal-entity <key>, that Tr\xE4ger's own brand \u2014 `branding: null` and no files means it has none, and its units wear the next brand up (a parent Tr\xE4ger's, else the tenant's)."});legalEntity=$a();async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.branding.platformGetBranding,{client:t,...Ra(this.legalEntity)});return this.print(r),0}},MD=[jk,Kk,Fk,Lk,Mk,qk];var Ia=s(()=>f.String("--output",{hidden:!0}),"retiredOutputOption"),kn=s(()=>f.Boolean("--force",!1,{description:"Overwrite an existing --out file."}),"forceOption");function Oa(e){if(e.retiredOutput===void 0)return e.out;if(e.out!==void 0&&e.out!==e.retiredOutput)throw new Oe(`--out "${e.out}" and --output "${e.retiredOutput}" disagree \u2014 pass only --out.`);return ln(e.context.stderr,"--output","--out"),e.retiredOutput}s(Oa,"resolveOut");function Cn(e,n){let t=Y.resolve(e);if(Ae(t)&&!n)throw new Oe(`${t} exists \u2014 pick another --out or pass --force.`);return t}s(Cn,"assertOutFree");function o4(e){try{return Cr(e)}catch{throw new Oe(`${e} is not a directory \u2014 --out names a directory here.`)}}s(o4,"entriesOf");function Vk(e,n){let t=Y.resolve(e);if(Ae(t)&&o4(t).length>0&&!n)throw new Oe(`${t} is not empty \u2014 pick another --out or pass --force.`);return t}s(Vk,"assertOutDirFree");function qD(e,n,t){let r=Cn(e,t),i=n.map(o=>Y.join(Y.dirname(r),o)).filter(o=>Ae(o));if(i.length>0&&!t)throw new Oe(`${i.join(", ")} exist(s) beside --out \u2014 pick another directory or pass --force.`);return r}s(qD,"assertSnapshotOutFree");function dm(e){(!Number.isSafeInteger(e)||e<0)&&ae("INVALID",{de:"Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.",en:"Amounts must be non-negative whole amounts in cents."})}s(dm,"assertMoney");var Bk=["month","year","once","unit"];var s4=s(e=>e!==void 0&&/^[1-9]\d{0,8}$/.test(e),"positiveIntegerText");function wi(e,n){return ae("CONFLICT",{de:e,en:n})}s(wi,"missing");var KD=s(e=>e!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(e)&&Number.isFinite(new Date(`${e}T00:00:00Z`).valueOf())&&new Date(`${e}T00:00:00Z`).toISOString().slice(0,10)===e,"isoDate");function jD(e,n,t){return{label:n,kind:"chosen",valueType:"choice",choices:t,resolve(r){let i=r.selections?.[e];return(!i||!t.includes(i))&&wi(`Die Auswahl f\xFCr \u201E${n.de}\u201C fehlt oder ist ung\xFCltig.`,`The selection for \u201C${n.en}\u201D is missing or invalid.`),{value:i,explanation:{de:`${n.de}: ${i} (Vertragsauswahl)`,en:`${n.en}: ${i} (contract selection)`}}}}}s(jD,"chosen");function Uk(e,n){let t=e.enrollment,r=t?.contextDate??n;return(!t||!t.startDate||t.startDate>r||t.endDate&&t.endDate<r)&&wi("F\xFCr dieses Datum fehlt eine eindeutige Einschreibung.","An unambiguous enrollment is missing for this date."),t}s(Uk,"enrollment");var a4={paymentFrequency:jD("paymentFrequency",{de:"Zahlungsweise",en:"Payment frequency"},["monthly","yearly"]),gradeLevel:{label:{de:"Klassenstufe",en:"Grade level"},kind:"derived",valueType:"integer",resolve(e,n){let t=Uk(e,n).gradeLevel;return(!Number.isSafeInteger(t)||t<1)&&wi("Die Klassenstufe fehlt.","The grade level is missing."),{value:t,explanation:{de:`Klassenstufe ${t} am ${n}`,en:`Grade ${t} on ${n}`}}}},schoolYear:{label:{de:"Schuljahr",en:"School year"},kind:"derived",valueType:"integer",resolve(e,n){let t=Uk(e,n).schoolYear;return(!Number.isSafeInteger(t)||t<1)&&wi("F\xFCr dieses Datum fehlt ein j\xE4hrlicher Schuljahreslauf.","An annual school-year run is missing for this date."),{value:t,explanation:{de:`Schuljahr ${t}/${t+1}`,en:`School year ${t}/${t+1}`}}}},siblingRank:{label:{de:"Geschwisterrang",en:"Sibling rank"},kind:"derived",valueType:"integer",resolve(e,n){if(e.chosenCriteria?.includes("siblingRank")){let c=e.selections?.siblingRank;return s4(c)||wi("Der im Vertrag gew\xE4hlte Geschwisterrang fehlt oder ist keine ganze Zahl ab 1.","The sibling rank chosen on the contract is missing or not a whole number from 1."),{value:Number(c),explanation:{de:`Geschwisterrang ${c} (im Vertrag gew\xE4hlt)`,en:`Sibling rank ${c} (chosen on the contract)`}}}e.unavailable?.siblingRank&&ae("CONFLICT",e.unavailable.siblingRank);let t=e.siblings?[...new Map(e.siblings.filter(c=>c.eligible).map(c=>[c.partyId,c])).values()]:void 0;(!e.partyId||!t?.some(c=>c.partyId===e.partyId))&&wi("F\xFCr dieses Datum fehlt die Sch\xFClerrolle des Kindes.","The child\u2019s Student role is missing for this date."),t.some(c=>!KD(c.firstEnrolledOn)||c.firstEnrolledOn>n)&&wi("F\xFCr den Geschwisterrang fehlt ein g\xFCltiger erster Einschreibungsbeginn.","A valid first enrollment start is missing for sibling ranking.");let r=t.find(c=>c.partyId===e.partyId),i=r.firstEnrolledOn,o=t.filter(c=>c.firstEnrolledOn===i);o.length>1&&o.some(c=>!KD(c.birthDate)||c.birthDate>n)&&wi("Geschwister wurden am selben Tag erstmals eingeschrieben, und f\xFCr die Reihenfolge fehlt ein g\xFCltiges Geburtsdatum.","Siblings first enrolled on the same day, and a valid birth date is missing to order them.");let a=s(c=>c.birthDate<r.birthDate||c.birthDate===r.birthDate&&c.partyId<r.partyId,"before"),l=t.filter(c=>c.firstEnrolledOn<i).length+o.filter(c=>c!==r&&a(c)).length+1,d=o.length>1?{de:`; gleicher Beginn wie ${o.length-1} Geschwister: \xE4lteste zuerst, bei gleichem Geburtsdatum nach Personen-ID`,en:`; same start as ${o.length-1} sibling${o.length>2?"s":""}: oldest first, then party ID for equal birth dates`}:{de:"",en:""};return{value:l,explanation:{de:`${l}. Kind von ${t.length} berechtigten Kindern am ${n}; erste Einschreibung am ${i}, zuerst eingeschriebene Kinder zuerst${d.de}.`,en:`Child ${l} of ${t.length} eligible children on ${n}; first enrollment on ${i}, first enrolled first${d.en}.`}}}},program:{label:{de:"Programm",en:"Program"},kind:"derived",valueType:"program",resolve(e,n){let t=Uk(e,n).programId;return t||wi("Das Programm fehlt.","The program is missing."),{value:t,explanation:{de:`Programm der Einschreibung am ${n}`,en:`Enrollment program on ${n}`}}}},admissionFeeTier:jD("admissionFeeTier",{de:"Anmeldegeb\xFChrensatz",en:"Admission fee tier"},["100","75","50"])},l4=Object.fromEntries(Object.entries(a4).map(([e,n])=>[e,{...n,matchSchema:{parse(t){return c4(n,t),t}},matches:d4}])),fxe=Object.keys(l4);function d4(e,n){return"else"in n?!0:"eq"in n?e===n.eq:"in"in n?n.in.includes(e):typeof e=="number"&&(n.gte===void 0||e>=n.gte)&&(n.lte===void 0||e<=n.lte)}s(d4,"matchesPrice");function c4(e,n){let t=s(()=>ae("INVALID",{de:"Der Match passt nicht zum Preiskriterium.",en:"The match does not fit the price criterion."}),"fail");if(!n||typeof n!="object"||Array.isArray(n))return t();let r=n,i=Object.keys(r).sort().join();if(i==="else"&&r.else===!0)return;let o=s(a=>e.valueType==="integer"?Number.isSafeInteger(a)&&Number(a)>=1:typeof a=="string"&&a.length>0&&(e.valueType!=="choice"||e.choices.includes(a)),"validValue");if(!(i==="eq"&&o(r.eq))&&!(i==="in"&&Array.isArray(r.in)&&r.in.length>0&&new Set(r.in).size===r.in.length&&r.in.every(o))&&!(e.valueType==="integer"&&["gte","lte","gte,lte"].includes(i)&&Object.values(r).every(a=>Number.isSafeInteger(a)&&Number(a)>=1)&&(r.gte===void 0||r.lte===void 0||Number(r.gte)<=Number(r.lte))))return t()}s(c4,"validateMatch");function VD(e,n){if(Object.keys(n).some(t=>!["percent","amountMinor"].includes(t))&&ae("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."}),e==="percent"&&"percent"in n&&!("amountMinor"in n)){(!Number.isFinite(n.percent)||n.percent<0||n.percent>100)&&ae("INVALID",{de:"Prozentwerte m\xFCssen zwischen 0 und 100 liegen.",en:"Percentages must be between 0 and 100."});return}if(e==="absolute"&&"amountMinor"in n&&!("percent"in n))return dm(n.amountMinor);ae("INVALID",{de:"Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.",en:"The reduction needs exactly one percentage rule or one amount in cents."})}s(VD,"validateRule");var u4=/^[a-z][a-z0-9_-]{0,63}$/;function BD(e){return u4.test(e)}s(BD,"isTemplateConfigKey");import{createHash as y4}from"node:crypto";import{inflateRawSync as w4}from"node:zlib";var UD=/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/,f4=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,p4=/^[#/]\s*/;function m4(e){let n=e.trim(),t=n.match(/^{{\s*([^{}]+?)\s*}}$/);if(t)return t[1]?.trim()??n;let r=n.match(/^<<\s*([^<>]+?)\s*>>$/);return r?r[1]?.trim()??n:n}s(m4,"innerTemplatePlaceholder");function cm(e){return m4(e).replace(p4,"")}s(cm,"normalizeTemplatePlaceholderKey");function um(e){return cm(e).toLowerCase()}s(um,"canonicalTemplatePlaceholderKey");function GD(e){let n=new Map;for(let t of h4(e))n.has(t.key)||n.set(t.key,t.placeholder);return Array.from(n.entries()).sort(([t],[r])=>t.localeCompare(r,"de")).map(([,t])=>t)}s(GD,"extractTemplatePlaceholders");function h4(e){let n=[];for(let t of e.matchAll(f4)){let r=cm(t[1]??t[2]??"");r&&n.push({key:um(r),placeholder:t[0].trim()})}return n}s(h4,"extractTemplatePlaceholderOccurrences");var zD=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function g4(e){return e.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(n,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-f]+);/gi,(n,t)=>String.fromCodePoint(parseInt(t,16))).replace(/&amp;/g,"&")}s(g4,"templateXmlText");function WD(e){return e.map(g4).join(`
11288
+ `)}s(WD,"templateTextFromParts");var k4="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function pd(e){let n=Y.resolve(e);if(!n.toLowerCase().endsWith(".docx"))throw new Error("Word templates must be a .docx file.");let t=new Uint8Array(await zt(n));return{file:n,bytes:t,sha256:y4("sha256").update(t).digest("base64"),placeholders:GD(b4(t)).map(cm)}}s(pd,"readLocalDocx");async function fm(e,n,t,r){let i=await e.query(x.templates.roleOptions,{client:n}),o=i.find(d=>d.key===r.role);if(o===void 0)throw new Error(`Unknown leaf role "${r.role}". Available: ${i.map(d=>d.key).join(", ")}`);let a=await HD(e,n,t),{templateId:l}=await e.action(x.templateFileActions.create,{client:n,name:r.name,roleId:o.id,storageId:a,filename:Y.basename(t.file),...r.configKey===void 0?{}:{configKey:r.configKey},...r.icon===void 0?{}:{icon:r.icon},...r.fileNamePattern===void 0?{}:{fileNamePattern:r.fileNamePattern}});return l}s(fm,"uploadDocumentTemplate");async function YD(e,n,t,r){let i=await HD(e,n,r);await e.action(x.templateFileActions.replaceFile,{client:n,templateId:t,storageId:i,filename:Y.basename(r.file)})}s(YD,"replaceDocumentTemplateFile");async function HD(e,n,t){let{uploadUrl:r,uploadTicket:i}=await e.mutation(x.templates.generateUploadUrl,{client:n}),o=await e.upload(r,t.bytes,k4);return await e.mutation(x.uploads.registerUpload,{uploadTicket:i,storageId:o}),o}s(HD,"stageDocx");function b4(e){let n=v4(e,t=>zD.test(t));if(!n.has("word/document.xml"))throw new Error("word/document.xml not found \u2014 the file is not a readable .docx.");return WD([...n.values()])}s(b4,"docxPlaceholderText");function v4(e,n){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new Error("No ZIP central directory \u2014 the file is not a readable .docx."),i=-1;for(let d=e.length-22;d>=Math.max(0,e.length-22-65535);d--)if(t.getUint32(d,!0)===101010256){i=d;break}if(i<0)throw r;let o=t.getUint16(i+10,!0),a=t.getUint32(i+16,!0),l=new Map;for(let d=0;d<o;d++){if(a+46>e.length||t.getUint32(a,!0)!==33639248)throw r;let c=t.getUint16(a+10,!0),u=t.getUint32(a+20,!0),p=t.getUint16(a+28,!0),h=t.getUint16(a+30,!0),w=t.getUint16(a+32,!0),k=t.getUint32(a+42,!0),y=new TextDecoder().decode(e.subarray(a+46,a+46+p));if(a+=46+p+h+w,!n(y))continue;if(t.getUint32(k,!0)!==67324752)throw r;let b=k+30+t.getUint16(k+26,!0)+t.getUint16(k+28,!0),E=Buffer.from(e.subarray(b,b+u));l.set(y,(c===0?E:w4(E)).toString("utf8"))}return l}s(v4,"readZipEntries");function Dn(e,n,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t}: ${n} muss ein Objekt sein.`);return e}s(Dn,"record");function Ge(e,n,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t}: ${n} fehlt.`);return e.trim()}s(Ge,"text");function gt(e,n,t,r){let i=In(e);if(i==="not-localized"){let a=typeof e=="string"&&e.trim()!==""?e.trim():"\u2026";throw new Error(`${t}: ${n}: erwartet { "de": "\u2026", "en": "\u2026" } (${r} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(i.length>0)throw new Error(`${t}: ${n}.${i.join(` und ${n}.`)} ${i.length>1?"fehlen":"fehlt"} (${r} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let o=e;return{de:o.de.trim(),en:o.en.trim()}}s(gt,"localizedName");function Mt(e,n,t){if(!Array.isArray(e))throw new Error(`${t}: ${n} muss eine Liste sein.`);return e}s(Mt,"list");function pm(e,n){return Mt(e,"revenueAccounts",n).map((t,r)=>{let i=Dn(t,`revenueAccounts[${r}]`,n);return{code:Ge(i.code,`revenueAccounts[${r}].code`,n),name:Ge(i.name,`revenueAccounts[${r}].name`,n)}})}s(pm,"parseRevenueAccounts");function mm(e,n){return Mt(e,"billingItems",n).map((t,r)=>{let i=`billingItems[${r}]`,o=Dn(t,i,n),a=Ge(o.itemType,`${i}.itemType`,n),l=Ge(o.taxTreatment,`${i}.taxTreatment`,n);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new Error(`${n}: ${i}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new Error(`${n}: ${i}.itemType "${a}" ist unbekannt.`);if(o.minAmount!==void 0)throw new Error(`${n}: ${i}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=Dn(o.price,`${i}.price`,n),c=d.effectiveFrom===void 0?{}:{effectiveFrom:Ge(d.effectiveFrom,`${i}.price.effectiveFrom`,n)},u=Ge(d.currency,`${i}.price.currency`,n),p=d.tree===void 0?(()=>{let h=Ge(d.period,`${i}.price.period`,n);if(!["month","year","once","unit"].includes(h))throw new Error(`${n}: ${i}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new Error(`${n}: ${i}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:Dn(d.tree,`${i}.price.tree`,n),...c}})();return{key:Ge(o.key,`${i}.key`,n),name:gt(o.name,`${i}.name`,n,"Artikelnamen"),itemType:a,revenueAccount:Ge(o.revenueAccount,`${i}.revenueAccount`,n),taxTreatment:l,config:Dn(o.config??{},`${i}.config`,n),...o.programs===void 0?{}:{programs:Mt(o.programs,`${i}.programs`,n).map((h,w)=>Ge(h,`${i}.programs[${w}]`,n))},price:p}})}s(mm,"parseBillingItems");var Ie="catalog",x4=["sibling","stipend","promo","needsBased","singleParent"],S4=["percent","absolute"];function Gk(e,n){let t=new Set;for(let r of e){if(t.has(r))throw new Error(`${Ie}: ${n}: Schl\xFCssel "${r}" steht zweimal in der Datei.`);t.add(r)}}s(Gk,"uniqueKeys");function hm(e,n,t){if(!n.includes(e))throw new Error(`${Ie}: ${t} "${e}" ist unbekannt (${n.join(", ")}).`);return e}s(hm,"oneOf");function A4(e,n){let t=Dn(e,"Datei",Ie);if(t.plans!==void 0)throw new Error("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let r=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],i=Object.keys(t).filter(c=>!r.includes(c));if(i.length>0)throw new Error(`${Ie}: unbekannte Abschnitte ${i.join(", ")} (erlaubt: ${r.join(", ")}).`);let o=mm(t.billingItems??[],Ie).map((c,u)=>{let p=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new Error(`${Ie}: ${p}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new Error(`${Ie}: ${p}.effectiveFrom fehlt \u2014 der erste Tag, ab dem der Preis gilt (YYYY-MM-DD).`);return{...c,price:"tree"in c.price?{currency:c.price.currency,tree:c.price.tree,effectiveFrom:c.price.effectiveFrom}:{currency:c.price.currency,amount:c.price.amount,effectiveFrom:c.price.effectiveFrom,period:c.price.period}}}),a=Mt(t.grantTemplates??[],"grantTemplates",Ie).map((c,u)=>{let p=`grantTemplates[${u}]`,h=Dn(c,p,Ie);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new Error(`${Ie}: ${p}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new Error(`${Ie}: ${p}.retroactiveRevocation muss true oder false sein.`);let w=hm(Ge(h.scope,`${p}.scope`,Ie),["line","aggregate"],`${p}.scope`),k=hm(Ge(h.kind,`${p}.kind`,Ie),S4,`${p}.kind`),y=Dn(h.rule,`${p}.rule`,Ie);VD(k,y);let b=hm(Ge(h.pricePeriod,`${p}.pricePeriod`,Ie),["month","year","once","unit"],`${p}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||w!=="aggregate")throw new Error(`${Ie}: ${p}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);dm(h.floorTotal)}let E=Mt(h.eligibleItems,`${p}.eligibleItems`,Ie).map((T,R)=>Ge(T,`${p}.eligibleItems[${R}]`,Ie));if(E.length===0||new Set(E).size!==E.length)throw new Error(`${Ie}: ${p}.eligibleItems braucht eindeutige Artikel.`);return{key:Ge(h.key,`${p}.key`,Ie),name:gt(h.name,`${p}.name`,Ie,"Erm\xE4\xDFigungsnamen"),eligibleItems:E,scope:w,rule:y,pricePeriod:b,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:Ge(h.offeredFrom,`${p}.offeredFrom`,Ie)},...h.offeredUntil===void 0?{}:{offeredUntil:Ge(h.offeredUntil,`${p}.offeredUntil`,Ie)},reason:hm(Ge(h.reason,`${p}.reason`,Ie),x4,`${p}.reason`),kind:k,eligibility:Dn(h.eligibility,`${p}.eligibility`,Ie),retroactiveRevocation:h.retroactiveRevocation}}),l=Mt(t.documentTemplates??[],"documentTemplates",Ie).map((c,u)=>{let p=`documentTemplates[${u}]`,h=Dn(c,p,Ie),w=Ge(h.key,`${p}.key`,Ie);if(!BD(w))throw new Error(`${Ie}: ${p}.key "${w}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let k=Y.resolve(n,Ge(h.file,`${p}.file`,Ie));if(!k.toLowerCase().endsWith(".docx"))throw new Error(`${Ie}: ${p}.file muss eine .docx sein.`);return{key:w,name:gt(h.name,`${p}.name`,Ie,"Vorlagennamen"),file:k,role:Ge(h.role,`${p}.role`,Ie),...h.icon===void 0?{}:{icon:Ge(h.icon,`${p}.icon`,Ie)},...h.fileNamePattern===void 0?{}:{fileNamePattern:Ge(h.fileNamePattern,`${p}.fileNamePattern`,Ie)},...h.parameters===void 0?{}:{parameters:h.parameters===null?null:E4(h.parameters,`${p}.parameters`)}}});Gk(o.map(c=>c.key),"billingItems"),Gk(a.map(c=>c.key),"grantTemplates");for(let[c,u]of o.entries()){if(u.programs===void 0)throw new Error(`${Ie}: billingItems[${c}] (${u.key}) geh\xF6rt keinem Programm \u2014 "programs" nennen (die Programm-Schl\xFCssel, die den Artikel einzeln verkaufen; [] f\xFCr einen stillgelegten Artikel) oder den Artikel in ein Paket aufnehmen.`);if(u.programs!==void 0&&new Set(u.programs).size!==u.programs.length)throw new Error(`${Ie}: billingItems[${c}].programs: ein Programm steht zweimal.`)}Gk(l.map(c=>c.key),"documentTemplates");let d=pm(t.revenueAccounts??[],Ie);if(d.length+o.length+a.length+l.length===0)throw new Error(`${Ie}: die Datei deklariert nichts (${r.join(", ")}).`);return{revenueAccounts:d,billingItems:o,grantTemplates:a,documentTemplates:l}}s(A4,"parseCatalog");function zk(e){let n=Y.resolve(e);if(!Ae(n))throw new Error(`${Ie}: ${n} gibt es nicht.`);return A4(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(zk,"readCatalog");function E4(e,n){let t=Dn(e,n,Ie);return Mt(t.fields,`${n}.fields`,Ie),t}s(E4,"declaredParameters");function T4(e){return{revenueAccounts:e.revenueAccounts,billingItems:e.billingItems.map(n=>({key:n.key,name:n.name,itemType:n.itemType,revenueAccountCode:n.revenueAccount,taxTreatment:n.taxTreatment,config:n.config,price:n.price,programs:n.programs}))}}s(T4,"billingArgs");function $4(e){return{articlePrograms:e.billingItems.map(n=>({item:n.key,programs:n.programs??[]}))}}s($4,"planArgs");async function Wk(e,n,t,r=pd){let i=[],o=[],a=null;if(t.billingItems.length>0||t.revenueAccounts.length>0){a=T4(t);let u=await e.query(x.contractSetup.planBillingSetup,{client:n,...a});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail}),p.kind==="billingItem"&&p.action==="create"&&o.push(p.key)}let l=null;if(t.billingItems.length>0){l=$4(t);let u=await e.query(x.catalogPrograms.planProgramSetup,{client:n,...l,pendingItems:o});for(let p of u.rows)i.push({step:p.kind,target:p.key,action:p.action,detail:p.detail?.de??""});for(let p of t.billingItems)p.programs?.length===0&&i.push({step:"billingItemProgram",target:p.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(t.grantTemplates.length>0){d={grantTemplates:t.grantTemplates};let u=await e.query(x.contractSetup.planGrantSetup,{client:n,grantTemplates:t.grantTemplates,pendingItems:o});for(let p of u.rows)i.push({step:"grantTemplate",target:p.key,action:p.action,detail:p.detail})}let c=[];if(t.documentTemplates.length>0){let u=await e.query(x.templates.roleOptions,{client:n});for(let p of t.documentTemplates){let h=u.find(R=>R.key===p.role);if(h===void 0)throw new Error(`${Ie}: Vorlage ${p.key}: Rolle "${p.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(R=>R.key).join(", ")}).`);let w=await r(p.file),k=await e.query(x.templates.stateByConfigKey,{client:n,configKey:p.key});if(k!==null&&k.roleKey!==p.role)throw new Error(`${Ie}: Vorlage ${p.key} geh\xF6rt zur Rolle "${k.roleKey}", die Datei nennt "${p.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let y=k===null||k.sha256!==w.sha256,b=p.parameters!==void 0&&Pe(p.parameters)!==Pe(k?.parameters??null),E=[];k!==null&&(Is(k.name,p.name)||E.push(`Name ${k.name.de} / ${k.name.en||"\u2014"} \u2192 ${p.name.de} / ${p.name.en}`),p.icon!==void 0&&k.icon!==p.icon&&E.push(`Icon \u2192 ${p.icon}`),p.fileNamePattern!==void 0&&k.fileNamePattern!==p.fileNamePattern&&E.push("Dateinamensmuster")),c.push({declared:p,docx:w,roleId:h.id,state:k,upload:y,metadata:E,parametersChange:b});let T=b?[p.parameters===null?"Parameter entfernen":`Parameter (${p.parameters.fields.length} Felder)`]:[];i.push({step:"documentTemplate",target:p.key,action:k===null?"create":y||E.length>0||b?"update":"same",detail:k===null?[`${p.name.de} \xB7 ${Y.basename(p.file)}`,...T].join(", "):[...y?[`Datei ersetzen (${Y.basename(p.file)})`]:[],...E,...T].join(", ")})}}return{rows:i,billing:a,programs:l,grants:d,templates:c}}s(Wk,"planCatalog");async function JD(e,n,t,r=pd){let i=await Wk(e,n,t,r),o=[];if(i.billing!==null){let a=await e.mutation(x.contractSetup.applyBillingSetup,{client:n,...i.billing});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.programs!==null){let a=await e.mutation(x.catalogPrograms.applyProgramSetup,{client:n,...i.programs});for(let l of a.rows)o.push({step:l.kind,target:l.key,action:l.action,detail:l.detail?.de??""})}if(i.grants!==null){let a=await e.mutation(x.contractSetup.applyGrantSetup,{client:n,grantTemplates:i.grants.grantTemplates});for(let l of a.rows)o.push({step:"grantTemplate",target:l.key,action:l.action,detail:l.detail})}for(let a of i.templates){let{declared:l,state:d}=a;if(d===null)await fm(e,n,a.docx,{name:l.name,role:l.role,configKey:l.key,...l.icon===void 0?{}:{icon:l.icon},...l.fileNamePattern===void 0?{}:{fileNamePattern:l.fileNamePattern}});else if(a.upload&&await YD(e,n,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await e.mutation(x.templates.updateMetadata,{client:n,templateId:d.templateId,name:l.name,roleId:a.roleId,configKey:l.key,...c===null?{}:{icon:c},...u===null?{}:{fileNamePattern:u}})}a.parametersChange&&await e.mutation(x.templates.setParameters,{client:n,configKey:l.key,parameters:l.parameters??null}),o.push(i.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return o}s(JD,"applyCatalog");async function QD(e,n){let{unkeyed:t,...r}=await e.query(x.catalogExport.exportCatalog,{client:n});return{file:{revenueAccounts:r.revenueAccounts,billingItems:r.billingItems,grantTemplates:r.grantTemplates},unkeyed:t}}s(QD,"exportCatalog");var ZD={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},XD=["step","target","action","detail"],Yk=class extends C{static{s(this,"CatalogPlanCommand")}file=f.String("--file",ZD);static paths=[["catalog","plan"]];static usage=$.Usage({category:"Contracts",description:"Read-only: what `catalog apply` would write (revenue accounts, articles, price versions, program assignments, packages, tiers, Word templates)."});async execute(){let n=await this.caller(),t=await Wk(n,this.requireTenant(n),zk(this.file));return this.print(t.rows,r=>r,XD),0}},Hk=class extends C{static{s(this,"CatalogApplyCommand")}file=f.String("--file",ZD);static paths=[["catalog","apply"]];static usage=$.Usage({category:"Contracts",description:"Bring a catalog file onto the environment by stable key; a Word file is uploaded only when its SHA-256 differs. Idempotent."});async execute(){let n=await this.caller();return this.print(await JD(n,this.requireTenant(n),zk(this.file)),t=>t,XD),0}},Jk=class extends C{static{s(this,"CatalogExportCommand")}out=f.String("--out",{required:!0,description:"catalog.json to write (refused when it exists, unless --force)"});force=kn();static paths=[["catalog","export"]];static usage=$.Usage({category:"Contracts",description:"Read-only: write the tenant's catalog (revenue accounts, articles with price, floor and programs, packages, grant templates) as catalog.json \u2014 `catalog plan` on it reports `same` everywhere. Word templates are not exported."});async execute(){let n=Cn(this.out,this.force),t=await this.caller(),{file:r,unkeyed:i}=await QD(t,this.requireTenant(t));ze(n,`${JSON.stringify(r,null,2)}
11289
11289
  `);let o=Object.entries(i).filter(([,a])=>a>0).map(([a,l])=>`${l} ${a}`);return this.context.stdout.write(`${this.out}: ${r.billingItems.length} Artikel, ${r.grantTemplates.length} Rabattvorlagen`+(o.length===0?`
11290
11290
  `:` \u2014 ohne Schl\xFCssel nicht exportiert: ${o.join(", ")}
11291
- `)),0}},eF=[Yk,Hk,Jk];var R6=65279;function gm(e,n,t){(n.length!==1||n==='"'||n===`
11292
- `||n==="\r")&&ae("INVALID",{de:`${t}: ung\xFCltiges CSV-Trennzeichen ${JSON.stringify(n)}.`,en:`${t}: invalid CSV delimiter ${JSON.stringify(n)}.`});let r=e.charCodeAt(0)===R6?e.slice(1):e,i=I6(r,n,t),o=i.shift();(o===void 0||o.cells.every(u=>u.trim()===""))&&ae("INVALID",{de:`${t}: Die Datei hat keine Kopfzeile.`,en:`${t}: the file has no header row.`});let a=o.cells.map(u=>u.trim()),l=a.findIndex(u=>u==="");l!==-1&&ae("INVALID",{de:`${t}: Spalte ${l+1} der Kopfzeile hat keinen Namen.`,en:`${t}: header column ${l+1} has no name.`});let d=new Set;for(let u of a)d.has(u)&&ae("INVALID",{de:`${t}: Die Kopfzeile nennt die Spalte \u201E${u}\u201C zweimal.`,en:`${t}: the header names column "${u}" twice.`}),d.add(u);let c=[];for(let u of i)u.cells.length===1&&u.cells[0]===""||(u.cells.length!==a.length&&ae("INVALID",{de:`${t}: Zeile ${u.line} hat ${u.cells.length} Zellen, die Kopfzeile ${a.length} \u2014 die Datei ist keine Tabelle.`,en:`${t}: line ${u.line} has ${u.cells.length} cells, the header ${a.length} \u2014 the file is not one table.`}),c.push({line:u.line,cells:Object.fromEntries(a.map((p,h)=>[p,u.cells[h]]))}));return{columns:a,rows:c}}s(gm,"parseCsv");function I6(e,n,t){let r=[],i=[],o="",a=!1,l=1,d=1;for(let c=0;c<e.length;c++){let u=e[c];if(a){u==='"'?e[c+1]==='"'?(o+='"',c++):a=!1:(u===`
11291
+ `)),0}},eF=[Yk,Hk,Jk];var R4=65279;function gm(e,n,t){(n.length!==1||n==='"'||n===`
11292
+ `||n==="\r")&&ae("INVALID",{de:`${t}: ung\xFCltiges CSV-Trennzeichen ${JSON.stringify(n)}.`,en:`${t}: invalid CSV delimiter ${JSON.stringify(n)}.`});let r=e.charCodeAt(0)===R4?e.slice(1):e,i=I4(r,n,t),o=i.shift();(o===void 0||o.cells.every(u=>u.trim()===""))&&ae("INVALID",{de:`${t}: Die Datei hat keine Kopfzeile.`,en:`${t}: the file has no header row.`});let a=o.cells.map(u=>u.trim()),l=a.findIndex(u=>u==="");l!==-1&&ae("INVALID",{de:`${t}: Spalte ${l+1} der Kopfzeile hat keinen Namen.`,en:`${t}: header column ${l+1} has no name.`});let d=new Set;for(let u of a)d.has(u)&&ae("INVALID",{de:`${t}: Die Kopfzeile nennt die Spalte \u201E${u}\u201C zweimal.`,en:`${t}: the header names column "${u}" twice.`}),d.add(u);let c=[];for(let u of i)u.cells.length===1&&u.cells[0]===""||(u.cells.length!==a.length&&ae("INVALID",{de:`${t}: Zeile ${u.line} hat ${u.cells.length} Zellen, die Kopfzeile ${a.length} \u2014 die Datei ist keine Tabelle.`,en:`${t}: line ${u.line} has ${u.cells.length} cells, the header ${a.length} \u2014 the file is not one table.`}),c.push({line:u.line,cells:Object.fromEntries(a.map((p,h)=>[p,u.cells[h]]))}));return{columns:a,rows:c}}s(gm,"parseCsv");function I4(e,n,t){let r=[],i=[],o="",a=!1,l=1,d=1;for(let c=0;c<e.length;c++){let u=e[c];if(a){u==='"'?e[c+1]==='"'?(o+='"',c++):a=!1:(u===`
11293
11293
  `&&l++,o+=u);continue}u==='"'&&o===""?a=!0:u===n?(i.push(o),o=""):u===`
11294
11294
  `||u==="\r"?(u==="\r"&&e[c+1]===`
11295
- `&&c++,i.push(o),r.push({line:d,cells:i}),i=[],o="",l++,d=l):o+=u}return a&&ae("INVALID",{de:`${t}: Die in Zeile ${d} ge\xF6ffnete Anf\xFChrung schlie\xDFt nie.`,en:`${t}: the quoted cell opened on line ${d} never closes.`}),(o!==""||i.length>0)&&(i.push(o),r.push({line:d,cells:i})),r}s(I6,"csvRecords");var nF=["school","vocational","care","seminar","other"],tF=["none","manual","annual_rollover"],rF=/^\d{4}-\d{2}-\d{2}$/;function md(e){return vf(e.trim())}s(md,"importSlug");function Qk(e,n,t){return`${e}:${md(n)}:${md(t)}`}s(Qk,"learningGroupImportKey");function sF(e){let n=[];if(!Er(e))return["The mapping is not a JSON object."];e.version!==1&&n.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||n.push('delimiter must be ";", "," or "\\t".');let t=e.schoolYear;Er(t)?((typeof t.key!="string"||md(t.key)==="")&&n.push("schoolYear.key must name the year (e.g. 2026-27)."),_6(t.name)||n.push("schoolYear.name must be { de, en }."),(typeof t.startDate!="string"||!rF.test(t.startDate))&&n.push("schoolYear.startDate must be YYYY-MM-DD."),(typeof t.endDate!="string"||!rF.test(t.endDate))&&n.push("schoolYear.endDate must be YYYY-MM-DD."),typeof t.startDate=="string"&&typeof t.endDate=="string"&&t.endDate<t.startDate&&n.push("schoolYear.endDate lies before startDate.")):n.push("schoolYear is missing.");let r=e.columns;!Er(r)||typeof r.code!="string"||typeof r.unit!="string"?n.push("columns.code and columns.unit must name columns."):r.capacity!==void 0&&typeof r.capacity!="string"&&n.push("columns.capacity must name a column.");let i=e.program;return Er(i)?((!Array.isArray(i.nameColumns)||i.nameColumns.length===0||!i.nameColumns.every(o=>typeof o=="string"))&&n.push("program.nameColumns must list at least one column."),n.push(...oF("program.kind",i.kind,o=>nF.includes(o),nF.join(", "))),tF.includes(i.progressionMode)||n.push(`program.progressionMode must be one of ${tF.join(", ")}.`),i.existing!==void 0&&(!Er(i.existing)||!Object.entries(i.existing).every(([o,a])=>o.includes("/")&&typeof a=="string"&&a!==""))&&n.push("program.existing must map `<unit key>/<program name>` to a program key.")):n.push("program is missing."),n.push(...oF("gradeLevel",e.gradeLevel,o=>o===null||Number.isInteger(o)&&o>=0,"a whole number or null")),(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(o=>Er(o)&&typeof o.column=="string"&&typeof o.reason=="string"&&o.reason.trim()!==""))&&n.push("ignoredColumns must list { column, reason } entries, each with a reason."),n}s(sF,"learningGroupMappingProblems");function O6(e){let n=[e.columns.code,e.columns.unit,...e.program.nameColumns];e.columns.capacity!==void 0&&n.push(e.columns.capacity);for(let t of[e.program.kind,e.gradeLevel])lF(t)&&n.push(t.column);return[...new Set(n)]}s(O6,"learningGroupMappingColumns");function aF(e,n){let t=[],r=O6(n),i=n.ignoredColumns.map(y=>y.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(y=>!a.has(y));l.length>0&&t.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(y=>r.includes(y));d.length>0&&t.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...r,...i].filter(y=>!o.has(y));if(c.length>0&&t.push(`The mapping names columns the file does not have: ${[...new Set(c)].join(", ")}.`),t.length>0)return{rows:[],problems:t};let u=[],p=new Map,h=new Map,w=new Set;for(let{line:y,cells:b}of e.rows){let E=`line ${y}`,T=b[n.columns.code].trim(),R=b[n.columns.unit].trim();if(T===""||md(T)===""){t.push(`${E}: the class code is empty or has no letter or digit.`);continue}if(R===""){t.push(`${E} (${T}): the unit is empty.`);continue}let D=n.program.nameColumns.map(Q=>b[Q].trim()).filter(Q=>Q!=="").join(" ");if(D===""){t.push(`${E} (${T}): the program columns ${n.program.nameColumns.join(", ")} are empty.`);continue}let L=iF(n.program.kind,b,E,t),_=iF(n.gradeLevel,b,E,t),v=null;if(n.columns.capacity!==void 0){let Q=b[n.columns.capacity].trim();if(Q!==""){if(!/^\d+$/.test(Q)){t.push(`${E} (${T}): capacity "${Q}" is no whole number.`);continue}v=Number(Q)}}if(L===void 0||_===void 0)continue;let P=Qk(R,n.schoolYear.key,T),A=p.get(P);if(A!==void 0){t.push(A===T?`${E}: the class "${T}" of unit "${R}" is listed twice.`:`${E}: the codes "${A}" and "${T}" share one key (${P}) \u2014 rename one of them in the file.`);continue}p.set(P,T);let M=n.program.existing?.[`${R}/${D}`];M!==void 0&&w.add(`${R}/${D}`);let U=M??`${R}-${md(D)}`,oe=h.get(U);if(oe===void 0)h.set(U,{unitKey:R,name:D,kind:L});else if(oe.unitKey!==R||oe.name!==D||oe.kind!==L){t.push(`${E} (${T}): the program key ${U} stands for "${oe.name}" (${oe.unitKey}, ${oe.kind}) and for "${D}" (${R}, ${L}) \u2014 one key, one program.`);continue}u.push({line:y,unitKey:R,program:{key:U,name:D,kind:L,progressionMode:n.program.progressionMode,existing:M!==void 0},group:{key:P,code:T,gradeLevel:_,capacity:v}})}let k=Object.keys(n.program.existing??{}).filter(y=>!w.has(y));return k.length>0&&t.push(`program.existing entries no row names (a typo would create a second program): ${k.join(", ")}.`),t.length===0&&u.length===0&&t.push("The file holds no class row."),{rows:u,problems:t}}s(aF,"learningGroupRows");function iF(e,n,t,r){if(!lF(e))return e;let i=n[e.column].trim();if(!Object.hasOwn(e.values,i)){r.push(`${t}: column "${e.column}" holds "${i}", which the mapping's values do not list.`);return}return e.values[i]}s(iF,"mappedValue");function oF(e,n,t,r){if(Er(n)&&"column"in n){if(typeof n.column!="string"||!Er(n.values))return[`${e} must be a constant or { column, values }.`];let i=Object.entries(n.values).filter(([,o])=>!t(o)).map(([o])=>o);return i.length===0?[]:[`${e}.values for ${i.map(o=>`"${o}"`).join(", ")} must be ${r}.`]}return t(n)?[]:[`${e} must be ${r}, or { column, values }.`]}s(oF,"mappedValueProblems");function lF(e){return Er(e)&&typeof e.column=="string"&&Er(e.values)}s(lF,"isColumnValue");function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Er,"isRecord");function _6(e){return Er(e)&&typeof e.de=="string"&&e.de.trim()!==""&&typeof e.en=="string"&&e.en.trim()!==""}s(_6,"isText");function hd(e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(he(n))}catch(t){throw new Error(`${e}: ${n} is not UTF-8 text \u2014 save it as "CSV UTF-8".`,{cause:t})}}s(hd,"readUtf8File");function ym(e,n,t){let r;try{r=JSON.parse(hd(e,n))}catch(o){throw new Error(`${e}: ${n} is no JSON file (${o instanceof Error?o.message:String(o)}).`,{cause:o})}let i=t(r);if(i.length>0)throw new Error(`${e}: the mapping ${n} is invalid:
11295
+ `&&c++,i.push(o),r.push({line:d,cells:i}),i=[],o="",l++,d=l):o+=u}return a&&ae("INVALID",{de:`${t}: Die in Zeile ${d} ge\xF6ffnete Anf\xFChrung schlie\xDFt nie.`,en:`${t}: the quoted cell opened on line ${d} never closes.`}),(o!==""||i.length>0)&&(i.push(o),r.push({line:d,cells:i})),r}s(I4,"csvRecords");var nF=["school","vocational","care","seminar","other"],tF=["none","manual","annual_rollover"],rF=/^\d{4}-\d{2}-\d{2}$/;function md(e){return vf(e.trim())}s(md,"importSlug");function Qk(e,n,t){return`${e}:${md(n)}:${md(t)}`}s(Qk,"learningGroupImportKey");function sF(e){let n=[];if(!Er(e))return["The mapping is not a JSON object."];e.version!==1&&n.push(`version must be 1 (got ${JSON.stringify(e.version)}).`),[";",","," "].includes(e.delimiter)||n.push('delimiter must be ";", "," or "\\t".');let t=e.schoolYear;Er(t)?((typeof t.key!="string"||md(t.key)==="")&&n.push("schoolYear.key must name the year (e.g. 2026-27)."),_4(t.name)||n.push("schoolYear.name must be { de, en }."),(typeof t.startDate!="string"||!rF.test(t.startDate))&&n.push("schoolYear.startDate must be YYYY-MM-DD."),(typeof t.endDate!="string"||!rF.test(t.endDate))&&n.push("schoolYear.endDate must be YYYY-MM-DD."),typeof t.startDate=="string"&&typeof t.endDate=="string"&&t.endDate<t.startDate&&n.push("schoolYear.endDate lies before startDate.")):n.push("schoolYear is missing.");let r=e.columns;!Er(r)||typeof r.code!="string"||typeof r.unit!="string"?n.push("columns.code and columns.unit must name columns."):r.capacity!==void 0&&typeof r.capacity!="string"&&n.push("columns.capacity must name a column.");let i=e.program;return Er(i)?((!Array.isArray(i.nameColumns)||i.nameColumns.length===0||!i.nameColumns.every(o=>typeof o=="string"))&&n.push("program.nameColumns must list at least one column."),n.push(...oF("program.kind",i.kind,o=>nF.includes(o),nF.join(", "))),tF.includes(i.progressionMode)||n.push(`program.progressionMode must be one of ${tF.join(", ")}.`),i.existing!==void 0&&(!Er(i.existing)||!Object.entries(i.existing).every(([o,a])=>o.includes("/")&&typeof a=="string"&&a!==""))&&n.push("program.existing must map `<unit key>/<program name>` to a program key.")):n.push("program is missing."),n.push(...oF("gradeLevel",e.gradeLevel,o=>o===null||Number.isInteger(o)&&o>=0,"a whole number or null")),(!Array.isArray(e.ignoredColumns)||!e.ignoredColumns.every(o=>Er(o)&&typeof o.column=="string"&&typeof o.reason=="string"&&o.reason.trim()!==""))&&n.push("ignoredColumns must list { column, reason } entries, each with a reason."),n}s(sF,"learningGroupMappingProblems");function O4(e){let n=[e.columns.code,e.columns.unit,...e.program.nameColumns];e.columns.capacity!==void 0&&n.push(e.columns.capacity);for(let t of[e.program.kind,e.gradeLevel])lF(t)&&n.push(t.column);return[...new Set(n)]}s(O4,"learningGroupMappingColumns");function aF(e,n){let t=[],r=O4(n),i=n.ignoredColumns.map(y=>y.column),o=new Set(e.columns),a=new Set([...r,...i]),l=e.columns.filter(y=>!a.has(y));l.length>0&&t.push(`Columns neither read by the mapping nor in ignoredColumns: ${l.join(", ")}.`);let d=i.filter(y=>r.includes(y));d.length>0&&t.push(`Columns both read by the mapping and in ignoredColumns: ${d.join(", ")}.`);let c=[...r,...i].filter(y=>!o.has(y));if(c.length>0&&t.push(`The mapping names columns the file does not have: ${[...new Set(c)].join(", ")}.`),t.length>0)return{rows:[],problems:t};let u=[],p=new Map,h=new Map,w=new Set;for(let{line:y,cells:b}of e.rows){let E=`line ${y}`,T=b[n.columns.code].trim(),R=b[n.columns.unit].trim();if(T===""||md(T)===""){t.push(`${E}: the class code is empty or has no letter or digit.`);continue}if(R===""){t.push(`${E} (${T}): the unit is empty.`);continue}let D=n.program.nameColumns.map(Q=>b[Q].trim()).filter(Q=>Q!=="").join(" ");if(D===""){t.push(`${E} (${T}): the program columns ${n.program.nameColumns.join(", ")} are empty.`);continue}let L=iF(n.program.kind,b,E,t),_=iF(n.gradeLevel,b,E,t),v=null;if(n.columns.capacity!==void 0){let Q=b[n.columns.capacity].trim();if(Q!==""){if(!/^\d+$/.test(Q)){t.push(`${E} (${T}): capacity "${Q}" is no whole number.`);continue}v=Number(Q)}}if(L===void 0||_===void 0)continue;let P=Qk(R,n.schoolYear.key,T),A=p.get(P);if(A!==void 0){t.push(A===T?`${E}: the class "${T}" of unit "${R}" is listed twice.`:`${E}: the codes "${A}" and "${T}" share one key (${P}) \u2014 rename one of them in the file.`);continue}p.set(P,T);let M=n.program.existing?.[`${R}/${D}`];M!==void 0&&w.add(`${R}/${D}`);let U=M??`${R}-${md(D)}`,oe=h.get(U);if(oe===void 0)h.set(U,{unitKey:R,name:D,kind:L});else if(oe.unitKey!==R||oe.name!==D||oe.kind!==L){t.push(`${E} (${T}): the program key ${U} stands for "${oe.name}" (${oe.unitKey}, ${oe.kind}) and for "${D}" (${R}, ${L}) \u2014 one key, one program.`);continue}u.push({line:y,unitKey:R,program:{key:U,name:D,kind:L,progressionMode:n.program.progressionMode,existing:M!==void 0},group:{key:P,code:T,gradeLevel:_,capacity:v}})}let k=Object.keys(n.program.existing??{}).filter(y=>!w.has(y));return k.length>0&&t.push(`program.existing entries no row names (a typo would create a second program): ${k.join(", ")}.`),t.length===0&&u.length===0&&t.push("The file holds no class row."),{rows:u,problems:t}}s(aF,"learningGroupRows");function iF(e,n,t,r){if(!lF(e))return e;let i=n[e.column].trim();if(!Object.hasOwn(e.values,i)){r.push(`${t}: column "${e.column}" holds "${i}", which the mapping's values do not list.`);return}return e.values[i]}s(iF,"mappedValue");function oF(e,n,t,r){if(Er(n)&&"column"in n){if(typeof n.column!="string"||!Er(n.values))return[`${e} must be a constant or { column, values }.`];let i=Object.entries(n.values).filter(([,o])=>!t(o)).map(([o])=>o);return i.length===0?[]:[`${e}.values for ${i.map(o=>`"${o}"`).join(", ")} must be ${r}.`]}return t(n)?[]:[`${e} must be ${r}, or { column, values }.`]}s(oF,"mappedValueProblems");function lF(e){return Er(e)&&typeof e.column=="string"&&Er(e.values)}s(lF,"isColumnValue");function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Er,"isRecord");function _4(e){return Er(e)&&typeof e.de=="string"&&e.de.trim()!==""&&typeof e.en=="string"&&e.en.trim()!==""}s(_4,"isText");function hd(e,n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(he(n))}catch(t){throw new Error(`${e}: ${n} is not UTF-8 text \u2014 save it as "CSV UTF-8".`,{cause:t})}}s(hd,"readUtf8File");function ym(e,n,t){let r;try{r=JSON.parse(hd(e,n))}catch(o){throw new Error(`${e}: ${n} is no JSON file (${o instanceof Error?o.message:String(o)}).`,{cause:o})}let i=t(r);if(i.length>0)throw new Error(`${e}: the mapping ${n} is invalid:
11296
11296
  - ${i.join(`
11297
- - `)}`);return r}s(ym,"readMappingFile");async function gd(e,n,t,r,i){let o=[];for(let a=0;a<n.length;a+=t)try{o.push(...await i(n.slice(a,a+t)))}catch(l){let d=a===0?"":r?` The first ${a} of ${n.length} rows were written; a re-run finds them again.`:` (after ${a} of ${n.length} rows planned; nothing was written)`;throw new Error(`${e}: ${l instanceof Error?l.message:String(l)}${d}`,{cause:l})}return o}s(gd,"sendInBatches");var P6=100,Zk="learning-groups apply",Xk=class extends C{static{s(this,"LearningGroupsApplyCommand")}file=f.String("--file",{required:!0,description:"The class list (CSV, header row, the mapping's delimiter)."});mapping=f.String("--mapping",{required:!0,description:"The mapping file (JSON): which column is code, unit, program, grade level, capacity; every other column ignored with a reason."});confirm=f.Boolean("--confirm",!1,{description:"Write (else the plan only)."});static paths=[["learning-groups","apply"]];static usage=$.Usage({category:"Master data",description:"Bring a school's classes in from a file: program, school year and learning group per row, by stable key \u2014 plan unless --confirm.",details:"Every column of the file is read by the mapping or listed in its ignoredColumns, every mapped value is listed \u2014 else the plan names each problem and nothing is sent. An existing program is reused and never renamed; a class is found again by its key (unit, school year, class code), so a re-run creates nothing.",examples:[["Plan","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json"],["Write","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json --confirm"]]});async execute(){let n=ym(Zk,this.mapping,sF),t=gm(hd(Zk,this.file),n.delimiter,this.file),{rows:r,problems:i}=aF(t,n);if(i.length>0)throw new Error(`learning-groups apply: ${i.length} problems, nothing was sent:
11297
+ - `)}`);return r}s(ym,"readMappingFile");async function gd(e,n,t,r,i){let o=[];for(let a=0;a<n.length;a+=t)try{o.push(...await i(n.slice(a,a+t)))}catch(l){let d=a===0?"":r?` The first ${a} of ${n.length} rows were written; a re-run finds them again.`:` (after ${a} of ${n.length} rows planned; nothing was written)`;throw new Error(`${e}: ${l instanceof Error?l.message:String(l)}${d}`,{cause:l})}return o}s(gd,"sendInBatches");var P4=100,Zk="learning-groups apply",Xk=class extends C{static{s(this,"LearningGroupsApplyCommand")}file=f.String("--file",{required:!0,description:"The class list (CSV, header row, the mapping's delimiter)."});mapping=f.String("--mapping",{required:!0,description:"The mapping file (JSON): which column is code, unit, program, grade level, capacity; every other column ignored with a reason."});confirm=f.Boolean("--confirm",!1,{description:"Write (else the plan only)."});static paths=[["learning-groups","apply"]];static usage=$.Usage({category:"Master data",description:"Bring a school's classes in from a file: program, school year and learning group per row, by stable key \u2014 plan unless --confirm.",details:"Every column of the file is read by the mapping or listed in its ignoredColumns, every mapped value is listed \u2014 else the plan names each problem and nothing is sent. An existing program is reused and never renamed; a class is found again by its key (unit, school year, class code), so a re-run creates nothing.",examples:[["Plan","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json"],["Write","$0 --env staging --tenant <slug> learning-groups apply --file ./klassen.csv --mapping ./klassen.mapping.json --confirm"]]});async execute(){let n=ym(Zk,this.mapping,sF),t=gm(hd(Zk,this.file),n.delimiter,this.file),{rows:r,problems:i}=aF(t,n);if(i.length>0)throw new Error(`learning-groups apply: ${i.length} problems, nothing was sent:
11298
11298
  - ${i.join(`
11299
- - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await gd(Zk,r,P6,this.confirm,async d=>(await o.mutation(x.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:n.schoolYear,rows:d})).rows);return this.print(N6(l,this.confirm),d=>[...d.classes.map(c=>({...c})),{class:"\u2014",program:`${d.programsCreated} new / ${d.programsTotal}`,schoolYear:`${d.runsCreated} new / ${d.runsTotal}`,action:d.totals,changes:d.mode}],["class","program","schoolYear","action","changes"]),0}};function N6(e,n){let t=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=t(e.map(a=>[a.program.key,a.program.action])),i=t(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:n?"COMMITTED":"PLAN (re-run with --confirm to write)",programsTotal:r.size,programsCreated:[...r.values()].filter(a=>a==="create").length,runsTotal:i.size,runsCreated:[...i.values()].filter(a=>a==="create").length,totals:`${o("create")} create \xB7 ${o("update")} update \xB7 ${o("unchanged")} unchanged`,classes:e.map(a=>({class:a.code,program:`${a.program.key}${a.program.action==="create"?" (new)":""}`,schoolYear:`${a.run.key}${a.run.action==="create"?" (new)":""}`,action:a.group.action,changes:a.group.changes.join("; ")}))}}s(N6,"summary");var dF=[Xk];function eb(e){return e.trim().toLowerCase()}s(eb,"normalizeEmail");var C6=["permanentLink","periodLink"],OSe=720*60*1e3;function cF(e){if(typeof e!="object"||e===null)return!1;let n=e;return n.mode==="oneTimeLink"&&Object.keys(n).join(",")==="mode"}s(cF,"isExternalSignIn");function uF(e){if(typeof e!="object"||e===null)return!1;let n=e.mode;return C6.includes(n)}s(uF,"namesRetiredExternalSignIn");function fF(e,n,t){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&F(`Role inheritance cycle at ${o}.`),n.has(o)||F(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of t.get(o)??[]){let l=r.get(a.customFieldId);l&&ae("ROLE_FIELD_INHERITED",{de:`Das Feld ${a.customFieldId} ist auf dem Vererbungspfad der Rolle mehrfach zugeordnet (${l.roleId}, ${o}). Geerbte Felder lassen sich nicht \xFCberschreiben.`,en:`The field ${a.customFieldId} is assigned more than once on the role's inheritance path (${l.roleId}, ${o}). Inherited fields cannot be overridden.`}),r.set(a.customFieldId,a)}o=n.get(o)}return[...r.values()]}s(fF,"resolveRoleFields");var pF=new Set(["input","parties"]);function mF(e,n){let t=new Set(Array.from(e,um));for(let i of t)(!/^[a-z][a-z0-9_]*$/.test(i)||pF.has(i))&&ae("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of n){let o=um(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||pF.has(o.split(".")[0]))&&ae("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),t.has(o)&&ae("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&ae("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(mF,"assertResolverFieldKeys");var nb=["debtor","beneficiary","service_provider"];var hF=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],D6={stammdaten:{_self:["access","read","write","configure"],parties:["read","write","delete"],customFields:["read","configure","editAutomatic"]},bewerbungsmanagement:{_self:["access"],branding:["manage"],applications:["read","manage","submitOwn","viewExternal","assignResponsibility"],forms:["configure"],workflow:["approval"],testActions:["run"]},finanzen_vertraege:{_self:["access"],contracts:["manage"],payments:["connect"]},administration:{_self:["access"],roles:["manage"],permissions:["manage"],users:["manage"],masterData:["manage"],feedback:["viewAll"],organizationStructure:["manage"],apiTokens:["manage"],config:["read","manage"]},aufgaben:{_self:["access"],items:["read","write","assign","decide"]},notifications:{_self:["access"],mail:["configure"],deliveries:["read"]}},tb=Object.entries(D6).flatMap(([e,n])=>Object.entries(n).flatMap(([t,r])=>r.map(i=>`${e}.${t}.${i}`))),gF=["read","write","configure"];var F6={tenants:["accessAll"],workers:["monitor"],notifications:["monitor"],users:["manage"],feedback:["read","manage","tags","assign"],config:["read","manage"],schema:["read"],audit:["read","readActor"],apiTokens:["manage"],demoLinks:["manage"]};var rb=Object.entries(F6).flatMap(([e,n])=>n.map(t=>`_platform.${e}.${t}`)),L6=rb,M6=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],jSe=L6.filter(e=>!M6.includes(e));function yd(e,n){return e?.includes(n)??!1}s(yd,"tenantHasModule");var yF=["bewerbungsmanagement.applications.submitOwn"];function wF(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(wF,"isRetentionDays");var WSe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var q6={Abholberechtigt:"Authorized pickup",Abholzeitfenster:"Pickup window","Abmeldung vom Religionsunterricht seit":"Withdrawn from religion class since","5a, 7b, Vorkurs":"5a, 7b, prep course",Adresszusatz:"Address supplement",Aktiv:"Active","Allergien & Besonderheiten":"Allergies & special notes","Alle Einrichtungen":"All units",Anrede:"Salutation",Ansprechpartner:"Contact person",Arbeitsverh\u00E4ltnis:"Employment",Arbeitszeit:"Working time",Art:"Type","Art der rechtlichen Vertretung":"Legal representation type",Aufenthalt:"Residence","Aufnahme am":"Admission date",Auskunftsberechtigt:"Authorized for information","Ausweis erforderlich":"ID required",Bewerbung:"Application",Bereiche:"Areas","Bedarf an sonderp\xE4dagogischer Unterst\xFCtzung":"Special educational support needed",befreit:"Exempt","Betreuung bis":"Care until",Beziehungen:"Relationships",Daten:"Data",Deutsch:"German",Deutschland:"Germany",divers:"Diverse",Divers:"Diverse","Dokumente & Nachweise":"Documents & evidence",Eintrittsdatum:"Start date","Einwilligung f\xFCr Videoaufnahmen":"Video recording consent",Einschulung:"School enrollment","Endg\xFCltige Zuweisung liegt vor":"Final assignment confirmed","elterliche Sorge":"Parental custody","Entlassung am":"Release date",Entscheidungsbefugt:"Authorized to decide",Erg\u00E4nzungspflegschaft:"Supplementary guardianship",Erstsprache:"First language",Evangelisch:"Protestant",evangelisch:"Protestant",Ehemalig:"Alumni","E-Mail":"Email","Empfehlung Bedarf sonderpad. Unterst.":"Recommendation: special educational support","Empfehlung F\xF6rderort":"Recommendation: support location","Empfehlung F\xF6rderschwerpunkt":"Recommendation: support focus","Extern/Bewerber":"External/applicant",F\u00F6rderbedarf:"Support needs",F\u00F6rderschule:"Special school",F\u00F6rderstunden:"Support hours","F\xF6rderstunden/Woche":"Support hours/week","F\xF6rderschwerpunkte (Mehrfachauswahl)":"Support focuses (multiple selection)",Fotoerlaubnis:"Photo consent",F\u00F6rderung:"Support",Frau:"Ms.",Ganztag:"Full-day care","Ganztag aktiv":"Full-day active",Gasth\u00F6rer:"Guest student",Geburtsdatum:"Date of birth",Geburtsland:"Country of birth",Geburtsort:"Place of birth","Gemeinsames Lernen":"Inclusive learning",Geschlecht:"Gender",Gesundheit:"Health","Gesundheit & Nachweise":"Health & evidence","Getrennt lebend":"Living separately","Gutachten an Schulamt/BezReg":"Report sent to school authority/district government","Gutachten erstellt von":"Report prepared by","Gutachten-Beauftragung bis":"Report commissioned until",Herr:"Mr.",Hinweis:"Note",Hinweise:"Notes","in Kl\xE4rung":"Clarifying","In Pr\xFCfung":"Under review","in Pr\xFCfung":"Under review",Islamisch:"Islamic",islamisch:"Islamic",Ja:"Yes","Ja \u2014 \xA74 Abs. 1 S. 1":"Yes \u2014 Section 4 (1) sentence 1",Katholisch:"Catholic",katholisch:"Catholic",Keine:"None","Keine Auskunft an Dritte":"No information to third parties","keine Teilnahme":"No participation","kein Bedarf":"No need",Klasse:"Class","Klassenlehrer/in":"Class teacher",Konfession:"Denomination",Kontaktarten:"Contact types",Korrespondenz:"Correspondence","K\xF6rperliche und motorische Entwicklung":"Physical and motor development",Land:"Country",Lernen:"Learning","LRS / Rechenschw\xE4che":"Dyslexia / dyscalculia",m\u00E4nnlich:"male",Masernimpfnachweis:"Measles vaccination proof","Mit Einschr\xE4nkungen":"With restrictions","Mitarbeiter/in":"Staff member",Mutter:"Mother",Nachname:"Last name","Name der Organisation":"Organization name",Nein:"No","Nicht gruppiert":"Ungrouped",Notfallkontakt:"Emergency contact","Nr.":"No.","Ohne Angabe":"Not specified","ohne Angabe":"not specified","Operative Kontaktart":"Operational contact type","Operativer Kontakt":"Operational contact",Organisation:"Organization",Organisationen:"Organizations",Ort:"City",Ortsteil:"District",Person:"Person",PLZ:"Postal code",Polen:"Poland",Position:"Position",Prim\u00E4rkontakt:"Primary contact",Priorit\u00E4t:"Priority","Probeweise Zuweisung liegt vor bis":"Trial assignment confirmed until",Regelschule:"Mainstream school","Rechtliche Vertretung":"Legal representation",Religionsunterricht:"Religion class",Rolle:"Role",Schule:"School",Schulinformationen:"School information","Sch\xFCler/in":"Student","Sch\xFClerinteressent/in":"Prospective student",Sch\u00FClernummer:"Student number",Sch\u00FClerstatus:"Student status","Sch\xFClerverzeichnis Nr.":"Student directory no.",Schwimmunterricht:"Swimming class","Scope der rechtlichen Vertretung":"Legal representation scope",Sprache:"Language",Staatsangeh\u00F6rigkeit:"Nationality",Stammdaten:"Master data",Standort:"Location","Standort/Schule":"Location/school",Status:"Status",Stra\u00DFe:"Street",Syrien:"Syria",Telefon:"Phone",Teilnahme:"Participation",T\u00FCrkei:"Turkey",T\u00FCrkisch:"Turkish",Ukraine:"Ukraine",Umfang:"Extent","Umfang der rechtlichen Vertretung":"Legal representation extent",Verwaltung:"Administration",Verwandtschaft:"Kinship",Verwandtschaftsart:"Kinship type",Verwandtschaftsgrad:"Degree of kinship",Vater:"Father",Vietnamesisch:"Vietnamese",Vollst\u00E4ndig:"Complete",voll:"full",Vorname:"First name","Vormundschaft Amt":"Public guardianship","Vormundschaft Einzelner":"Individual guardianship","Vormundschaft Verein":"Association guardianship",weiblich:"female",Wohnadresse:"Residential address",Wohnort:"City of residence","Aktives Programm \xFCber Einschreibung, Lerngruppe und Programm.":"Active program across enrollment, learning group, and program.",Arabisch:"Arabic","Auskunft gesperrt":"Information blocked","Campus Lindenfeld":"Campus Lindenfeld","Campus Sonnhalde":"Campus Sonnhalde","Emotionale Entwicklung":"Emotional development","Emotionale und soziale Entwicklung":"Emotional and social development","Foto eingeschr\xE4nkt":"Photo restricted","Geistige Entwicklung":"Cognitive development",Gro\u00DFeltern:"Grandparents","Grundschule Sonnenberg":"Sonnenberg Elementary School","Interessent/in":"Prospect","Keine Einwilligung f\xFCr Videoaufnahmen":"No video recording consent","Keine Fotos":"No photos","K\xF6rper/Motorik":"Physical/motor",Lehrer:"Teacher",Mitarbeitende:"Staff","Moers, Krefeld":"Moers, Krefeld","Namen der verkn\xFCpften rechtlichen Vertretungen.":"Names of the linked legal representatives.",Pflegeperson:"Caregiver",Programm:"Program","Rechtliche Vertretungen":"Legal representatives",Schulleitung:"School leadership",Schulverwaltung:"School administration",Stiefeltern:"Stepparents",Verm\u00F6gen:"Assets",teilweise:"partial"};function Ho(e,n=q6[e]){return(n===void 0||n.trim()==="")&&F(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:n.trim()}}s(Ho,"label");var ib=[{key:"first_name",label:Ho("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ho("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ho("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],K6=new Map(ib.map(e=>[e.key,e]));function kF(e){return K6.has(e)}s(kF,"isSystemFieldKey");var ob={string:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},textarea:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},email:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},tel:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},date:{dataType:"date",valueColumn:"valueDate",fieldMapTarget:!0},number:{dataType:"number",valueColumn:"valueNumber",fieldMapTarget:!0},boolean:{dataType:"boolean",valueColumn:"valueBoolean",fieldMapTarget:!0},files:{dataType:"file",valueColumn:"valueJson",fieldMapTarget:!0},"auto-string":{dataType:"text",valueColumn:"valueString",fieldMapTarget:!1},"0-1-select":{dataType:"option",valueColumn:"valueString",fieldMapTarget:!0},"0-n-select":{dataType:"option",valueColumn:"valueJson",fieldMapTarget:!0},object:{dataType:"composite",valueColumn:"valueJson",fieldMapTarget:!0},relationship:{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1},"program-interest":{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1}};var aAe=11*6e4;var lAe=30*6e4;var dAe=5*6e4;var cAe=5*6e4;var wm="tenant",uAe=m.record(m.string(),m.string());var Hi=1024*1024,wd=["application/pdf","image/jpeg","image/png","image/webp"];var km=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","image/jpeg","image/png"],bF={docRef:{maxBytes:25*Hi,allowedMime:wd},partyFile:{maxBytes:25*Hi,allowedMime:wd},import:{maxBytes:500*Hi,allowedMime:null},signedContract:{maxBytes:25*Hi,allowedMime:wd},artifactVersion:{maxBytes:25*Hi,allowedMime:wd},chatAttachment:{maxBytes:25*Hi,allowedMime:wd},tenantFile:{maxBytes:20*Hi,allowedMime:km},documentTemplate:{maxBytes:25*Hi,allowedMime:null}};function vF(e){let n=atob(e),t="";for(let r=0;r<n.length;r++)t+=n.charCodeAt(r).toString(16).padStart(2,"0");return t}s(vF,"sha256Base64ToHex");var qt={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},j6=m.object({storageId:m.id("_storage"),filename:qt.filename,mimeType:qt.mimeType,sizeBytes:qt.sizeBytes,sha256:m.optional(qt.sha256)}),bAe=m.object({storageId:j6.fields.storageId,filename:qt.filename,mimeType:m.optional(qt.mimeType),sizeBytes:m.optional(qt.sizeBytes),sha256:m.optional(qt.sha256),url:m.union(m.string(),m.null())});async function V6(e,n){let t=await e.db.system.get("_storage",n);return t===null?null:{...t.contentType===void 0?{}:{mimeType:t.contentType},sizeBytes:t.size,sha256:vF(t.sha256)}}s(V6,"storedObjectMeta");async function sb(e,n){let t=(await V6(e,n))?.mimeType;return t===void 0?{}:{mimeType:t}}s(sb,"objectType");var TAe=m.union(m.literal("de"),m.literal("en")),$Ae=m.record(m.string(),m.string()),Ji=m.object({de:m.string(),en:m.string()}),RAe=m.object({title:Ji,body:Ji,confirmLabel:Ji}),IAe=m.union(m.string(),Ji);function bm(e){return Ye.includes(e)}s(bm,"isSupportedLocale");var B6=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),xF=m.object({storageId:m.string(),filename:qt.filename,mimeType:m.optional(qt.mimeType),sizeBytes:m.optional(qt.sizeBytes),sha256:m.optional(qt.sha256),uploadedAt:m.number()}),OAe=m.union(m.string(),m.number(),m.boolean(),m.null(),B6,xF,m.array(m.string()),m.array(xF)),_Ae=m.record(m.string(),m.string());var ab=["Bewerbung","Anmeldung"];var AF=m.object({application:m.optional(m.union(...ab.map(e=>m.literal(e))))}),DAe=m.object({application:m.union(...ab.map(e=>m.literal(e)))}),SF={application:ab};function lb(e,n="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${n} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let t=[];for(let[r,i]of Object.entries(e)){let o=SF[r];if(o===void 0){t.push(`[terms/unknownTerm] ${n}.${r} gibt es nicht. Einstellbar: ${Object.keys(SF).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&t.push(`[terms/unknownChoice] ${n}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return t}s(lb,"termsFindings");var Hr="recipientName",_a="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var kd={de:{greeting:`Hallo {{${Hr}}},`,closing:`Viele Gr\xFC\xDFe
11299
+ - `)}`);let o=await this.caller(),a=this.requireTenant(o),l=await gd(Zk,r,P4,this.confirm,async d=>(await o.mutation(x.learningGroupImport.apply,{client:a,dryRun:!this.confirm,schoolYear:n.schoolYear,rows:d})).rows);return this.print(N4(l,this.confirm),d=>[...d.classes.map(c=>({...c})),{class:"\u2014",program:`${d.programsCreated} new / ${d.programsTotal}`,schoolYear:`${d.runsCreated} new / ${d.runsTotal}`,action:d.totals,changes:d.mode}],["class","program","schoolYear","action","changes"]),0}};function N4(e,n){let t=s(a=>{let l=new Map;for(let[d,c]of a)l.get(d)!=="create"&&l.set(d,c);return l},"created"),r=t(e.map(a=>[a.program.key,a.program.action])),i=t(e.map(a=>[a.run.key,a.run.action])),o=s(a=>e.filter(l=>l.group.action===a).length,"count");return{mode:n?"COMMITTED":"PLAN (re-run with --confirm to write)",programsTotal:r.size,programsCreated:[...r.values()].filter(a=>a==="create").length,runsTotal:i.size,runsCreated:[...i.values()].filter(a=>a==="create").length,totals:`${o("create")} create \xB7 ${o("update")} update \xB7 ${o("unchanged")} unchanged`,classes:e.map(a=>({class:a.code,program:`${a.program.key}${a.program.action==="create"?" (new)":""}`,schoolYear:`${a.run.key}${a.run.action==="create"?" (new)":""}`,action:a.group.action,changes:a.group.changes.join("; ")}))}}s(N4,"summary");var dF=[Xk];function eb(e){return e.trim().toLowerCase()}s(eb,"normalizeEmail");var C4=["permanentLink","periodLink"],OSe=720*60*1e3;function cF(e){if(typeof e!="object"||e===null)return!1;let n=e;return n.mode==="oneTimeLink"&&Object.keys(n).join(",")==="mode"}s(cF,"isExternalSignIn");function uF(e){if(typeof e!="object"||e===null)return!1;let n=e.mode;return C4.includes(n)}s(uF,"namesRetiredExternalSignIn");function fF(e,n,t){let r=new Map,i=new Set,o=e;for(;o!==void 0;){i.has(o)&&F(`Role inheritance cycle at ${o}.`),n.has(o)||F(`Missing role ${o} in inheritance path.`),i.add(o);for(let a of t.get(o)??[]){let l=r.get(a.customFieldId);l&&ae("ROLE_FIELD_INHERITED",{de:`Das Feld ${a.customFieldId} ist auf dem Vererbungspfad der Rolle mehrfach zugeordnet (${l.roleId}, ${o}). Geerbte Felder lassen sich nicht \xFCberschreiben.`,en:`The field ${a.customFieldId} is assigned more than once on the role's inheritance path (${l.roleId}, ${o}). Inherited fields cannot be overridden.`}),r.set(a.customFieldId,a)}o=n.get(o)}return[...r.values()]}s(fF,"resolveRoleFields");var pF=new Set(["input","parties"]);function mF(e,n){let t=new Set(Array.from(e,um));for(let i of t)(!/^[a-z][a-z0-9_]*$/.test(i)||pF.has(i))&&ae("INVALID",{de:`Ung\xFCltiger oder reservierter Feldschl\xFCssel: ${i}.`,en:`Invalid or reserved field key: ${i}.`});let r=new Set;for(let i of n){let o=um(i);(!/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(o)||pF.has(o.split(".")[0]))&&ae("INVALID",{de:`Ung\xFCltiger oder reservierter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Invalid or reserved resolver parameter key: ${i}.`}),t.has(o)&&ae("INVALID",{de:`Der Resolver-Parameter ${i} kollidiert mit einem Feldschl\xFCssel.`,en:`The resolver parameter ${i} collides with a field key.`}),r.has(o)&&ae("INVALID",{de:`Doppelter Parameterschl\xFCssel des Resolvers: ${i}.`,en:`Duplicate resolver parameter key: ${i}.`}),r.add(o)}}s(mF,"assertResolverFieldKeys");var nb=["debtor","beneficiary","service_provider"];var hF=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],D4={stammdaten:{_self:["access","read","write","configure"],parties:["read","write","delete"],customFields:["read","configure","editAutomatic"]},bewerbungsmanagement:{_self:["access"],branding:["manage"],applications:["read","manage","submitOwn","viewExternal","assignResponsibility"],forms:["configure"],workflow:["approval"],testActions:["run"]},finanzen_vertraege:{_self:["access"],contracts:["manage"],payments:["connect"]},administration:{_self:["access"],roles:["manage"],permissions:["manage"],users:["manage"],masterData:["manage"],feedback:["viewAll"],organizationStructure:["manage"],apiTokens:["manage"],config:["read","manage"]},aufgaben:{_self:["access"],items:["read","write","assign","decide"]},notifications:{_self:["access"],mail:["configure"],deliveries:["read"]}},tb=Object.entries(D4).flatMap(([e,n])=>Object.entries(n).flatMap(([t,r])=>r.map(i=>`${e}.${t}.${i}`))),gF=["read","write","configure"];var F4={tenants:["accessAll"],workers:["monitor"],notifications:["monitor"],users:["manage"],feedback:["read","manage","tags","assign"],config:["read","manage"],schema:["read"],audit:["read","readActor"],apiTokens:["manage"],demoLinks:["manage"]};var rb=Object.entries(F4).flatMap(([e,n])=>n.map(t=>`_platform.${e}.${t}`)),L4=rb,M4=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],jSe=L4.filter(e=>!M4.includes(e));function yd(e,n){return e?.includes(n)??!1}s(yd,"tenantHasModule");var yF=["bewerbungsmanagement.applications.submitOwn"];function wF(e){return Number.isSafeInteger(e)&&e>=1&&e<=36500}s(wF,"isRetentionDays");var WSe=m.union(m.literal("persons.firstName"),m.literal("persons.lastName"),m.literal("organizations.name"));var q4={Abholberechtigt:"Authorized pickup",Abholzeitfenster:"Pickup window","Abmeldung vom Religionsunterricht seit":"Withdrawn from religion class since","5a, 7b, Vorkurs":"5a, 7b, prep course",Adresszusatz:"Address supplement",Aktiv:"Active","Allergien & Besonderheiten":"Allergies & special notes","Alle Einrichtungen":"All units",Anrede:"Salutation",Ansprechpartner:"Contact person",Arbeitsverh\u00E4ltnis:"Employment",Arbeitszeit:"Working time",Art:"Type","Art der rechtlichen Vertretung":"Legal representation type",Aufenthalt:"Residence","Aufnahme am":"Admission date",Auskunftsberechtigt:"Authorized for information","Ausweis erforderlich":"ID required",Bewerbung:"Application",Bereiche:"Areas","Bedarf an sonderp\xE4dagogischer Unterst\xFCtzung":"Special educational support needed",befreit:"Exempt","Betreuung bis":"Care until",Beziehungen:"Relationships",Daten:"Data",Deutsch:"German",Deutschland:"Germany",divers:"Diverse",Divers:"Diverse","Dokumente & Nachweise":"Documents & evidence",Eintrittsdatum:"Start date","Einwilligung f\xFCr Videoaufnahmen":"Video recording consent",Einschulung:"School enrollment","Endg\xFCltige Zuweisung liegt vor":"Final assignment confirmed","elterliche Sorge":"Parental custody","Entlassung am":"Release date",Entscheidungsbefugt:"Authorized to decide",Erg\u00E4nzungspflegschaft:"Supplementary guardianship",Erstsprache:"First language",Evangelisch:"Protestant",evangelisch:"Protestant",Ehemalig:"Alumni","E-Mail":"Email","Empfehlung Bedarf sonderpad. Unterst.":"Recommendation: special educational support","Empfehlung F\xF6rderort":"Recommendation: support location","Empfehlung F\xF6rderschwerpunkt":"Recommendation: support focus","Extern/Bewerber":"External/applicant",F\u00F6rderbedarf:"Support needs",F\u00F6rderschule:"Special school",F\u00F6rderstunden:"Support hours","F\xF6rderstunden/Woche":"Support hours/week","F\xF6rderschwerpunkte (Mehrfachauswahl)":"Support focuses (multiple selection)",Fotoerlaubnis:"Photo consent",F\u00F6rderung:"Support",Frau:"Ms.",Ganztag:"Full-day care","Ganztag aktiv":"Full-day active",Gasth\u00F6rer:"Guest student",Geburtsdatum:"Date of birth",Geburtsland:"Country of birth",Geburtsort:"Place of birth","Gemeinsames Lernen":"Inclusive learning",Geschlecht:"Gender",Gesundheit:"Health","Gesundheit & Nachweise":"Health & evidence","Getrennt lebend":"Living separately","Gutachten an Schulamt/BezReg":"Report sent to school authority/district government","Gutachten erstellt von":"Report prepared by","Gutachten-Beauftragung bis":"Report commissioned until",Herr:"Mr.",Hinweis:"Note",Hinweise:"Notes","in Kl\xE4rung":"Clarifying","In Pr\xFCfung":"Under review","in Pr\xFCfung":"Under review",Islamisch:"Islamic",islamisch:"Islamic",Ja:"Yes","Ja \u2014 \xA74 Abs. 1 S. 1":"Yes \u2014 Section 4 (1) sentence 1",Katholisch:"Catholic",katholisch:"Catholic",Keine:"None","Keine Auskunft an Dritte":"No information to third parties","keine Teilnahme":"No participation","kein Bedarf":"No need",Klasse:"Class","Klassenlehrer/in":"Class teacher",Konfession:"Denomination",Kontaktarten:"Contact types",Korrespondenz:"Correspondence","K\xF6rperliche und motorische Entwicklung":"Physical and motor development",Land:"Country",Lernen:"Learning","LRS / Rechenschw\xE4che":"Dyslexia / dyscalculia",m\u00E4nnlich:"male",Masernimpfnachweis:"Measles vaccination proof","Mit Einschr\xE4nkungen":"With restrictions","Mitarbeiter/in":"Staff member",Mutter:"Mother",Nachname:"Last name","Name der Organisation":"Organization name",Nein:"No","Nicht gruppiert":"Ungrouped",Notfallkontakt:"Emergency contact","Nr.":"No.","Ohne Angabe":"Not specified","ohne Angabe":"not specified","Operative Kontaktart":"Operational contact type","Operativer Kontakt":"Operational contact",Organisation:"Organization",Organisationen:"Organizations",Ort:"City",Ortsteil:"District",Person:"Person",PLZ:"Postal code",Polen:"Poland",Position:"Position",Prim\u00E4rkontakt:"Primary contact",Priorit\u00E4t:"Priority","Probeweise Zuweisung liegt vor bis":"Trial assignment confirmed until",Regelschule:"Mainstream school","Rechtliche Vertretung":"Legal representation",Religionsunterricht:"Religion class",Rolle:"Role",Schule:"School",Schulinformationen:"School information","Sch\xFCler/in":"Student","Sch\xFClerinteressent/in":"Prospective student",Sch\u00FClernummer:"Student number",Sch\u00FClerstatus:"Student status","Sch\xFClerverzeichnis Nr.":"Student directory no.",Schwimmunterricht:"Swimming class","Scope der rechtlichen Vertretung":"Legal representation scope",Sprache:"Language",Staatsangeh\u00F6rigkeit:"Nationality",Stammdaten:"Master data",Standort:"Location","Standort/Schule":"Location/school",Status:"Status",Stra\u00DFe:"Street",Syrien:"Syria",Telefon:"Phone",Teilnahme:"Participation",T\u00FCrkei:"Turkey",T\u00FCrkisch:"Turkish",Ukraine:"Ukraine",Umfang:"Extent","Umfang der rechtlichen Vertretung":"Legal representation extent",Verwaltung:"Administration",Verwandtschaft:"Kinship",Verwandtschaftsart:"Kinship type",Verwandtschaftsgrad:"Degree of kinship",Vater:"Father",Vietnamesisch:"Vietnamese",Vollst\u00E4ndig:"Complete",voll:"full",Vorname:"First name","Vormundschaft Amt":"Public guardianship","Vormundschaft Einzelner":"Individual guardianship","Vormundschaft Verein":"Association guardianship",weiblich:"female",Wohnadresse:"Residential address",Wohnort:"City of residence","Aktives Programm \xFCber Einschreibung, Lerngruppe und Programm.":"Active program across enrollment, learning group, and program.",Arabisch:"Arabic","Auskunft gesperrt":"Information blocked","Campus Lindenfeld":"Campus Lindenfeld","Campus Sonnhalde":"Campus Sonnhalde","Emotionale Entwicklung":"Emotional development","Emotionale und soziale Entwicklung":"Emotional and social development","Foto eingeschr\xE4nkt":"Photo restricted","Geistige Entwicklung":"Cognitive development",Gro\u00DFeltern:"Grandparents","Grundschule Sonnenberg":"Sonnenberg Elementary School","Interessent/in":"Prospect","Keine Einwilligung f\xFCr Videoaufnahmen":"No video recording consent","Keine Fotos":"No photos","K\xF6rper/Motorik":"Physical/motor",Lehrer:"Teacher",Mitarbeitende:"Staff","Moers, Krefeld":"Moers, Krefeld","Namen der verkn\xFCpften rechtlichen Vertretungen.":"Names of the linked legal representatives.",Pflegeperson:"Caregiver",Programm:"Program","Rechtliche Vertretungen":"Legal representatives",Schulleitung:"School leadership",Schulverwaltung:"School administration",Stiefeltern:"Stepparents",Verm\u00F6gen:"Assets",teilweise:"partial"};function Ho(e,n=q4[e]){return(n===void 0||n.trim()==="")&&F(`label("${e}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:e.trim(),en:n.trim()}}s(Ho,"label");var ib=[{key:"first_name",label:Ho("Vorname","First name"),type:"string",systemColumn:"persons.firstName",partyKind:"person",required:!0},{key:"last_name",label:Ho("Nachname","Last name"),type:"string",systemColumn:"persons.lastName",partyKind:"person",required:!0},{key:"organization_name",label:Ho("Name der Organisation","Organization name"),type:"string",systemColumn:"organizations.name",partyKind:"organization",required:!0}],K4=new Map(ib.map(e=>[e.key,e]));function kF(e){return K4.has(e)}s(kF,"isSystemFieldKey");var ob={string:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},textarea:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},email:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},tel:{dataType:"text",valueColumn:"valueString",fieldMapTarget:!0},date:{dataType:"date",valueColumn:"valueDate",fieldMapTarget:!0},number:{dataType:"number",valueColumn:"valueNumber",fieldMapTarget:!0},boolean:{dataType:"boolean",valueColumn:"valueBoolean",fieldMapTarget:!0},files:{dataType:"file",valueColumn:"valueJson",fieldMapTarget:!0},"auto-string":{dataType:"text",valueColumn:"valueString",fieldMapTarget:!1},"0-1-select":{dataType:"option",valueColumn:"valueString",fieldMapTarget:!0},"0-n-select":{dataType:"option",valueColumn:"valueJson",fieldMapTarget:!0},object:{dataType:"composite",valueColumn:"valueJson",fieldMapTarget:!0},relationship:{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1},"program-interest":{dataType:"edge",valueColumn:"valueJson",fieldMapTarget:!1}};var aAe=11*6e4;var lAe=30*6e4;var dAe=5*6e4;var cAe=5*6e4;var wm="tenant",uAe=m.record(m.string(),m.string());var Hi=1024*1024,wd=["application/pdf","image/jpeg","image/png","image/webp"];var km=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","image/jpeg","image/png"],bF={docRef:{maxBytes:25*Hi,allowedMime:wd},partyFile:{maxBytes:25*Hi,allowedMime:wd},import:{maxBytes:500*Hi,allowedMime:null},signedContract:{maxBytes:25*Hi,allowedMime:wd},artifactVersion:{maxBytes:25*Hi,allowedMime:wd},chatAttachment:{maxBytes:25*Hi,allowedMime:wd},tenantFile:{maxBytes:20*Hi,allowedMime:km},documentTemplate:{maxBytes:25*Hi,allowedMime:null}};function vF(e){let n=atob(e),t="";for(let r=0;r<n.length;r++)t+=n.charCodeAt(r).toString(16).padStart(2,"0");return t}s(vF,"sha256Base64ToHex");var qt={filename:m.string(),mimeType:m.string(),sizeBytes:m.number(),sha256:m.string()},j4=m.object({storageId:m.id("_storage"),filename:qt.filename,mimeType:qt.mimeType,sizeBytes:qt.sizeBytes,sha256:m.optional(qt.sha256)}),bAe=m.object({storageId:j4.fields.storageId,filename:qt.filename,mimeType:m.optional(qt.mimeType),sizeBytes:m.optional(qt.sizeBytes),sha256:m.optional(qt.sha256),url:m.union(m.string(),m.null())});async function V4(e,n){let t=await e.db.system.get("_storage",n);return t===null?null:{...t.contentType===void 0?{}:{mimeType:t.contentType},sizeBytes:t.size,sha256:vF(t.sha256)}}s(V4,"storedObjectMeta");async function sb(e,n){let t=(await V4(e,n))?.mimeType;return t===void 0?{}:{mimeType:t}}s(sb,"objectType");var TAe=m.union(m.literal("de"),m.literal("en")),$Ae=m.record(m.string(),m.string()),Ji=m.object({de:m.string(),en:m.string()}),RAe=m.object({title:Ji,body:Ji,confirmLabel:Ji}),IAe=m.union(m.string(),Ji);function bm(e){return Ye.includes(e)}s(bm,"isSupportedLocale");var B4=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string(),land:m.string()}),xF=m.object({storageId:m.string(),filename:qt.filename,mimeType:m.optional(qt.mimeType),sizeBytes:m.optional(qt.sizeBytes),sha256:m.optional(qt.sha256),uploadedAt:m.number()}),OAe=m.union(m.string(),m.number(),m.boolean(),m.null(),B4,xF,m.array(m.string()),m.array(xF)),_Ae=m.record(m.string(),m.string());var ab=["Bewerbung","Anmeldung"];var AF=m.object({application:m.optional(m.union(...ab.map(e=>m.literal(e))))}),DAe=m.object({application:m.union(...ab.map(e=>m.literal(e)))}),SF={application:ab};function lb(e,n="tenant.terms"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[terms/shape] ${n} muss ein Objekt sein, z. B. { "application": "Anmeldung" }.`];let t=[];for(let[r,i]of Object.entries(e)){let o=SF[r];if(o===void 0){t.push(`[terms/unknownTerm] ${n}.${r} gibt es nicht. Einstellbar: ${Object.keys(SF).join(", ")}.`);continue}(typeof i!="string"||!o.includes(i))&&t.push(`[terms/unknownChoice] ${n}.${r} = ${JSON.stringify(i)} ist keine Wahl. M\xF6glich: ${o.join(", ")}.`)}return t}s(lb,"termsFindings");var Hr="recipientName",_a="Name der Empf\xE4ngerin oder des Empf\xE4ngers";var kd={de:{greeting:`Hallo {{${Hr}}},`,closing:`Viele Gr\xFC\xDFe
11300
11300
  Ihr Aufnahme-Team`,noReplyNote:"Diese E-Mail wurde automatisch versandt. Bitte antworten Sie nicht auf diese Nachricht."},en:{greeting:`Hello {{${Hr}}},`,closing:`Kind regards
11301
- The admissions team`,noReplyNote:"This e-mail was sent automatically. Please do not reply to it."}},U6={de:{...kd.de,closing:`Viele Gr\xFC\xDFe
11301
+ The admissions team`,noReplyNote:"This e-mail was sent automatically. Please do not reply to it."}},U4={de:{...kd.de,closing:`Viele Gr\xFC\xDFe
11302
11302
  Ihr Plexus-Team`},en:{...kd.en,closing:`Kind regards
11303
- The Plexus team`}},G6={de:{...kd.de,closing:null},en:{...kd.en,closing:null}};var z6=/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,Jo=2e3;function vm(e){let n=[];for(let t of e.matchAll(z6)){let r=t[1];n.includes(r)||n.push(r)}return n}s(vm,"placeholdersIn");function EF(e){return e.slots??[]}s(EF,"slotsOf");function W6(e){return e.bodyVariants!==void 0?e.bodyVariants:[EF(e).filter(n=>n.key!==Ul).map(n=>n.key)]}s(W6,"bodyVariantsOf");var Y6=/:\/\/|www\.|mailto:/i;function H6(e,n){let t=`{{${n}}}`,r=0;for(;;){let i=e.indexOf(t,r);if(i===-1)return!1;let o=i===0?"":e[i-1],a=e[i+t.length]??"";if(o!==""&&!/\s/.test(o)||a!==""&&!/[\s.,;:!?)]/.test(a))return!0;r=i+t.length}}s(H6,"linkGlued");function J6(e,n){let t=e.default[n];return(typeof t!="string"||t.length===0)&&F(`notifications: slot "${e.key}" has no "${n}" text`),t}s(J6,"defaultText");function TF(e,n,t){let r=[],i=EF(e),o=e.placeholders??[],a=o.map(u=>u.key),l=o.filter(u=>u.subjectSafe===!0).map(u=>u.key);for(let[u,p]of Object.entries(n)){let h=i.find(w=>w.key===u);if(h===void 0){r.push({slotKey:u,code:"unknownSlot",message:i.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C l\xE4sst sich nicht anpassen.`,en:`The notification "${e.label}" cannot be customized.`}:{de:`Der Baustein \u201E${u}\u201C geh\xF6rt nicht zur Benachrichtigung \u201E${e.label}\u201C.`,en:`The block "${u}" does not belong to the letter "${e.label}".`}});continue}if(p.trim().length===0){r.push({slotKey:u,code:"empty",message:{de:`\u201E${h.label}\u201C darf nicht leer sein. Zum Entfernen den Baustein zur\xFCcksetzen.`,en:`"${h.label}" must not be empty. To remove it, reset the block.`}});continue}if(p.length>Jo){r.push({slotKey:u,code:"tooLong",message:{de:`\u201E${h.label}\u201C ist ${p.length} Zeichen lang, erlaubt sind ${Jo}.`,en:`"${h.label}" is ${p.length} characters long; the limit is ${Jo}.`}});continue}if(OP(e)){Y6.test(p)&&r.push({slotKey:u,code:"foreignUrl",message:{de:`\u201E${h.label}\u201C enth\xE4lt eine Adresse. Der Brief \u201E${e.label}\u201C tr\xE4gt einen Anmeldeschl\xFCssel und darf keine weiteren Links enthalten.`,en:`"${h.label}" contains an address. The letter "${e.label}" carries a sign-in key and must not contain any further links.`}});for(let w of o)w.link!==!0||!H6(p,w.key)||r.push({slotKey:u,code:"linkNotStandalone",message:{de:`\u201E{{${w.key}}}\u201C (${w.label}) muss f\xFCr sich stehen \u2014 davor und dahinter nur ein Leerzeichen, ein Zeilenumbruch oder ein Satzzeichen.`,en:`"{{${w.key}}}" (${w.label}) must stand on its own \u2014 only a space, a line break or punctuation before and after it.`}})}for(let w of vm(p)){if(!a.includes(w)){r.push({slotKey:u,code:"unknownPlaceholder",message:w===Hr?{de:`\u201E{{${Hr}}}\u201C (${_a}) geh\xF6rt in die Anrede der Schule (unter \u201EAnrede und Gru\xDFformel\u201C), nicht in \u201E${h.label}\u201C \u2014 dort gibt es eine neutrale Anrede, wenn kein Name bekannt ist.`,en:`"{{${Hr}}}" (${_a}) belongs in the school's greeting (under \u201CGreeting and sign-off\u201D), not in "${h.label}" \u2014 the greeting has a neutral form for when no name is known.`}:a.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C kennt keine Platzhalter, \u201E{{${w}}}\u201C bliebe unersetzt stehen.`,en:`The notification "${e.label}" has no placeholders; "{{${w}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${w}}}\u201C gibt es in \u201E${e.label}\u201C nicht. Erlaubt: ${a.map(y=>`{{${y}}}`).join(", ")}.`,en:`"{{${w}}}" does not exist in "${e.label}". Allowed: ${a.map(y=>`{{${y}}}`).join(", ")}.`}});continue}if(u!==Ul||l.includes(w))continue;let k=o.find(y=>y.key===w)?.label??w;r.push({slotKey:u,code:"subjectUnsupported",message:{de:`\u201E{{${w}}}\u201C (${k}) l\xE4sst sich im Betreff nicht einsetzen \u2014 der Wert entsteht erst beim Versand. `+(l.length===0?"In dieser Benachrichtigung kann der Betreff keine Platzhalter tragen.":`Im Betreff m\xF6glich: ${l.map(y=>`{{${y}}}`).join(", ")}.`),en:`"{{${w}}}" (${k}) cannot be used in the subject \u2014 the value only exists when the mail is sent. `+(l.length===0?"In this letter the subject cannot carry placeholders.":`Possible in the subject: ${l.map(y=>`{{${y}}}`).join(", ")}.`)}})}}let d=s(u=>n[u]??Q6(i,u,t),"textOf"),c=W6(e);for(let u of o){if(u.required!==!0)continue;let p=c.filter(y=>!vm(y.map(d).join(`
11304
- `)).includes(u.key));if(p.length===0)continue;let h=s((y,b)=>y.map(E=>b(i.find(T=>T.key===E)?.label??E)).join(" + "),"variantLabel"),w=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(y=>h(y,b=>`\u201E${b}\u201C`)).join(" und in der aus ")}.`,k=c.length===1?"":` It is missing in the version made of ${p.map(y=>h(y,b=>`"${b}"`)).join(" and in the one made of ")}.`;r.push({slotKey:u.key,code:"missingRequired",message:{de:`Ohne \u201E{{${u.key}}}\u201C (${u.label}) funktioniert der Brief \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+w,en:`Without "{{${u.key}}}" (${u.label}) the letter "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+k}})}return r}s(TF,"validateOverride");function Q6(e,n,t){let r=e.find(i=>i.key===n);return r===void 0?"":J6(r,t)}s(Q6,"defaultTextOf");function db(e){let n=e?.trim();return n===void 0||n.length===0?void 0:n}s(db,"normalizeChromeText");var Qo=s(e=>String.fromCharCode(e),"cp"),Z6=new RegExp(`[${Qo(0)}-${Qo(31)}${Qo(127)}]`,"g"),X6=new RegExp(`[${Qo(8234)}-${Qo(8238)}${Qo(8294)}-${Qo(8297)}]`,"g");var e3=200;function n3(e,n=e3){return e.replace(Z6," ").replace(X6,"").replace(/\s+/g," ").trim().slice(0,n)}s(n3,"sanitizeHeaderValue");function xm(e){return n3(e.replace(/["<>@]/g,""),100)}s(xm,"sanitizeDisplayName");var cb={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},t3={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function $F(e){let n=[],t=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=t3[i],l=In(o);l!=="not-localized"&&l.length>0&&l.length<Ye.length&&t.push({de:`${a.de} fehlt auf ${l.map(d=>cb[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>cb[d].en).join(" and ")}`});for(let d of Ye){let c=Pw(h=>`${a[h]} (${cb[d][h]})`),u=db(o[d]);u!==void 0&&u.length>Jo&&n.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Jo}; Anrede und Gru\xDFformel sind je eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Jo}; the greeting and the sign-off are one line of the mail each, not a document.`});let p=i==="greeting"?[Hr]:[];for(let h of vm(u??""))p.includes(h)||n.push(p.length===0?{de:`${c.de} kann keine Platzhalter tragen \u2014 \u201E{{${h}}}\u201C bliebe unersetzt stehen.`,en:`${c.en} cannot carry placeholders \u2014 "{{${h}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${h}}}\u201C gibt es in der ${c.de} nicht. Erlaubt: {{${Hr}}} (${_a}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${Hr}}} (${_a}).`})}}t.length>0&&n.unshift({de:`[notification/chromeMissingTranslation] ${t.map(i=>i.de).join("; ")} \u2014 Anrede und Gru\xDFformel gelten f\xFCr jede Benachrichtigung, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${t.map(i=>i.en).join("; ")} \u2014 the greeting and sign-off apply to every notification, in every language.`});let r=db(e.senderName);return r!==void 0&&xm(r)!==r&&n.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${xm(r)}\u201C hinaus. Keine Anf\xFChrungszeichen, spitzen Klammern, \u201E@\u201C oder Steuerzeichen.`,en:`The sender name (senderName) "${r}" does not survive the mail header unchanged \u2014 it would go out as "${xm(r)}". No quotation marks, angle brackets, "@" or control characters.`}),n}s($F,"chromeFindings");var RF=m.object({family:m.string()}),IF=m.object({family:m.string(),url:m.optional(m.string())}),xEe=m.object({heading:m.optional(IF),body:m.optional(IF)}),r3=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),i3=m.union(m.literal("light"),m.literal("dark")),o3=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),s3=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),a3=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),l3=m.object({heading:m.optional(RF),body:m.optional(RF)}),SEe=m.object({colors:m.optional(a3),radius:m.optional(r3),logoSize:m.optional(o3),bannerDensity:m.optional(s3),logoGround:m.optional(i3),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(l3)}),AEe=m.object({primaryUrl:m.union(m.null(),m.string())}),EEe=m.literal("primary"),TEe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),$Ee=m.union(m.literal("heading"),m.literal("body")),Sm=["logo","fontHeading","fontBody"],OF={logo:null,fontHeading:"heading",fontBody:"body"};function _F(e){let{contentType:n,size:t}=e;return n==null||!n.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${n??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${n??"unknown"}").`}:n.startsWith("image/svg")?{de:"Das Logo muss eine Rastergrafik sein (PNG, JPEG oder GIF) \u2013 E-Mail-Programme zeigen SVG nicht an.",en:"The logo must be a raster image (PNG, JPEG or GIF) \u2013 email clients do not display SVG."}:t>3e6?{de:`Das Logo ist zu gro\xDF (${t} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${t} bytes, at most 3000000 bytes).`}:null}s(_F,"logoFileProblem");var ub="font/woff2";var d3=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function PF(e){return e?.trim()?d3.some(n=>n.toLowerCase()===e.trim().toLowerCase())?{de:`\u201E${e}\u201C ist die Schrift von Plexus selbst \u2013 w\xE4hlen Sie f\xFCr eine eigene Datei einen anderen Familiennamen.`,en:`"${e}" is Plexus's own typeface \u2013 choose a different family name for your own file.`}:null:{de:"Speichern Sie zuerst die Schriftfamilie \u2013 die Datei wird unter diesem Namen eingebunden.",en:"Save the font family first \u2013 the file is registered under that name."}}s(PF,"fontFamilyProblem");var c3=["approved","rejected","withdrawn","waitlist","expired"];var Am=["admitted","rejected","withdrawn","waitlist","expired","unknown"],CEe=m.union(...c3.map(e=>m.literal(e))),DEe=m.union(...Am.map(e=>m.literal(e))),u3=["approved","rejected","waitlist"],f3=["withdrawn","expired"],p3=m.union(...u3.map(e=>m.literal(e))),m3=m.union(...f3.map(e=>m.literal(e))),FEe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:p3,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(m3),endedAt:m.number()}};var NF=30,CF=3650;var h3=m.object({admitted:m.optional(m.number()),rejected:m.optional(m.number()),withdrawn:m.optional(m.number()),expired:m.optional(m.number()),waitlist:m.optional(m.number()),unknown:m.optional(m.number())}),VEe=h3.fields,g3=s(e=>Am.includes(e),"isClassification");function DF(e,n="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${n} must be an object of days per classification (got ${JSON.stringify(e)}).`];let t=[];for(let[r,i]of Object.entries(e)){if(!g3(r)){t.push(`[retention/unknownClassification] ${n}.${r} is no retention classification \u2014 one of ${Am.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<NF||i>CF)&&t.push(`[retention/days] ${n}.${r} must be a whole number of days from ${NF} to ${CF} (got ${JSON.stringify(i)}).`)}return t}s(DF,"retentionDaysFindings");var y3=["ad","ae","af","ag","ai","al","am","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","um","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","xk","ye","yt","za","zm","zw"],w3=new Set(y3);function Em(e){return w3.has(e)}s(Em,"isCountryCode");var fb=["off","always","deviating"],FF={mode:"deviating",defaultCountryCode:"de"};var k3=["street","plz","ort"];function b3(e){return k3.filter(n=>!e.has(n))}s(b3,"missingInvoiceAddressParts");var v3=new Set(["0-1-select","0-n-select"]);function LF(e){return e===void 0?null:new Set(e.properties.flatMap(n=>n.addressPart!==void 0&&u_(n.addressPart)?[n.addressPart]:[]))}s(LF,"declaredAddressParts");function x3(e){return v3.has(e)}s(x3,"isSelectFieldKind");function MF(e){let n=[];for(let o of e)if(o.isNationality&&(x3(o.kind)?o.listKind!=="country"&&n.push({code:"nationality/notCountryList",fieldKey:o.key}):n.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&n.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&n.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)n.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=b3(o.addressParts);a.length>0&&n.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let t=e.filter(o=>o.isAccountEmail);if(t.length>1)for(let o of t)n.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)n.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)n.push({code:"invoiceAddress/multiple",fieldKey:o.key});return n}s(MF,"fieldRoleFindings");function qF(e,n,...t){let r=e[n.code];return r(n,...t)}s(qF,"wordListElementFinding");function KF(e,n){let t=[];for(let r of n){if(e.kind==="plain"){r.countryCode!==void 0&&t.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?t.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!Em(r.countryCode)&&t.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return t}s(KF,"listElementCountryFindings");var A3={key:!0,tenant:!0,foundation:!0,source:!0,displayGroups:!0,lists:!0,roles:!0,fields:!0,roleFields:!0,contractRoleMappings:!0,templatePlaceholders:!0,searchTargets:!0,searchFilters:!0,partyResultIcons:!0,notificationLetters:!0,admission:!0,files:!0,agent:!0,deferredColumns:!0,ignoredColumns:!0},E3={slug:!0,name:!0,enabledModules:!0,permissions:!0,defaultApplicantGroupKey:!0,defaultEnrolleeRoleKey:!0,priceCriteriaFacts:!0,defaultInteressentRoleKey:!0,admissionFieldDisplayGroupKey:!0,defaultStartInProxy:!0,terms:!0,retentionDays:!0,mailLevel:!0,notificationChrome:!0,hideMailLevelNotice:!0,unassignedTaskNoticeDays:!0,testMailRecipients:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},T3=new Set(["enabledMailCategories","mailEnabled"]);function $3(e){let n=s((t,r,i)=>t.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&T3.has(o))).map(o=>`[config/unknownKey] ${i}${o} is not a config field of this release \u2014 a typo, or a field a newer release introduced.`),"unknown");return[...n(Object.keys(e),A3,""),...n(Object.keys(e.tenant),E3,"tenant.")]}s($3,"unknownKeyFindings");var jF=["plain","country"],R3={"list/countryCodeMissing":s(({elementKey:e},n)=>`Element "${n}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},n)=>`Element "${n}.${e}" carries countryCode, but list "${n}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:n},t)=>`Element "${t}.${e}" has unknown countryCode ${JSON.stringify(n)}.`,"list/unknownCountryCode")},I3={"nationality/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isNationality but not a 0-1-select / 0-n-select.`,"nationality/wrongFieldKind"),"nationality/notCountryList":s(({fieldKey:e})=>`Field "${e}" is isNationality but its list is not kind "country".`,"nationality/notCountryList"),"accountEmail/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isAccountEmail but not an email field.`,"accountEmail/wrongFieldKind"),"accountEmail/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isAccountEmail fields \u2014 at most one per tenant.`,"accountEmail/multiple"),"contactPhone/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isContactPhone but not a tel field.`,"contactPhone/wrongFieldKind"),"contactPhone/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isContactPhone fields \u2014 at most one per tenant.`,"contactPhone/multiple"),"invoiceAddress/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isInvoiceAddress but not an object field.`,"invoiceAddress/wrongFieldKind"),"invoiceAddress/missingPart":s(({fieldKey:e,parts:n})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${n.join(", ")} (objectSchema.properties[].addressPart) \u2014 an invoice cannot print its address without them.`,"invoiceAddress/missingPart"),"invoiceAddress/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isInvoiceAddress fields \u2014 at most one per tenant.`,"invoiceAddress/multiple")};function O3(e){let n=I3[e.code];return n(e)}s(O3,"roleText");function _3(e){let n=[],t=e.tenant.nationalityFlag,r=typeof t=="object"&&t!==null?t:{},i=r.mode;if(fb.includes(i)||n.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${fb.join(", ")} (got ${t===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),t!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!Em(l))&&n.push(`[nationality/defaultCountryCode] tenant.nationalityFlag.defaultCountryCode must be a lowercase ISO 3166-1 alpha-2 code (got ${JSON.stringify(l??null)}).`)}let o=new Map;for(let l of e.lists){let d=l.kind;if(!jF.includes(d)){n.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${jF.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of KF({key:l.key,kind:l.kind},l.elements))n.push(`[${c.code}] ${qF(R3,c,l.key)}`)}let a=MF(e.fields.map(l=>({key:l.key,kind:l.type,listKind:l.listKey===void 0?null:o.get(l.listKey)??null,isNationality:l.isNationality===!0,isAccountEmail:l.isAccountEmail===!0,isContactPhone:l.isContactPhone===!0,isInvoiceAddress:l.isInvoiceAddress===!0,addressParts:l.type==="object"?LF(l.objectSchema??{properties:[]}):null})));for(let l of a)n.push(`[${l.code}] ${O3(l)}`);return n}s(_3,"nationalityFindings");function VF(e){return Ri(e)?.message.de??(e instanceof Error?e.message:String(e))}s(VF,"errorText");function GF(e,n={}){let t=[...$3(e)],r=[];try{mF(e.fields.map(v=>v.key),[])}catch(v){t.push(VF(v))}e.tenant.terms!==void 0&&t.push(...lb(e.tenant.terms)),e.tenant.retentionDays!==void 0&&t.push(...DF(e.tenant.retentionDays)),$P(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!yd(e.tenant.enabledModules,"notifications")&&t.push('[notification/levelWithoutModule] tenant.mailLevel is "all" but the notifications module is not enabled \u2014 only sign-in and security mail would go out. Enable the module or set "loginOnly".'):t.push(`[notification/mailLevel] tenant.mailLevel must be one of ${Lw.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`);let i=e.tenant.testMailRecipients;i!==void 0&&(!Array.isArray(i)||i.length===0||!i.every(v=>typeof v=="string"&&eb(v).includes("@"))?t.push("[notification/testRecipients] tenant.testMailRecipients must be a non-empty list of login addresses (leave it out for no test recipients)."):new Set(i.map(v=>eb(v))).size!==i.length&&t.push("[notification/testRecipients] tenant.testMailRecipients names an address twice."),(e.tenant.mailLevel!=="loginOnly"||!yd(e.tenant.enabledModules,"notifications"))&&t.push('[notification/testRecipientsWithoutEffect] tenant.testMailRecipients decides only at mailLevel "loginOnly" with the notifications module on \u2014 at "all" everybody gets mail, with the module off nobody. Remove the list or change the level.')),"enabledMailCategories"in e.tenant&&t.push('[notification/mailCategoriesRetired] tenant.enabledMailCategories was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),"mailEnabled"in e.tenant&&t.push('[notification/mailEnabledRetired] tenant.mailEnabled was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),Tn(e.displayGroups.map(v=>v.key),"display group",t),Tn(e.lists.map(v=>v.key),"list",t),Tn(e.roles.map(v=>v.key),"role",t),Tn(e.fields.map(v=>v.key),"field",t),Tn(e.foundation.legalEntities.map(v=>v.key),"legal entity",t),Tn(e.foundation.units.map(v=>v.key),"unit",t),Tn(e.foundation.permissionGroups.map(v=>v.key),"permission group",t),"teams"in e.foundation&&t.push("foundation.teams is retired: a team is a permission group \u2014 move each team to foundation.permissionGroups (same key) and remove the block.");for(let v of e.foundation.users)"teamKeys"in v&&t.push(`User "${v.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);Tn(e.foundation.users.map(v=>v.key),"user",t),Tn((e.searchFilters??[]).map(v=>v.key),"search filter",t),Tn((e.searchTargets??[]).map(v=>v.objectPropertyKey===void 0?v.fieldKey:`${v.fieldKey}.${v.objectPropertyKey}`),"search target",t),Tn((e.partyResultIcons??[]).map(v=>v.key),"party result icon",t),Tn((e.templatePlaceholders??[]).map(v=>v.key),"template placeholder",t),Tn((e.notificationLetters??[]).map(zF),"notification letter",t),q3(e.notificationLetters??[],t),K3(e.tenant.notificationChrome,t),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&t.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&t.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!RP(e.tenant.unassignedTaskNoticeDays)&&t.push("tenant.unassignedTaskNoticeDays must be a whole number from 1 to 30 (days before an unassigned team task is reported); leave it out for the platform default."),typeof e.tenant.magicLinkLogin!="boolean"&&t.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&t.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&t.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),uF(e.tenant.externalSignIn)?t.push(`[auth/externalSignInRetired] tenant.externalSignIn names the retired mode "${String(e.tenant.externalSignIn.mode)}" \u2014 every sign-in link now signs in once; state { mode: "oneTimeLink" }.`):cF(e.tenant.externalSignIn)||t.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let o=new Set(e.displayGroups.map(v=>v.key)),a=new Set(e.lists.map(v=>v.key)),l=new Set(e.roles.map(v=>v.key)),d=new Set(e.fields.map(v=>v.key)),c=new Map(e.fields.map(v=>[v.key,v])),u=new Set(e.foundation.legalEntities.map(v=>v.key)),p=new Set(e.foundation.units.map(v=>v.key)),h=new Set(e.foundation.permissionGroups.map(v=>v.key));yd(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(P=>P.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||t.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let w=e.tenant.admissionFieldDisplayGroupKey;w!==void 0&&!o.has(w)&&t.push(`tenant.admissionFieldDisplayGroupKey "${w}" names no display group of this config.`),w===void 0&&(yd(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&t.push("tenant.admissionFieldDisplayGroupKey is required when admissions is enabled or admission.fields declares fields: it names the display group the fields an offer creates land in."),t.push(..._3(e)),Tn(e.fields.flatMap(v=>(v.relationshipKinds??[]).map(P=>P.key)),"relationship kind",t);for(let v of e.fields){o.has(v.displayGroupKey)||t.push(`Field "${v.key}" references missing display group "${v.displayGroupKey}".`),N3(v,t),v.formWritable===!0&&!ob[v.type].fieldMapTarget&&t.push(`Field "${v.key}" is formWritable, but a form cannot write a "${v.type}" field.`),v.type==="files"&&v.shareable===!0&&t.push(`[field/filesShareable] Field "${v.key}" is a files field and cannot be shareable.`),v.type==="auto-string"?C3(v,c,t):v.autoString!==void 0&&t.push(`Non-automatic field "${v.key}" must not define autoString.`),(!Number.isFinite(v.sortOrder)||v.sortOrder<0)&&t.push(`Field "${v.key}" has invalid sortOrder "${v.sortOrder}" (must be a non-negative number).`),(v.type==="0-1-select"||v.type==="0-n-select")&&!v.listKey&&t.push(`Select field "${v.key}" must define listKey.`),v.type!=="0-1-select"&&v.type!=="0-n-select"&&v.listKey!==void 0&&t.push(`Non-select field "${v.key}" must not define listKey.`),v.listKey&&!a.has(v.listKey)&&t.push(`Field "${v.key}" references missing list "${v.listKey}".`),(v.type==="object"||v.type==="relationship")&&!v.objectSchema&&t.push(`Field "${v.key}" must define objectSchema.`),v.type!=="object"&&v.type!=="relationship"&&v.objectSchema&&t.push(`Non-object field "${v.key}" must not define objectSchema.`);for(let P of v.objectSchema?.properties??[])(P.type==="0-1-select"||P.type==="0-n-select")&&!P.listKey&&t.push(`Object select property "${v.key}.${P.key}" must define listKey.`),P.listKey&&!a.has(P.listKey)&&t.push(`Object property "${v.key}.${P.key}" references missing list "${P.listKey}".`);P3(v,t)}let k=e.tenant.priceCriteriaFacts;if(k){let v=e.fields.find(P=>P.key===k.birthDateFieldKey);(!v||v.type!=="date")&&t.push("Price criteria require a configured date field for birth dates."),l.has(k.studentRoleKey)||t.push("Price criteria require a configured Student eligibility role."),k.siblingRankSource!==void 0&&k.siblingRankSource!=="derived"&&k.siblingRankSource!=="chosen"&&t.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let P of Object.keys(k))P!=="birthDateFieldKey"&&P!=="studentRoleKey"&&P!=="siblingRankSource"&&t.push(`Unknown price criteria fact setting "${P}".`)}let y=e.tenant.defaultEnrolleeRoleKey;y&&!l.has(y)&&t.push(`Default enrollment role "${y}" does not exist.`),y&&e.roles.some(v=>v.parentRoleKey===y)&&t.push(`Default enrollment role "${y}" must be a leaf role.`);for(let v of e.roles){(typeof v.icon!="string"||v.icon.trim().length===0)&&t.push(`Role "${v.key}" must define an icon.`),v.parentRoleKey&&!l.has(v.parentRoleKey)&&t.push(`Role "${v.key}" references missing parent role "${v.parentRoleKey}".`);for(let P of v.listDisplayFieldKeys??[])d.has(P)||t.push(`Role "${v.key}" list display references missing field "${P}".`)}let b=new Map(e.roles.map(v=>[v.key,v.parentRoleKey])),E=new Map;for(let v of e.roleFields){let P=E.get(v.roleKey)??[];P.push({roleId:v.roleKey,customFieldId:v.fieldKey}),E.set(v.roleKey,P)}for(let v of e.roles)try{fF(v.key,b,E)}catch(P){t.push(VF(P))}for(let v of e.roleFields){l.has(v.roleKey)||t.push(`Role field references missing role "${v.roleKey}" for field "${v.fieldKey}".`),d.has(v.fieldKey)||t.push(`Role field references missing field "${v.fieldKey}" for role "${v.roleKey}".`);for(let P of v.targetRequirementFieldKeys??[])d.has(P)||t.push(`Role field "${v.roleKey}.${v.fieldKey}" references missing target requirement field "${P}".`)}M3(e.contractRoleMappings??[],l,t);for(let v of e.templatePlaceholders??[])UD.test(v.key)||t.push(`Template placeholder "${v.key}" must use lower_snake_case segments, optionally separated by dots.`),v.source.kind==="customField"?Tm(v.source,c,t,`Template placeholder "${v.key}"`):v.source.kind==="relationshipTargetField"&&D3(v,c,t);for(let v of e.searchTargets??[])Tm(v,c,t,"Search target");for(let v of e.fields)kF(v.key)&&(v.defaultValue!==void 0||v.validations!==void 0)&&t.push(`System field "${v.key}" takes no defaultValue or validations.`);for(let v of e.lists)Tn(v.elements.map((P,A)=>String(P.sortOrder??(A+1)*10)),`sortOrder of an element of list "${v.key}"`,t);for(let v of e.searchFilters??[])Tn((v.options??[]).map((P,A)=>String(P.sortOrder??(A+1)*10)),`sortOrder of an option of search filter "${v.key}"`,t);for(let v of e.foundation.permissionGroups){v.grantAllCustomFields===!0&&v.customFieldPermissions!==void 0&&t.push(`Permission group "${v.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),Tn((v.customFieldPermissions??[]).map(P=>P.displayGroupKey),`display group of a field permission of group "${v.key}"`,t);for(let P of v.customFieldPermissions??[]){o.has(P.displayGroupKey)||t.push(`Permission group "${v.key}" grants field permissions on missing display group "${P.displayGroupKey}".`);for(let A of P.permissions)gF.includes(A)||t.push(`Permission group "${v.key}" grants unknown field permission "${A}".`)}}let T=e.tenant.partyRetention;T!==void 0&&(wF(T.days)||t.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(T.days)}).`),Number.isFinite(T.enabledAt)||t.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),T.formerRoleKey!==void 0&&!l.has(T.formerRoleKey)&&t.push(`tenant.partyRetention references missing role "${T.formerRoleKey}".`));for(let v of e.searchFilters??[]){(v.kind==="chips"||v.kind==="select")&&(v.options?.length??0)===0&&t.push(`Search filter "${v.key}" must define options.`),(v.kind==="text"||v.kind==="numberRange")&&v.target===void 0&&t.push(`Search filter "${v.key}" must define a target field.`),v.options!==void 0&&Tn(v.options.map(P=>P.key),`search filter option for "${v.key}"`,t),Tm(v.target,c,t,`Search filter "${v.key}"`);for(let P of v.options??[]){P.predicates.length===0&&t.push(`Search filter option "${v.key}.${P.key}" must define at least one predicate.`);for(let A of P.predicates){if(A.kind==="role"){l.has(A.roleKey)||t.push(`Search filter option "${v.key}.${P.key}" references missing role "${A.roleKey}".`);continue}Tm(A,c,t,`Search filter option "${v.key}.${P.key}"`)}}}for(let v of e.partyResultIcons??[])F3(v,c,t);for(let v of e.foundation.legalEntities)if(v.terms!==void 0&&t.push(...lb(v.terms,`foundation.legalEntities.${v.key}.terms`)),BF(v.branding,t,`foundation.legalEntities.${v.key}.branding`),UF(v,t,`foundation.legalEntities.${v.key}`),v.signatoryUserKey!==void 0&&v.type==="school_group"&&t.push(`[config/signatoryOnGroup] Legal entity "${v.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),v.parentLegalEntityKey&&!u.has(v.parentLegalEntityKey)&&t.push(`Legal entity "${v.key}" references missing parent "${v.parentLegalEntityKey}".`),v.address!==void 0){let P=v.address,A=["street","hausnr","plz","ort"];v.type==="school_group"?t.push(`Legal entity "${v.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof P!="object"||P===null||Array.isArray(P)||Object.keys(P).some(M=>!A.includes(M))||A.some(M=>typeof P[M]!="string"||(P[M]??"").trim()===""))&&t.push(`Legal entity "${v.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let R=new Map;for(let v of e.foundation.units){if(v.slug!==void 0){let P=typeof v.slug=="string"?xI(v.slug):"must be a string";P!==void 0&&t.push(`Unit "${v.key}" has invalid slug "${v.slug}" (${P}).`);let A=R.get(v.slug);A!==void 0&&t.push(`Units "${A}" and "${v.key}" both declare slug "${v.slug}" (unit slugs are unique per tenant).`),R.set(v.slug,v.key)}u.has(v.legalEntityKey)||t.push(`Unit "${v.key}" references missing legal entity "${v.legalEntityKey}".`),v.parentUnitKey&&!p.has(v.parentUnitKey)&&t.push(`Unit "${v.key}" references missing parent unit "${v.parentUnitKey}".`),v.sortOrder!==void 0&&(!Number.isFinite(v.sortOrder)||v.sortOrder<0)&&t.push(`Unit "${v.key}" has invalid sortOrder "${v.sortOrder}" (must be a non-negative number).`)}let D=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let v of e.foundation.users){h.has(v.permissionGroupKey)||t.push(`User "${v.email}" references missing permission group "${v.permissionGroupKey}".`),v.unitKey&&!p.has(v.unitKey)&&t.push(`User "${v.email}" references missing unit "${v.unitKey}".`),v.status!==void 0&&v.status!=="deactivated"&&t.push(`User "${v.email}": status must be "deactivated" or absent, not "${String(v.status)}".`);let P=[v,...v.additionalMemberships??[]];for(let M of v.additionalMemberships??[])h.has(M.permissionGroupKey)||t.push(`User "${v.email}" references missing permission group "${M.permissionGroupKey}".`),M.unitKey&&!p.has(M.unitKey)&&t.push(`User "${v.email}" references missing unit "${M.unitKey}".`);Tn(P.map(M=>`${M.permissionGroupKey}/${M.unitKey??""}`),`membership (permission group/unit) of user "${v.email}"`,t);for(let M of P)M.validFrom!==void 0&&M.validTo!==void 0&&M.validTo<=M.validFrom&&t.push(`User "${v.email}": membership "${M.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let A=[v.firstName,v.lastName];A.some(M=>M!==void 0)&&A.some(M=>typeof M!="string"||M.trim()==="")&&t.push(`[config/userNameIncomplete] User "${v.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let M of["staging","prod"]){let U=v.passwordHashes?.[M];U!==void 0&&!D.test(U)&&t.push(`User "${v.email}" passwordHashes.${M} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}BF(e.tenant.branding,t),UF(e.tenant,t);let L=WF(e.fields.flatMap(v=>v.sourceColumns));for(let v of L)r.push(`Source column "${v}" is mapped by more than one field.`);B3(e,t);let _=n.sourceColumns===void 0||e.source===void 0?void 0:j3(e,n.sourceColumns,t);return{ok:t.length===0,errors:t,warnings:r,coverage:_}}s(GF,"validateTenantConfig");function P3(e,n){let t=new Map;for(let r of e.objectSchema?.properties??[]){let i=r.addressPart;if(i===void 0)continue;let o=`Object property "${e.key}.${r.key}"`;if(!pw.includes(i)){n.push(`${o}: addressPart "${i}" is none of ${pw.join(", ")}.`);continue}e.type!=="object"&&n.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&n.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=t.get(i);a!==void 0&&n.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),t.set(i,r.key)}}s(P3,"validateAddressParts");function N3(e,n){let t=e.relationshipKinds;if(t===void 0)return;if(e.type!=="relationship"){n.push(`Field "${e.key}" declares relationshipKinds, but only a relationship field carries them.`);return}let r=new Map((e.objectSchema?.properties??[]).map(i=>[i.key,i]));for(let i of t){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){n.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&n.push(`${o}: label.${l} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);if(i.edge===null||typeof i.edge!="object"||Array.isArray(i.edge)){n.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&n.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=t.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare a property another kind of the field merges into.`),i.sibling===!0&&Object.keys(i.edge).length===0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 an empty edge would count every edge of the field.`),i.mergeInto!==void 0){let l=r.get(i.mergeInto);l===void 0||l.type!=="0-n-select"?n.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||n.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(N3,"validateRelationshipKinds");function C3(e,n,t){if(e.autoString===void 0){t.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&t.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&t.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&t.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&t.push(`Automatic field "${e.key}" must define exactly one sequence segment.`);for(let i of e.autoString.segments)if(i.kind==="literal"&&i.value.length===0&&t.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&t.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&t.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=n.get(i.fieldKey);if(o===void 0){t.push(`Automatic field "${e.key}" references missing field "${i.fieldKey}".`);continue}i.objectPropertyKey!==void 0&&o.objectSchema?.properties.find(l=>l.key===i.objectPropertyKey)===void 0&&t.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(C3,"validateAutomaticStringField");function Tm(e,n,t,r){if(e===void 0)return;let i=n.get(e.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||t.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(Tm,"validateSearchTarget");function D3(e,n,t){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=n.get(e.source.relationshipFieldKey);if(i===void 0)t.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")t.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])pb(i,a.propertyKey,t,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&pb(i,e.source.selection.sortPropertyKey,t,`${r} selection sort`)}let o=n.get(e.source.targetFieldKey);if(o===void 0){t.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&t.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&pb(o,e.source.targetObjectPropertyKey,t,`${r} target`)}s(D3,"validateRelationshipTemplatePlaceholder");function pb(e,n,t,r){(e.objectSchema?.properties.some(o=>o.key===n)??!1)||t.push(`${r} references missing object property "${e.key}.${n}".`)}s(pb,"validateObjectPropertyReference");function F3(e,n,t){let r=`Party result icon "${e.key}"`,i=n.get(e.when.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`);return}let o=i.objectSchema?.properties.find(a=>a.key===e.when.objectPropertyKey);if(o===void 0){t.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`)}s(F3,"validatePartyResultIconTarget");function zF(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(zF,"letterIdentity");function L3(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(L3,"contractRoleMappingIdentity");function M3(e,n,t){let r=new Set;for(let i of e){let o=L3(i),a=`Contract role mapping "${o}"`;nb.includes(i.partyKind)||t.push(`${a}: partyKind must be one of ${nb.join(", ")}.`),i.partyKind==="beneficiary"&&t.push(`${a}: a beneficiary holds the enrollee role of the program it attends (programs.enrolleeRoleKey, else tenant.defaultEnrolleeRoleKey) \u2014 remove the mapping.`),n.has(i.roleKey)||t.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&t.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&t.push(`${a} is declared twice.`),r.add(o)}}s(M3,"validateContractRoleMappings");function q3(e,n){for(let t of e){let r=`Notification letter "${zF(t)}"`;if(!bm(t.locale)){n.push(`${r} declares locale "${String(t.locale)}" \u2014 letters are written in ${Ye.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(t.scopeKey!==wm){n.push(`${r} declares scopeKey "${t.scopeKey}" \u2014 the only scope is "${wm}" (the whole school).`);continue}if(Object.keys(t.slots).length===0){n.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!Uw(t.templateId)){n.push(`${r} references no registered letter \u2014 "${t.templateId}" is not in the letter catalog.`);continue}for(let i of TF(Bw(t.templateId),t.slots,t.locale))n.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(q3,"validateNotificationLetters");function K3(e,n){if(e!==void 0)for(let t of $F(e))n.push(`Notification chrome: ${t.de}`)}s(K3,"validateNotificationChrome");function BF(e,n,t){if(e===void 0)return;let r=t===void 0?n:{push:s((...p)=>n.push(...p.map(h=>`${t}: ${h}`)),"push")},i=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,o=/^(?:rgb|rgba|hsl|hsla)\(.+\)$/i,a=s(p=>i.test(p.trim())||o.test(p.trim()),"isColor");for(let[p,h]of Object.entries(e.colors??{}))h!==void 0&&(a(h)||r.push(`Branding color "colors.${p}" has invalid value "${h}" (expected hex "#rgb"/"#rrggbb"/"#rrggbbaa" or rgb()/rgba()/hsl()/hsla()).`));let l=["sharp","rounded","soft"];e.radius!==void 0&&!l.includes(e.radius)&&r.push(`Branding radius "${e.radius}" is invalid (expected "sharp", "rounded", or "soft").`);let d=["sm","md","lg","max"];e.logoSize!==void 0&&!d.includes(e.logoSize)&&r.push(`Branding logoSize "${e.logoSize}" is invalid (expected "sm", "md", "lg", or "max").`);let c=["compact","normal","spacious"];e.bannerDensity!==void 0&&!c.includes(e.bannerDensity)&&r.push(`Branding bannerDensity "${e.bannerDensity}" is invalid (expected "compact", "normal", or "spacious").`);let u=["light","dark"];e.logoGround!==void 0&&!u.includes(e.logoGround)&&r.push(`Branding logoGround "${e.logoGround}" is invalid (expected "light" or "dark").`),e.websiteUrl!==void 0&&!e.websiteUrl.startsWith("https://")&&r.push(`Branding websiteUrl must be an https:// URL (got "${e.websiteUrl}").`);for(let p of["heading","body"]){let h=e.fonts?.[p];h!==void 0&&((typeof h.family!="string"||h.family.trim().length===0)&&r.push(`Branding font "fonts.${p}" must define a non-empty family.`),Object.hasOwn(h,"url")&&r.push(`Branding font "fonts.${p}.url" is no longer supported \u2014 the font file is uploaded (plexus-cli branding set-font --slot ${p} --file <woff2>) and config carries the family only.`))}}s(BF,"validateBranding");function UF(e,n,t="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){n.push(`${t}.brandingAssets must be an object keyed by slot (${Sm.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${t}.brandingAssets.${i}`;if(!Sm.includes(i)){n.push(`${a}: unknown slot (expected ${Sm.join(", ")}).`);continue}if(typeof o!="object"||o===null){n.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){n.push(`[config/fileRefRenamed] ${a} still names size \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}YF.test(o.sha256??"")||n.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&n.push(`${a}: sizeBytes must be a positive integer.`);let l=OF[i];if(l===null){let d=_F({contentType:o.mimeType,size:o.sizeBytes});d!==null&&n.push(`${a}: ${d.de}`)}else{o.mimeType!==ub&&n.push(`${a}: mimeType must be "${ub}" (got "${o.mimeType}").`);let d=PF(e.branding?.fonts?.[l]?.family);d!==null&&n.push(`${a}: [branding/fontFamilyMissing] ${t}.branding.fonts.${l}: ${d.de}`)}"path"in o&&n.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(UF,"validateBrandingAssets");function j3(e,n,t){let{source:r}=e;r===void 0&&F("validateSourceCoverage: called without a `source` block.");let i=new Set(n),o=new Set(e.fields.flatMap(k=>k.sourceColumns)),a=new Set(e.deferredColumns.map(k=>k.column)),l=new Set(e.ignoredColumns.map(k=>k.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(k=>!i.has(k)),u=n.filter(k=>!d.has(k)),p=[...o].filter(k=>!i.has(k)),h=[...a].filter(k=>!i.has(k)),w=[...l].filter(k=>!i.has(k));for(let k of c)t.push(`Required source column "${k}" is missing from ${r.primaryTable}.`);for(let k of u)t.push(`Source column "${k}" is neither mapped nor explicitly deferred/ignored.`);for(let k of p)t.push(`Mapped source column "${k}" does not exist in the source schema.`);for(let k of h)t.push(`Deferred source column "${k}" does not exist in the source schema.`);for(let k of w)t.push(`Ignored source column "${k}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:n.length,mappedColumns:[...o].filter(k=>i.has(k)).length,deferredColumns:[...a].filter(k=>i.has(k)).length,ignoredColumns:[...l].filter(k=>i.has(k)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:w}}s(j3,"validateSourceCoverage");function Tn(e,n,t){for(let r of WF(e))t.push(`Duplicate ${n} key "${r}".`)}s(Tn,"requireUnique");function WF(e){let n=new Set,t=new Set;for(let r of e)n.has(r)&&t.add(r),n.add(r);return[...t]}s(WF,"duplicates");var YF=/^[0-9a-f]{64}$/,V3=["fileName","size"];function B3(e,n){if(!Array.isArray(e.files)){n.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}Tn(e.files.map(t=>t.key),"file",n);for(let t of e.files){let r=`files["${t.key}"]`;Ea(t.key)||n.push(`${r}: key must match ${Ok}.`);for(let o of["de","en"])(t.label?.[o]??"").trim()===""&&n.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=V3.filter(o=>o in t);if(i.length>0){n.push(`[config/fileRefRenamed] ${r} still names ${i.join(", ")} \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now filename / sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}if(typeof t.filename!="string")n.push(`${r}: filename is missing.`);else{let o=Wo(t.filename);o!==null&&n.push(`${r}: filename ${o}.`)}km.includes(t.mimeType)||n.push(`${r}: mimeType "${t.mimeType}" is not allowed (${km.join(", ")}).`),YF.test(t.sha256??"")||n.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(t.sizeBytes)||t.sizeBytes<=0)&&n.push(`${r}: sizeBytes must be a positive integer.`),"path"in t&&n.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(B3,"validateFiles");var U3=new WeakMap,G3=new WeakSet;function mb(e,n){n(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>mb(r(),n),"value"),enumerable:!1}),e}s(mb,"carry");function Pa(e,n){return mb(e,t=>U3.set(t,n))}s(Pa,"tagged");var z3="tenant teardown drains every table explicitly (config/wipe.ts)",Ve={belongsTo:s(e=>Pa(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>Pa(e,{kind:"owns"}),"owns"),holds:s(e=>Pa(e,{kind:"holds"}),"holds"),restrict:s((e,n)=>Pa(e,n?{kind:"restrict",unindexed:n.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>Pa(e,{kind:"history"}),"history"),tenant:s(e=>Pa(e,{kind:"restrict",unindexed:z3}),"tenant"),historyOf:s(e=>mb(e,n=>G3.add(n)),"historyOf")};var W3=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),HF=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),Jr=HF.members.map(e=>e.value),Y3={tenantId:Ve.tenant(m.id("tenants")),name:m.optional(m.string()),type:HF,parentLegalEntityId:m.optional(Ve.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(Ve.restrict(m.id("parties"))),address:m.optional(W3),signatoryUserId:m.optional(Ve.restrict(m.id("users"))),terms:m.optional(AF)},KTe=Ct(Y3).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var H3=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Kt=H3.members.map(e=>e.value),BTe=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),UTe=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),GTe=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),zTe=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),WTe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),YTe=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),HTe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),JTe=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),QTe=m.union(m.literal("units"),m.literal("unit_profiles"),m.literal("programs"),m.literal("program_stages"),m.literal("program_runs"),m.literal("learning_groups"),m.literal("enrollments"),m.literal("learning_group_staff_assignments")),ZTe=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function QF(e){let n=["street","hausnr","plz","ort"].filter(t=>e[t]!==void 0);if(n.length!==0){if(n.length!==4)throw new Error(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${n.map(t=>`--${t}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(QF,"addressFrom");function ZF(e){if(!Jr.includes(e))throw new Error(`config legal-entity add: --type "${e}" is none of ${Jr.join(", ")}`);return e}s(ZF,"legalEntityType");function XF(e){if(!Kt.includes(e))throw new Error(`config unit add: --kind "${e}" is none of ${Kt.join(", ")}`);return e}s(XF,"unitKind");function eL(e,n,t){let r=e.find(i=>i.key===n.key);if(r===void 0)return e.push(n),"create";if(Pe(r)===Pe(n))return"same";throw new Error(`${t} "${n.key}" already exists with other values \u2014 decide by hand, nothing written.
11303
+ The Plexus team`}},G4={de:{...kd.de,closing:null},en:{...kd.en,closing:null}};var z4=/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,Jo=2e3;function vm(e){let n=[];for(let t of e.matchAll(z4)){let r=t[1];n.includes(r)||n.push(r)}return n}s(vm,"placeholdersIn");function EF(e){return e.slots??[]}s(EF,"slotsOf");function W4(e){return e.bodyVariants!==void 0?e.bodyVariants:[EF(e).filter(n=>n.key!==Ul).map(n=>n.key)]}s(W4,"bodyVariantsOf");var Y4=/:\/\/|www\.|mailto:/i;function H4(e,n){let t=`{{${n}}}`,r=0;for(;;){let i=e.indexOf(t,r);if(i===-1)return!1;let o=i===0?"":e[i-1],a=e[i+t.length]??"";if(o!==""&&!/\s/.test(o)||a!==""&&!/[\s.,;:!?)]/.test(a))return!0;r=i+t.length}}s(H4,"linkGlued");function J4(e,n){let t=e.default[n];return(typeof t!="string"||t.length===0)&&F(`notifications: slot "${e.key}" has no "${n}" text`),t}s(J4,"defaultText");function TF(e,n,t){let r=[],i=EF(e),o=e.placeholders??[],a=o.map(u=>u.key),l=o.filter(u=>u.subjectSafe===!0).map(u=>u.key);for(let[u,p]of Object.entries(n)){let h=i.find(w=>w.key===u);if(h===void 0){r.push({slotKey:u,code:"unknownSlot",message:i.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C l\xE4sst sich nicht anpassen.`,en:`The notification "${e.label}" cannot be customized.`}:{de:`Der Baustein \u201E${u}\u201C geh\xF6rt nicht zur Benachrichtigung \u201E${e.label}\u201C.`,en:`The block "${u}" does not belong to the letter "${e.label}".`}});continue}if(p.trim().length===0){r.push({slotKey:u,code:"empty",message:{de:`\u201E${h.label}\u201C darf nicht leer sein. Zum Entfernen den Baustein zur\xFCcksetzen.`,en:`"${h.label}" must not be empty. To remove it, reset the block.`}});continue}if(p.length>Jo){r.push({slotKey:u,code:"tooLong",message:{de:`\u201E${h.label}\u201C ist ${p.length} Zeichen lang, erlaubt sind ${Jo}.`,en:`"${h.label}" is ${p.length} characters long; the limit is ${Jo}.`}});continue}if(OP(e)){Y4.test(p)&&r.push({slotKey:u,code:"foreignUrl",message:{de:`\u201E${h.label}\u201C enth\xE4lt eine Adresse. Die Benachrichtigung \u201E${e.label}\u201C tr\xE4gt einen Anmeldeschl\xFCssel und darf keine weiteren Links enthalten.`,en:`"${h.label}" contains an address. The notification "${e.label}" carries a sign-in key and must not contain any further links.`}});for(let w of o)w.link!==!0||!H4(p,w.key)||r.push({slotKey:u,code:"linkNotStandalone",message:{de:`\u201E{{${w.key}}}\u201C (${w.label}) muss f\xFCr sich stehen \u2014 davor und dahinter nur ein Leerzeichen, ein Zeilenumbruch oder ein Satzzeichen.`,en:`"{{${w.key}}}" (${w.label}) must stand on its own \u2014 only a space, a line break or punctuation before and after it.`}})}for(let w of vm(p)){if(!a.includes(w)){r.push({slotKey:u,code:"unknownPlaceholder",message:w===Hr?{de:`\u201E{{${Hr}}}\u201C (${_a}) geh\xF6rt in die Anrede der Schule (unter \u201EAnrede und Gru\xDFformel\u201C), nicht in \u201E${h.label}\u201C \u2014 dort gibt es eine neutrale Anrede, wenn kein Name bekannt ist.`,en:`"{{${Hr}}}" (${_a}) belongs in the school's greeting (under \u201CGreeting and sign-off\u201D), not in "${h.label}" \u2014 the greeting has a neutral form for when no name is known.`}:a.length===0?{de:`Die Benachrichtigung \u201E${e.label}\u201C kennt keine Platzhalter, \u201E{{${w}}}\u201C bliebe unersetzt stehen.`,en:`The notification "${e.label}" has no placeholders; "{{${w}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${w}}}\u201C gibt es in \u201E${e.label}\u201C nicht. Erlaubt: ${a.map(y=>`{{${y}}}`).join(", ")}.`,en:`"{{${w}}}" does not exist in "${e.label}". Allowed: ${a.map(y=>`{{${y}}}`).join(", ")}.`}});continue}if(u!==Ul||l.includes(w))continue;let k=o.find(y=>y.key===w)?.label??w;r.push({slotKey:u,code:"subjectUnsupported",message:{de:`\u201E{{${w}}}\u201C (${k}) l\xE4sst sich im Betreff nicht einsetzen \u2014 der Wert entsteht erst beim Versand. `+(l.length===0?"In dieser Benachrichtigung kann der Betreff keine Platzhalter tragen.":`Im Betreff m\xF6glich: ${l.map(y=>`{{${y}}}`).join(", ")}.`),en:`"{{${w}}}" (${k}) cannot be used in the subject \u2014 the value only exists when the mail is sent. `+(l.length===0?"In this letter the subject cannot carry placeholders.":`Possible in the subject: ${l.map(y=>`{{${y}}}`).join(", ")}.`)}})}}let d=s(u=>n[u]??Q4(i,u,t),"textOf"),c=W4(e);for(let u of o){if(u.required!==!0)continue;let p=c.filter(y=>!vm(y.map(d).join(`
11304
+ `)).includes(u.key));if(p.length===0)continue;let h=s((y,b)=>y.map(E=>b(i.find(T=>T.key===E)?.label??E)).join(" + "),"variantLabel"),w=c.length===1?"":` Er fehlt in der Fassung aus ${p.map(y=>h(y,b=>`\u201E${b}\u201C`)).join(" und in der aus ")}.`,k=c.length===1?"":` It is missing in the version made of ${p.map(y=>h(y,b=>`"${b}"`)).join(" and in the one made of ")}.`;r.push({slotKey:u.key,code:"missingRequired",message:{de:`Ohne \u201E{{${u.key}}}\u201C (${u.label}) funktioniert die Benachrichtigung \u201E${e.label}\u201C nicht \u2014 der Platzhalter muss im Text stehen, nicht nur im Betreff.`+w,en:`Without "{{${u.key}}}" (${u.label}) the notification "${e.label}" does not work \u2014 the placeholder must be in the text, not only in the subject.`+k}})}return r}s(TF,"validateOverride");function Q4(e,n,t){let r=e.find(i=>i.key===n);return r===void 0?"":J4(r,t)}s(Q4,"defaultTextOf");function db(e){let n=e?.trim();return n===void 0||n.length===0?void 0:n}s(db,"normalizeChromeText");var Qo=s(e=>String.fromCharCode(e),"cp"),Z4=new RegExp(`[${Qo(0)}-${Qo(31)}${Qo(127)}]`,"g"),X4=new RegExp(`[${Qo(8234)}-${Qo(8238)}${Qo(8294)}-${Qo(8297)}]`,"g");var e3=200;function n3(e,n=e3){return e.replace(Z4," ").replace(X4,"").replace(/\s+/g," ").trim().slice(0,n)}s(n3,"sanitizeHeaderValue");function xm(e){return n3(e.replace(/["<>@]/g,""),100)}s(xm,"sanitizeDisplayName");var cb={de:{de:"Deutsch",en:"German"},en:{de:"Englisch",en:"English"}},t3={greeting:{de:"Anrede",en:"Greeting"},closing:{de:"Gru\xDFformel",en:"Closing"}};function $F(e){let n=[],t=[];for(let i of["greeting","closing"]){let o=e[i];if(o===void 0)continue;let a=t3[i],l=In(o);l!=="not-localized"&&l.length>0&&l.length<Ye.length&&t.push({de:`${a.de} fehlt auf ${l.map(d=>cb[d].de).join(" und ")}`,en:`${a.en} is missing in ${l.map(d=>cb[d].en).join(" and ")}`});for(let d of Ye){let c=Pw(h=>`${a[h]} (${cb[d][h]})`),u=db(o[d]);u!==void 0&&u.length>Jo&&n.push({de:`${c.de} hat ${u.length} Zeichen \u2014 h\xF6chstens ${Jo}; Anrede und Gru\xDFformel sind je eine Zeile der Mail, kein Dokument.`,en:`${c.en} has ${u.length} characters \u2014 at most ${Jo}; the greeting and the sign-off are one line of the mail each, not a document.`});let p=i==="greeting"?[Hr]:[];for(let h of vm(u??""))p.includes(h)||n.push(p.length===0?{de:`${c.de} kann keine Platzhalter tragen \u2014 \u201E{{${h}}}\u201C bliebe unersetzt stehen.`,en:`${c.en} cannot carry placeholders \u2014 "{{${h}}}" would stay in the text unreplaced.`}:{de:`\u201E{{${h}}}\u201C gibt es in der ${c.de} nicht. Erlaubt: {{${Hr}}} (${_a}).`,en:`"{{${h}}}" does not exist in the ${c.en}. Allowed: {{${Hr}}} (${_a}).`})}}t.length>0&&n.unshift({de:`[notification/chromeMissingTranslation] ${t.map(i=>i.de).join("; ")} \u2014 Anrede und Gru\xDFformel gelten f\xFCr jede Benachrichtigung, in jeder Sprache.`,en:`[notification/chromeMissingTranslation] ${t.map(i=>i.en).join("; ")} \u2014 the greeting and sign-off apply to every notification, in every language.`});let r=db(e.senderName);return r!==void 0&&xm(r)!==r&&n.push({de:`Absendername (senderName) \u201E${r}\u201C \xFCbersteht die Kopfzeile der Mail nicht unver\xE4ndert \u2014 er ginge als \u201E${xm(r)}\u201C hinaus. Keine Anf\xFChrungszeichen, spitzen Klammern, \u201E@\u201C oder Steuerzeichen.`,en:`The sender name (senderName) "${r}" does not survive the mail header unchanged \u2014 it would go out as "${xm(r)}". No quotation marks, angle brackets, "@" or control characters.`}),n}s($F,"chromeFindings");var RF=m.object({family:m.string()}),IF=m.object({family:m.string(),url:m.optional(m.string())}),xEe=m.object({heading:m.optional(IF),body:m.optional(IF)}),r3=m.union(m.literal("sharp"),m.literal("rounded"),m.literal("soft")),i3=m.union(m.literal("light"),m.literal("dark")),o3=m.union(m.literal("sm"),m.literal("md"),m.literal("lg"),m.literal("max")),s3=m.union(m.literal("compact"),m.literal("normal"),m.literal("spacious")),a3=m.object({primary:m.optional(m.string()),accent:m.optional(m.string()),background:m.optional(m.string()),foreground:m.optional(m.string())}),l3=m.object({heading:m.optional(RF),body:m.optional(RF)}),SEe=m.object({colors:m.optional(a3),radius:m.optional(r3),logoSize:m.optional(o3),bannerDensity:m.optional(s3),logoGround:m.optional(i3),filledHeader:m.optional(m.boolean()),websiteUrl:m.optional(m.string()),fonts:m.optional(l3)}),AEe=m.object({primaryUrl:m.union(m.null(),m.string())}),EEe=m.literal("primary"),TEe=m.object({headingUrl:m.union(m.null(),m.string()),bodyUrl:m.union(m.null(),m.string())}),$Ee=m.union(m.literal("heading"),m.literal("body")),Sm=["logo","fontHeading","fontBody"],OF={logo:null,fontHeading:"heading",fontBody:"body"};function _F(e){let{contentType:n,size:t}=e;return n==null||!n.startsWith("image/")?{de:`Das Logo muss ein Bild sein (erhalten: \u201E${n??"unbekannt"}\u201C).`,en:`The logo must be an image (received: "${n??"unknown"}").`}:n.startsWith("image/svg")?{de:"Das Logo muss eine Rastergrafik sein (PNG, JPEG oder GIF) \u2013 E-Mail-Programme zeigen SVG nicht an.",en:"The logo must be a raster image (PNG, JPEG or GIF) \u2013 email clients do not display SVG."}:t>3e6?{de:`Das Logo ist zu gro\xDF (${t} Byte, h\xF6chstens 3000000 Byte).`,en:`The logo is too large (${t} bytes, at most 3000000 bytes).`}:null}s(_F,"logoFileProblem");var ub="font/woff2";var d3=["Inter Variable","Azeret Mono Variable","Source Sans 3 Variable"];function PF(e){return e?.trim()?d3.some(n=>n.toLowerCase()===e.trim().toLowerCase())?{de:`\u201E${e}\u201C ist die Schrift von Plexus selbst \u2013 w\xE4hlen Sie f\xFCr eine eigene Datei einen anderen Familiennamen.`,en:`"${e}" is Plexus's own typeface \u2013 choose a different family name for your own file.`}:null:{de:"Speichern Sie zuerst die Schriftfamilie \u2013 die Datei wird unter diesem Namen eingebunden.",en:"Save the font family first \u2013 the file is registered under that name."}}s(PF,"fontFamilyProblem");var c3=["approved","rejected","withdrawn","waitlist","expired"];var Am=["admitted","rejected","withdrawn","waitlist","expired","unknown"],CEe=m.union(...c3.map(e=>m.literal(e))),DEe=m.union(...Am.map(e=>m.literal(e))),u3=["approved","rejected","waitlist"],f3=["withdrawn","expired"],p3=m.union(...u3.map(e=>m.literal(e))),m3=m.union(...f3.map(e=>m.literal(e))),FEe={active:{status:m.literal("active")},completed:{status:m.literal("completed"),outcome:p3,endedAt:m.number()},aborted:{status:m.literal("aborted"),outcome:m.optional(m3),endedAt:m.number()}};var NF=30,CF=3650;var h3=m.object({admitted:m.optional(m.number()),rejected:m.optional(m.number()),withdrawn:m.optional(m.number()),expired:m.optional(m.number()),waitlist:m.optional(m.number()),unknown:m.optional(m.number())}),VEe=h3.fields,g3=s(e=>Am.includes(e),"isClassification");function DF(e,n="tenant.retentionDays"){if(e===null||typeof e!="object"||Array.isArray(e))return[`[retention/shape] ${n} must be an object of days per classification (got ${JSON.stringify(e)}).`];let t=[];for(let[r,i]of Object.entries(e)){if(!g3(r)){t.push(`[retention/unknownClassification] ${n}.${r} is no retention classification \u2014 one of ${Am.join(", ")}.`);continue}(typeof i!="number"||!Number.isSafeInteger(i)||i<NF||i>CF)&&t.push(`[retention/days] ${n}.${r} must be a whole number of days from ${NF} to ${CF} (got ${JSON.stringify(i)}).`)}return t}s(DF,"retentionDaysFindings");var y3=["ad","ae","af","ag","ai","al","am","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","um","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","xk","ye","yt","za","zm","zw"],w3=new Set(y3);function Em(e){return w3.has(e)}s(Em,"isCountryCode");var fb=["off","always","deviating"],FF={mode:"deviating",defaultCountryCode:"de"};var k3=["street","plz","ort"];function b3(e){return k3.filter(n=>!e.has(n))}s(b3,"missingInvoiceAddressParts");var v3=new Set(["0-1-select","0-n-select"]);function LF(e){return e===void 0?null:new Set(e.properties.flatMap(n=>n.addressPart!==void 0&&u_(n.addressPart)?[n.addressPart]:[]))}s(LF,"declaredAddressParts");function x3(e){return v3.has(e)}s(x3,"isSelectFieldKind");function MF(e){let n=[];for(let o of e)if(o.isNationality&&(x3(o.kind)?o.listKind!=="country"&&n.push({code:"nationality/notCountryList",fieldKey:o.key}):n.push({code:"nationality/wrongFieldKind",fieldKey:o.key})),o.isAccountEmail&&o.kind!=="email"&&n.push({code:"accountEmail/wrongFieldKind",fieldKey:o.key}),o.isContactPhone&&o.kind!=="tel"&&n.push({code:"contactPhone/wrongFieldKind",fieldKey:o.key}),o.isInvoiceAddress)if(o.addressParts===null)n.push({code:"invoiceAddress/wrongFieldKind",fieldKey:o.key});else{let a=b3(o.addressParts);a.length>0&&n.push({code:"invoiceAddress/missingPart",fieldKey:o.key,parts:a})}let t=e.filter(o=>o.isAccountEmail);if(t.length>1)for(let o of t)n.push({code:"accountEmail/multiple",fieldKey:o.key});let r=e.filter(o=>o.isContactPhone);if(r.length>1)for(let o of r)n.push({code:"contactPhone/multiple",fieldKey:o.key});let i=e.filter(o=>o.isInvoiceAddress);if(i.length>1)for(let o of i)n.push({code:"invoiceAddress/multiple",fieldKey:o.key});return n}s(MF,"fieldRoleFindings");function qF(e,n,...t){let r=e[n.code];return r(n,...t)}s(qF,"wordListElementFinding");function KF(e,n){let t=[];for(let r of n){if(e.kind==="plain"){r.countryCode!==void 0&&t.push({code:"list/countryCodeOnPlain",elementKey:r.key,countryCode:r.countryCode});continue}r.countryCode===void 0?t.push({code:"list/countryCodeMissing",elementKey:r.key}):r.countryCode!==null&&!Em(r.countryCode)&&t.push({code:"list/unknownCountryCode",elementKey:r.key,countryCode:r.countryCode})}return t}s(KF,"listElementCountryFindings");var A3={key:!0,tenant:!0,foundation:!0,source:!0,displayGroups:!0,lists:!0,roles:!0,fields:!0,roleFields:!0,contractRoleMappings:!0,templatePlaceholders:!0,searchTargets:!0,searchFilters:!0,partyResultIcons:!0,notificationLetters:!0,admission:!0,files:!0,agent:!0,deferredColumns:!0,ignoredColumns:!0},E3={slug:!0,name:!0,enabledModules:!0,permissions:!0,defaultApplicantGroupKey:!0,defaultEnrolleeRoleKey:!0,priceCriteriaFacts:!0,defaultInteressentRoleKey:!0,admissionFieldDisplayGroupKey:!0,defaultStartInProxy:!0,terms:!0,retentionDays:!0,mailLevel:!0,notificationChrome:!0,hideMailLevelNotice:!0,unassignedTaskNoticeDays:!0,testMailRecipients:!0,magicLinkLogin:!0,externalSignIn:!0,nationalityFlag:!0,adminSeesSignatureImages:!0,signatureStamp:!0,bankImportScope:!0,branding:!0,brandingAssets:!0,partyRetention:!0},T3=new Set(["enabledMailCategories","mailEnabled"]);function $3(e){let n=s((t,r,i)=>t.filter(o=>!Object.hasOwn(r,o)&&!(i==="tenant."&&T3.has(o))).map(o=>`[config/unknownKey] ${i}${o} is not a config field of this release \u2014 a typo, or a field a newer release introduced.`),"unknown");return[...n(Object.keys(e),A3,""),...n(Object.keys(e.tenant),E3,"tenant.")]}s($3,"unknownKeyFindings");var jF=["plain","country"],R3={"list/countryCodeMissing":s(({elementKey:e},n)=>`Element "${n}.${e}" of a country list must state countryCode (null for no state).`,"list/countryCodeMissing"),"list/countryCodeOnPlain":s(({elementKey:e},n)=>`Element "${n}.${e}" carries countryCode, but list "${n}" is not kind "country".`,"list/countryCodeOnPlain"),"list/unknownCountryCode":s(({elementKey:e,countryCode:n},t)=>`Element "${t}.${e}" has unknown countryCode ${JSON.stringify(n)}.`,"list/unknownCountryCode")},I3={"nationality/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isNationality but not a 0-1-select / 0-n-select.`,"nationality/wrongFieldKind"),"nationality/notCountryList":s(({fieldKey:e})=>`Field "${e}" is isNationality but its list is not kind "country".`,"nationality/notCountryList"),"accountEmail/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isAccountEmail but not an email field.`,"accountEmail/wrongFieldKind"),"accountEmail/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isAccountEmail fields \u2014 at most one per tenant.`,"accountEmail/multiple"),"contactPhone/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isContactPhone but not a tel field.`,"contactPhone/wrongFieldKind"),"contactPhone/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isContactPhone fields \u2014 at most one per tenant.`,"contactPhone/multiple"),"invoiceAddress/wrongFieldKind":s(({fieldKey:e})=>`Field "${e}" is isInvoiceAddress but not an object field.`,"invoiceAddress/wrongFieldKind"),"invoiceAddress/missingPart":s(({fieldKey:e,parts:n})=>`Field "${e}" is isInvoiceAddress but declares no property for the address part(s) ${n.join(", ")} (objectSchema.properties[].addressPart) \u2014 an invoice cannot print its address without them.`,"invoiceAddress/missingPart"),"invoiceAddress/multiple":s(({fieldKey:e})=>`Field "${e}" is one of several isInvoiceAddress fields \u2014 at most one per tenant.`,"invoiceAddress/multiple")};function O3(e){let n=I3[e.code];return n(e)}s(O3,"roleText");function _3(e){let n=[],t=e.tenant.nationalityFlag,r=typeof t=="object"&&t!==null?t:{},i=r.mode;if(fb.includes(i)||n.push(`[nationality/flagMode] tenant.nationalityFlag.mode must be one of ${fb.join(", ")} (got ${t===void 0?"no tenant.nationalityFlag":JSON.stringify(i??null)}).`),t!==void 0){let l=r.defaultCountryCode;(typeof l!="string"||!Em(l))&&n.push(`[nationality/defaultCountryCode] tenant.nationalityFlag.defaultCountryCode must be a lowercase ISO 3166-1 alpha-2 code (got ${JSON.stringify(l??null)}).`)}let o=new Map;for(let l of e.lists){let d=l.kind;if(!jF.includes(d)){n.push(`[list/kind] List "${l.key}" has kind ${JSON.stringify(d??null)} \u2014 one of ${jF.join(", ")}.`);continue}o.set(l.key,l.kind);for(let c of KF({key:l.key,kind:l.kind},l.elements))n.push(`[${c.code}] ${qF(R3,c,l.key)}`)}let a=MF(e.fields.map(l=>({key:l.key,kind:l.type,listKind:l.listKey===void 0?null:o.get(l.listKey)??null,isNationality:l.isNationality===!0,isAccountEmail:l.isAccountEmail===!0,isContactPhone:l.isContactPhone===!0,isInvoiceAddress:l.isInvoiceAddress===!0,addressParts:l.type==="object"?LF(l.objectSchema??{properties:[]}):null})));for(let l of a)n.push(`[${l.code}] ${O3(l)}`);return n}s(_3,"nationalityFindings");function VF(e){return Ri(e)?.message.de??(e instanceof Error?e.message:String(e))}s(VF,"errorText");function GF(e,n={}){let t=[...$3(e)],r=[];try{mF(e.fields.map(v=>v.key),[])}catch(v){t.push(VF(v))}e.tenant.terms!==void 0&&t.push(...lb(e.tenant.terms)),e.tenant.retentionDays!==void 0&&t.push(...DF(e.tenant.retentionDays)),$P(e.tenant.mailLevel)?e.tenant.mailLevel==="all"&&!yd(e.tenant.enabledModules,"notifications")&&t.push('[notification/levelWithoutModule] tenant.mailLevel is "all" but the notifications module is not enabled \u2014 only sign-in and security mail would go out. Enable the module or set "loginOnly".'):t.push(`[notification/mailLevel] tenant.mailLevel must be one of ${Lw.join(", ")} (got ${e.tenant.mailLevel===void 0?"nothing":JSON.stringify(e.tenant.mailLevel)}).`);let i=e.tenant.testMailRecipients;i!==void 0&&(!Array.isArray(i)||i.length===0||!i.every(v=>typeof v=="string"&&eb(v).includes("@"))?t.push("[notification/testRecipients] tenant.testMailRecipients must be a non-empty list of login addresses (leave it out for no test recipients)."):new Set(i.map(v=>eb(v))).size!==i.length&&t.push("[notification/testRecipients] tenant.testMailRecipients names an address twice."),(e.tenant.mailLevel!=="loginOnly"||!yd(e.tenant.enabledModules,"notifications"))&&t.push('[notification/testRecipientsWithoutEffect] tenant.testMailRecipients decides only at mailLevel "loginOnly" with the notifications module on \u2014 at "all" everybody gets mail, with the module off nobody. Remove the list or change the level.')),"enabledMailCategories"in e.tenant&&t.push('[notification/mailCategoriesRetired] tenant.enabledMailCategories was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),"mailEnabled"in e.tenant&&t.push('[notification/mailEnabledRetired] tenant.mailEnabled was replaced by tenant.mailLevel \u2014 "all" for every mail, "loginOnly" for sign-in mail only to families (staff mail follows personal settings).'),Tn(e.displayGroups.map(v=>v.key),"display group",t),Tn(e.lists.map(v=>v.key),"list",t),Tn(e.roles.map(v=>v.key),"role",t),Tn(e.fields.map(v=>v.key),"field",t),Tn(e.foundation.legalEntities.map(v=>v.key),"legal entity",t),Tn(e.foundation.units.map(v=>v.key),"unit",t),Tn(e.foundation.permissionGroups.map(v=>v.key),"permission group",t),"teams"in e.foundation&&t.push("foundation.teams is retired: a team is a permission group \u2014 move each team to foundation.permissionGroups (same key) and remove the block.");for(let v of e.foundation.users)"teamKeys"in v&&t.push(`User "${v.email}" carries teamKeys, retired: team membership is the user's permission-group membership.`);Tn(e.foundation.users.map(v=>v.key),"user",t),Tn((e.searchFilters??[]).map(v=>v.key),"search filter",t),Tn((e.searchTargets??[]).map(v=>v.objectPropertyKey===void 0?v.fieldKey:`${v.fieldKey}.${v.objectPropertyKey}`),"search target",t),Tn((e.partyResultIcons??[]).map(v=>v.key),"party result icon",t),Tn((e.templatePlaceholders??[]).map(v=>v.key),"template placeholder",t),Tn((e.notificationLetters??[]).map(zF),"notification letter",t),q3(e.notificationLetters??[],t),K3(e.tenant.notificationChrome,t),e.tenant.bankImportScope!==void 0&&!["sepa_only","full_statement"].includes(e.tenant.bankImportScope)&&t.push("tenant.bankImportScope must be sepa_only or full_statement."),e.tenant.hideMailLevelNotice!==void 0&&typeof e.tenant.hideMailLevelNotice!="boolean"&&t.push("tenant.hideMailLevelNotice must be true or false (the dashboard's mail-level notice)."),e.tenant.unassignedTaskNoticeDays!==void 0&&!RP(e.tenant.unassignedTaskNoticeDays)&&t.push("tenant.unassignedTaskNoticeDays must be a whole number from 1 to 30 (days before an unassigned team task is reported); leave it out for the platform default."),typeof e.tenant.magicLinkLogin!="boolean"&&t.push("tenant.magicLinkLogin must be true or false (the login page's sign-in link option)."),typeof e.tenant.adminSeesSignatureImages!="boolean"&&t.push("tenant.adminSeesSignatureImages must be true or false (whether a school administrator sees other accounts' signature images)."),typeof e.tenant.signatureStamp!="boolean"&&t.push("tenant.signatureStamp must be true or false (whether the school offers the signature stamp at the countersignature)."),uF(e.tenant.externalSignIn)?t.push(`[auth/externalSignInRetired] tenant.externalSignIn names the retired mode "${String(e.tenant.externalSignIn.mode)}" \u2014 every sign-in link now signs in once; state { mode: "oneTimeLink" }.`):cF(e.tenant.externalSignIn)||t.push('[auth/externalSignIn] tenant.externalSignIn must be { mode: "oneTimeLink" } (how families sign in).');let o=new Set(e.displayGroups.map(v=>v.key)),a=new Set(e.lists.map(v=>v.key)),l=new Set(e.roles.map(v=>v.key)),d=new Set(e.fields.map(v=>v.key)),c=new Map(e.fields.map(v=>[v.key,v])),u=new Set(e.foundation.legalEntities.map(v=>v.key)),p=new Set(e.foundation.units.map(v=>v.key)),h=new Set(e.foundation.permissionGroups.map(v=>v.key));yd(e.tenant.enabledModules,"bewerbungsmanagement")&&e.tenant.defaultApplicantGroupKey!==void 0&&(e.foundation.permissionGroups.find(P=>P.key===e.tenant.defaultApplicantGroupKey)?.permissions.includes("bewerbungsmanagement.applications.submitOwn")||t.push(`Default applicant group "${e.tenant.defaultApplicantGroupKey}" must grant submitOwn.`));let w=e.tenant.admissionFieldDisplayGroupKey;w!==void 0&&!o.has(w)&&t.push(`tenant.admissionFieldDisplayGroupKey "${w}" names no display group of this config.`),w===void 0&&(yd(e.tenant.enabledModules,"bewerbungsmanagement")||(e.admission?.fields.length??0)>0)&&t.push("tenant.admissionFieldDisplayGroupKey is required when admissions is enabled or admission.fields declares fields: it names the display group the fields an offer creates land in."),t.push(..._3(e)),Tn(e.fields.flatMap(v=>(v.relationshipKinds??[]).map(P=>P.key)),"relationship kind",t);for(let v of e.fields){o.has(v.displayGroupKey)||t.push(`Field "${v.key}" references missing display group "${v.displayGroupKey}".`),N3(v,t),v.formWritable===!0&&!ob[v.type].fieldMapTarget&&t.push(`Field "${v.key}" is formWritable, but a form cannot write a "${v.type}" field.`),v.type==="files"&&v.shareable===!0&&t.push(`[field/filesShareable] Field "${v.key}" is a files field and cannot be shareable.`),v.type==="auto-string"?C3(v,c,t):v.autoString!==void 0&&t.push(`Non-automatic field "${v.key}" must not define autoString.`),(!Number.isFinite(v.sortOrder)||v.sortOrder<0)&&t.push(`Field "${v.key}" has invalid sortOrder "${v.sortOrder}" (must be a non-negative number).`),(v.type==="0-1-select"||v.type==="0-n-select")&&!v.listKey&&t.push(`Select field "${v.key}" must define listKey.`),v.type!=="0-1-select"&&v.type!=="0-n-select"&&v.listKey!==void 0&&t.push(`Non-select field "${v.key}" must not define listKey.`),v.listKey&&!a.has(v.listKey)&&t.push(`Field "${v.key}" references missing list "${v.listKey}".`),(v.type==="object"||v.type==="relationship")&&!v.objectSchema&&t.push(`Field "${v.key}" must define objectSchema.`),v.type!=="object"&&v.type!=="relationship"&&v.objectSchema&&t.push(`Non-object field "${v.key}" must not define objectSchema.`);for(let P of v.objectSchema?.properties??[])(P.type==="0-1-select"||P.type==="0-n-select")&&!P.listKey&&t.push(`Object select property "${v.key}.${P.key}" must define listKey.`),P.listKey&&!a.has(P.listKey)&&t.push(`Object property "${v.key}.${P.key}" references missing list "${P.listKey}".`);P3(v,t)}let k=e.tenant.priceCriteriaFacts;if(k){let v=e.fields.find(P=>P.key===k.birthDateFieldKey);(!v||v.type!=="date")&&t.push("Price criteria require a configured date field for birth dates."),l.has(k.studentRoleKey)||t.push("Price criteria require a configured Student eligibility role."),k.siblingRankSource!==void 0&&k.siblingRankSource!=="derived"&&k.siblingRankSource!=="chosen"&&t.push('Price criteria siblingRankSource must be "derived" or "chosen".');for(let P of Object.keys(k))P!=="birthDateFieldKey"&&P!=="studentRoleKey"&&P!=="siblingRankSource"&&t.push(`Unknown price criteria fact setting "${P}".`)}let y=e.tenant.defaultEnrolleeRoleKey;y&&!l.has(y)&&t.push(`Default enrollment role "${y}" does not exist.`),y&&e.roles.some(v=>v.parentRoleKey===y)&&t.push(`Default enrollment role "${y}" must be a leaf role.`);for(let v of e.roles){(typeof v.icon!="string"||v.icon.trim().length===0)&&t.push(`Role "${v.key}" must define an icon.`),v.parentRoleKey&&!l.has(v.parentRoleKey)&&t.push(`Role "${v.key}" references missing parent role "${v.parentRoleKey}".`);for(let P of v.listDisplayFieldKeys??[])d.has(P)||t.push(`Role "${v.key}" list display references missing field "${P}".`)}let b=new Map(e.roles.map(v=>[v.key,v.parentRoleKey])),E=new Map;for(let v of e.roleFields){let P=E.get(v.roleKey)??[];P.push({roleId:v.roleKey,customFieldId:v.fieldKey}),E.set(v.roleKey,P)}for(let v of e.roles)try{fF(v.key,b,E)}catch(P){t.push(VF(P))}for(let v of e.roleFields){l.has(v.roleKey)||t.push(`Role field references missing role "${v.roleKey}" for field "${v.fieldKey}".`),d.has(v.fieldKey)||t.push(`Role field references missing field "${v.fieldKey}" for role "${v.roleKey}".`);for(let P of v.targetRequirementFieldKeys??[])d.has(P)||t.push(`Role field "${v.roleKey}.${v.fieldKey}" references missing target requirement field "${P}".`)}M3(e.contractRoleMappings??[],l,t);for(let v of e.templatePlaceholders??[])UD.test(v.key)||t.push(`Template placeholder "${v.key}" must use lower_snake_case segments, optionally separated by dots.`),v.source.kind==="customField"?Tm(v.source,c,t,`Template placeholder "${v.key}"`):v.source.kind==="relationshipTargetField"&&D3(v,c,t);for(let v of e.searchTargets??[])Tm(v,c,t,"Search target");for(let v of e.fields)kF(v.key)&&(v.defaultValue!==void 0||v.validations!==void 0)&&t.push(`System field "${v.key}" takes no defaultValue or validations.`);for(let v of e.lists)Tn(v.elements.map((P,A)=>String(P.sortOrder??(A+1)*10)),`sortOrder of an element of list "${v.key}"`,t);for(let v of e.searchFilters??[])Tn((v.options??[]).map((P,A)=>String(P.sortOrder??(A+1)*10)),`sortOrder of an option of search filter "${v.key}"`,t);for(let v of e.foundation.permissionGroups){v.grantAllCustomFields===!0&&v.customFieldPermissions!==void 0&&t.push(`Permission group "${v.key}" states both grantAllCustomFields and customFieldPermissions \u2014 one of them.`),Tn((v.customFieldPermissions??[]).map(P=>P.displayGroupKey),`display group of a field permission of group "${v.key}"`,t);for(let P of v.customFieldPermissions??[]){o.has(P.displayGroupKey)||t.push(`Permission group "${v.key}" grants field permissions on missing display group "${P.displayGroupKey}".`);for(let A of P.permissions)gF.includes(A)||t.push(`Permission group "${v.key}" grants unknown field permission "${A}".`)}}let T=e.tenant.partyRetention;T!==void 0&&(wF(T.days)||t.push(`tenant.partyRetention.days must be a whole number of days from 1 to ${36500} (got ${JSON.stringify(T.days)}).`),Number.isFinite(T.enabledAt)||t.push("tenant.partyRetention.enabledAt must be a timestamp (epoch ms)."),T.formerRoleKey!==void 0&&!l.has(T.formerRoleKey)&&t.push(`tenant.partyRetention references missing role "${T.formerRoleKey}".`));for(let v of e.searchFilters??[]){(v.kind==="chips"||v.kind==="select")&&(v.options?.length??0)===0&&t.push(`Search filter "${v.key}" must define options.`),(v.kind==="text"||v.kind==="numberRange")&&v.target===void 0&&t.push(`Search filter "${v.key}" must define a target field.`),v.options!==void 0&&Tn(v.options.map(P=>P.key),`search filter option for "${v.key}"`,t),Tm(v.target,c,t,`Search filter "${v.key}"`);for(let P of v.options??[]){P.predicates.length===0&&t.push(`Search filter option "${v.key}.${P.key}" must define at least one predicate.`);for(let A of P.predicates){if(A.kind==="role"){l.has(A.roleKey)||t.push(`Search filter option "${v.key}.${P.key}" references missing role "${A.roleKey}".`);continue}Tm(A,c,t,`Search filter option "${v.key}.${P.key}"`)}}}for(let v of e.partyResultIcons??[])F3(v,c,t);for(let v of e.foundation.legalEntities)if(v.terms!==void 0&&t.push(...lb(v.terms,`foundation.legalEntities.${v.key}.terms`)),BF(v.branding,t,`foundation.legalEntities.${v.key}.branding`),UF(v,t,`foundation.legalEntities.${v.key}`),v.signatoryUserKey!==void 0&&v.type==="school_group"&&t.push(`[config/signatoryOnGroup] Legal entity "${v.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) declares an Unterschriftsperson.`),v.parentLegalEntityKey&&!u.has(v.parentLegalEntityKey)&&t.push(`Legal entity "${v.key}" references missing parent "${v.parentLegalEntityKey}".`),v.address!==void 0){let P=v.address,A=["street","hausnr","plz","ort"];v.type==="school_group"?t.push(`Legal entity "${v.key}" is a school_group \u2014 only a Tr\xE4ger (school_operator, service_entity) has an address.`):(typeof P!="object"||P===null||Array.isArray(P)||Object.keys(P).some(M=>!A.includes(M))||A.some(M=>typeof P[M]!="string"||(P[M]??"").trim()===""))&&t.push(`Legal entity "${v.key}" has an invalid address \u2014 expected { street, hausnr, plz, ort }, each non-empty.`)}let R=new Map;for(let v of e.foundation.units){if(v.slug!==void 0){let P=typeof v.slug=="string"?xI(v.slug):"must be a string";P!==void 0&&t.push(`Unit "${v.key}" has invalid slug "${v.slug}" (${P}).`);let A=R.get(v.slug);A!==void 0&&t.push(`Units "${A}" and "${v.key}" both declare slug "${v.slug}" (unit slugs are unique per tenant).`),R.set(v.slug,v.key)}u.has(v.legalEntityKey)||t.push(`Unit "${v.key}" references missing legal entity "${v.legalEntityKey}".`),v.parentUnitKey&&!p.has(v.parentUnitKey)&&t.push(`Unit "${v.key}" references missing parent unit "${v.parentUnitKey}".`),v.sortOrder!==void 0&&(!Number.isFinite(v.sortOrder)||v.sortOrder<0)&&t.push(`Unit "${v.key}" has invalid sortOrder "${v.sortOrder}" (must be a non-negative number).`)}let D=/^[0-9a-f]{32}:[0-9a-f]{128}$/;for(let v of e.foundation.users){h.has(v.permissionGroupKey)||t.push(`User "${v.email}" references missing permission group "${v.permissionGroupKey}".`),v.unitKey&&!p.has(v.unitKey)&&t.push(`User "${v.email}" references missing unit "${v.unitKey}".`),v.status!==void 0&&v.status!=="deactivated"&&t.push(`User "${v.email}": status must be "deactivated" or absent, not "${String(v.status)}".`);let P=[v,...v.additionalMemberships??[]];for(let M of v.additionalMemberships??[])h.has(M.permissionGroupKey)||t.push(`User "${v.email}" references missing permission group "${M.permissionGroupKey}".`),M.unitKey&&!p.has(M.unitKey)&&t.push(`User "${v.email}" references missing unit "${M.unitKey}".`);Tn(P.map(M=>`${M.permissionGroupKey}/${M.unitKey??""}`),`membership (permission group/unit) of user "${v.email}"`,t);for(let M of P)M.validFrom!==void 0&&M.validTo!==void 0&&M.validTo<=M.validFrom&&t.push(`User "${v.email}": membership "${M.permissionGroupKey}" ends (validTo) before it starts (validFrom).`);let A=[v.firstName,v.lastName];A.some(M=>M!==void 0)&&A.some(M=>typeof M!="string"||M.trim()==="")&&t.push(`[config/userNameIncomplete] User "${v.email}" states only part of firstName/lastName (or an empty one) \u2014 set both or neither.`);for(let M of["staging","prod"]){let U=v.passwordHashes?.[M];U!==void 0&&!D.test(U)&&t.push(`User "${v.email}" passwordHashes.${M} is not in Better Auth scrypt format "<32hex>:<128hex>".`)}}BF(e.tenant.branding,t),UF(e.tenant,t);let L=WF(e.fields.flatMap(v=>v.sourceColumns));for(let v of L)r.push(`Source column "${v}" is mapped by more than one field.`);B3(e,t);let _=n.sourceColumns===void 0||e.source===void 0?void 0:j3(e,n.sourceColumns,t);return{ok:t.length===0,errors:t,warnings:r,coverage:_}}s(GF,"validateTenantConfig");function P3(e,n){let t=new Map;for(let r of e.objectSchema?.properties??[]){let i=r.addressPart;if(i===void 0)continue;let o=`Object property "${e.key}.${r.key}"`;if(!pw.includes(i)){n.push(`${o}: addressPart "${i}" is none of ${pw.join(", ")}.`);continue}e.type!=="object"&&n.push(`${o}: only an object field stores an address (addressPart).`),r.type!=="string"&&n.push(`${o}: addressPart "${i}" needs a string property, not "${r.type}".`);let a=t.get(i);a!==void 0&&n.push(`${o}: addressPart "${i}" is already declared by "${e.key}.${a}".`),t.set(i,r.key)}}s(P3,"validateAddressParts");function N3(e,n){let t=e.relationshipKinds;if(t===void 0)return;if(e.type!=="relationship"){n.push(`Field "${e.key}" declares relationshipKinds, but only a relationship field carries them.`);return}let r=new Map((e.objectSchema?.properties??[]).map(i=>[i.key,i]));for(let i of t){let o=`Field "${e.key}" relationship kind "${i.key}"`;if(typeof i.key!="string"||i.key.trim()===""){n.push(`Field "${e.key}": a relationship kind needs a key.`);continue}for(let l of["de","en"])(i.label?.[l]??"").trim()===""&&n.push(`${o}: label.${l} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);if(i.edge===null||typeof i.edge!="object"||Array.isArray(i.edge)){n.push(`${o}: edge must be an object.`);continue}i.sibling!==void 0&&i.sibling!==!0&&n.push(`${o}: sibling must be true or absent.`),i.sibling===!0&&i.mergeInto!==void 0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare mergeInto.`);let a=t.flatMap(l=>l.mergeInto!==void 0?[l.mergeInto]:[]);if(i.sibling===!0&&a.some(l=>l in i.edge)&&n.push(`${o}: a sibling kind's edge is its identity \u2014 it cannot declare a property another kind of the field merges into.`),i.sibling===!0&&Object.keys(i.edge).length===0&&n.push(`${o}: a sibling kind's edge is its identity \u2014 an empty edge would count every edge of the field.`),i.mergeInto!==void 0){let l=r.get(i.mergeInto);l===void 0||l.type!=="0-n-select"?n.push(`${o}: mergeInto "${i.mergeInto}" must name a 0-n-select property of the field's objectSchema.`):Array.isArray(i.edge[i.mergeInto])||n.push(`${o}: mergeInto "${i.mergeInto}" must be set to a list in the edge.`)}}}s(N3,"validateRelationshipKinds");function C3(e,n,t){if(e.autoString===void 0){t.push(`Automatic field "${e.key}" must define autoString.`);return}e.allowMultiple===!0&&t.push(`Automatic field "${e.key}" must not allow multiple values.`),e.shareable===!0&&t.push(`Automatic field "${e.key}" must not be shareable.`),e.autoString.segments.length===0&&t.push(`Automatic field "${e.key}" must define at least one segment.`),e.autoString.segments.filter(i=>i.kind==="sequence").length!==1&&t.push(`Automatic field "${e.key}" must define exactly one sequence segment.`);for(let i of e.autoString.segments)if(i.kind==="literal"&&i.value.length===0&&t.push(`Automatic field "${e.key}" has an empty literal segment.`),i.kind==="sequence"&&(i.startAt!==void 0&&(!Number.isInteger(i.startAt)||i.startAt<1)&&t.push(`Automatic field "${e.key}" sequence startAt must be an integer >= 1.`),i.minDigits!==void 0&&(!Number.isInteger(i.minDigits)||i.minDigits<0)&&t.push(`Automatic field "${e.key}" sequence minDigits must be an integer >= 0.`)),i.kind==="field"){let o=n.get(i.fieldKey);if(o===void 0){t.push(`Automatic field "${e.key}" references missing field "${i.fieldKey}".`);continue}i.objectPropertyKey!==void 0&&o.objectSchema?.properties.find(l=>l.key===i.objectPropertyKey)===void 0&&t.push(`Automatic field "${e.key}" references missing object property "${i.fieldKey}.${i.objectPropertyKey}".`)}}s(C3,"validateAutomaticStringField");function Tm(e,n,t,r){if(e===void 0)return;let i=n.get(e.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.fieldKey}".`);return}if(e.objectPropertyKey===void 0)return;(i.objectSchema?.properties.some(a=>a.key===e.objectPropertyKey)??!1)||t.push(`${r} references missing object property "${e.fieldKey}.${e.objectPropertyKey}".`)}s(Tm,"validateSearchTarget");function D3(e,n,t){if(e.source.kind!=="relationshipTargetField")return;let r=`Template placeholder "${e.key}"`,i=n.get(e.source.relationshipFieldKey);if(i===void 0)t.push(`${r} references missing relationship field "${e.source.relationshipFieldKey}".`);else if(i.type!=="relationship")t.push(`${r} relationship field "${e.source.relationshipFieldKey}" must be a relationship field.`);else{for(let a of e.source.edgeFilters??[])pb(i,a.propertyKey,t,`${r} edge filter`);e.source.selection?.sortPropertyKey!==void 0&&pb(i,e.source.selection.sortPropertyKey,t,`${r} selection sort`)}let o=n.get(e.source.targetFieldKey);if(o===void 0){t.push(`${r} references missing target field "${e.source.targetFieldKey}".`);return}o.type==="relationship"&&t.push(`${r} target field "${e.source.targetFieldKey}" must not be a relationship field.`),e.source.targetObjectPropertyKey!==void 0&&pb(o,e.source.targetObjectPropertyKey,t,`${r} target`)}s(D3,"validateRelationshipTemplatePlaceholder");function pb(e,n,t,r){(e.objectSchema?.properties.some(o=>o.key===n)??!1)||t.push(`${r} references missing object property "${e.key}.${n}".`)}s(pb,"validateObjectPropertyReference");function F3(e,n,t){let r=`Party result icon "${e.key}"`,i=n.get(e.when.fieldKey);if(i===void 0){t.push(`${r} references missing field "${e.when.fieldKey}".`);return}if(e.when.objectPropertyKey===void 0){i.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`);return}let o=i.objectSchema?.properties.find(a=>a.key===e.when.objectPropertyKey);if(o===void 0){t.push(`${r} references missing object property "${e.when.fieldKey}.${e.when.objectPropertyKey}".`);return}o.type!=="boolean"&&t.push(`${r} must target a Boolean field or object property.`)}s(F3,"validatePartyResultIconTarget");function zF(e){return`${e.templateId}:${e.locale}:${e.scopeKey}`}s(zF,"letterIdentity");function L3(e){return`${e.generatorKey??"*"}/${e.partyKind}/${e.roleKey}`}s(L3,"contractRoleMappingIdentity");function M3(e,n,t){let r=new Set;for(let i of e){let o=L3(i),a=`Contract role mapping "${o}"`;nb.includes(i.partyKind)||t.push(`${a}: partyKind must be one of ${nb.join(", ")}.`),i.partyKind==="beneficiary"&&t.push(`${a}: a beneficiary holds the enrollee role of the program it attends (programs.enrolleeRoleKey, else tenant.defaultEnrolleeRoleKey) \u2014 remove the mapping.`),n.has(i.roleKey)||t.push(`${a} references missing role "${i.roleKey}".`),i.generatorKey!==void 0&&i.generatorKey.trim()===""&&t.push(`${a}: generatorKey must not be blank \u2014 omit it for the tenant default.`),r.has(o)&&t.push(`${a} is declared twice.`),r.add(o)}}s(M3,"validateContractRoleMappings");function q3(e,n){for(let t of e){let r=`Notification letter "${zF(t)}"`;if(!bm(t.locale)){n.push(`${r} declares locale "${String(t.locale)}" \u2014 letters are written in ${Ye.map(i=>`"${i}"`).join(" and ")} only, so no mail would ever read this deviation.`);continue}if(t.scopeKey!==wm){n.push(`${r} declares scopeKey "${t.scopeKey}" \u2014 the only scope is "${wm}" (the whole school).`);continue}if(Object.keys(t.slots).length===0){n.push(`${r} overrides no block. A deviation that deviates in nothing is not an entry \u2014 remove it.`);continue}if(!Uw(t.templateId)){n.push(`${r} references no registered letter \u2014 "${t.templateId}" is not in the letter catalog.`);continue}for(let i of TF(Bw(t.templateId),t.slots,t.locale))n.push(`${r}, block "${i.slotKey}" [${i.code}]: ${i.message.de}`)}}s(q3,"validateNotificationLetters");function K3(e,n){if(e!==void 0)for(let t of $F(e))n.push(`Notification chrome: ${t.de}`)}s(K3,"validateNotificationChrome");function BF(e,n,t){if(e===void 0)return;let r=t===void 0?n:{push:s((...p)=>n.push(...p.map(h=>`${t}: ${h}`)),"push")},i=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,o=/^(?:rgb|rgba|hsl|hsla)\(.+\)$/i,a=s(p=>i.test(p.trim())||o.test(p.trim()),"isColor");for(let[p,h]of Object.entries(e.colors??{}))h!==void 0&&(a(h)||r.push(`Branding color "colors.${p}" has invalid value "${h}" (expected hex "#rgb"/"#rrggbb"/"#rrggbbaa" or rgb()/rgba()/hsl()/hsla()).`));let l=["sharp","rounded","soft"];e.radius!==void 0&&!l.includes(e.radius)&&r.push(`Branding radius "${e.radius}" is invalid (expected "sharp", "rounded", or "soft").`);let d=["sm","md","lg","max"];e.logoSize!==void 0&&!d.includes(e.logoSize)&&r.push(`Branding logoSize "${e.logoSize}" is invalid (expected "sm", "md", "lg", or "max").`);let c=["compact","normal","spacious"];e.bannerDensity!==void 0&&!c.includes(e.bannerDensity)&&r.push(`Branding bannerDensity "${e.bannerDensity}" is invalid (expected "compact", "normal", or "spacious").`);let u=["light","dark"];e.logoGround!==void 0&&!u.includes(e.logoGround)&&r.push(`Branding logoGround "${e.logoGround}" is invalid (expected "light" or "dark").`),e.websiteUrl!==void 0&&!e.websiteUrl.startsWith("https://")&&r.push(`Branding websiteUrl must be an https:// URL (got "${e.websiteUrl}").`);for(let p of["heading","body"]){let h=e.fonts?.[p];h!==void 0&&((typeof h.family!="string"||h.family.trim().length===0)&&r.push(`Branding font "fonts.${p}" must define a non-empty family.`),Object.hasOwn(h,"url")&&r.push(`Branding font "fonts.${p}.url" is no longer supported \u2014 the font file is uploaded (plexus-cli branding set-font --slot ${p} --file <woff2>) and config carries the family only.`))}}s(BF,"validateBranding");function UF(e,n,t="tenant"){let r=e.brandingAssets;if(r!==void 0){if(typeof r!="object"||r===null||Array.isArray(r)){n.push(`${t}.brandingAssets must be an object keyed by slot (${Sm.join(", ")}).`);return}for(let[i,o]of Object.entries(r)){let a=`${t}.brandingAssets.${i}`;if(!Sm.includes(i)){n.push(`${a}: unknown slot (expected ${Sm.join(", ")}).`);continue}if(typeof o!="object"||o===null){n.push(`${a}: must be { sha256, sizeBytes, mimeType }.`);continue}if("size"in o){n.push(`[config/fileRefRenamed] ${a} still names size \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}YF.test(o.sha256??"")||n.push(`${a}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(o.sizeBytes)||o.sizeBytes<=0)&&n.push(`${a}: sizeBytes must be a positive integer.`);let l=OF[i];if(l===null){let d=_F({contentType:o.mimeType,size:o.sizeBytes});d!==null&&n.push(`${a}: ${d.de}`)}else{o.mimeType!==ub&&n.push(`${a}: mimeType must be "${ub}" (got "${o.mimeType}").`);let d=PF(e.branding?.fonts?.[l]?.family);d!==null&&n.push(`${a}: [branding/fontFamilyMissing] ${t}.branding.fonts.${l}: ${d.de}`)}"path"in o&&n.push(`${a}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}}s(UF,"validateBrandingAssets");function j3(e,n,t){let{source:r}=e;r===void 0&&F("validateSourceCoverage: called without a `source` block.");let i=new Set(n),o=new Set(e.fields.flatMap(k=>k.sourceColumns)),a=new Set(e.deferredColumns.map(k=>k.column)),l=new Set(e.ignoredColumns.map(k=>k.column)),d=new Set([...o,...a,...l]),c=r.requiredColumns.filter(k=>!i.has(k)),u=n.filter(k=>!d.has(k)),p=[...o].filter(k=>!i.has(k)),h=[...a].filter(k=>!i.has(k)),w=[...l].filter(k=>!i.has(k));for(let k of c)t.push(`Required source column "${k}" is missing from ${r.primaryTable}.`);for(let k of u)t.push(`Source column "${k}" is neither mapped nor explicitly deferred/ignored.`);for(let k of p)t.push(`Mapped source column "${k}" does not exist in the source schema.`);for(let k of h)t.push(`Deferred source column "${k}" does not exist in the source schema.`);for(let k of w)t.push(`Ignored source column "${k}" does not exist in the source schema.`);return{table:r.primaryTable,availableColumns:n.length,mappedColumns:[...o].filter(k=>i.has(k)).length,deferredColumns:[...a].filter(k=>i.has(k)).length,ignoredColumns:[...l].filter(k=>i.has(k)).length,missingRequiredColumns:c,unmappedColumns:u,unknownMappedColumns:p,unknownDeferredColumns:h,unknownIgnoredColumns:w}}s(j3,"validateSourceCoverage");function Tn(e,n,t){for(let r of WF(e))t.push(`Duplicate ${n} key "${r}".`)}s(Tn,"requireUnique");function WF(e){let n=new Set,t=new Set;for(let r of e)n.has(r)&&t.add(r),n.add(r);return[...t]}s(WF,"duplicates");var YF=/^[0-9a-f]{64}$/,V3=["fileName","size"];function B3(e,n){if(!Array.isArray(e.files)){n.push('"files" is missing \u2014 declare the file library (an empty list is fine).');return}Tn(e.files.map(t=>t.key),"file",n);for(let t of e.files){let r=`files["${t.key}"]`;Ea(t.key)||n.push(`${r}: key must match ${Ok}.`);for(let o of["de","en"])(t.label?.[o]??"").trim()===""&&n.push(`${r}: label.${o} is required \u2014 [i18n/missingTranslation] every shown text needs German and English.`);let i=V3.filter(o=>o in t);if(i.length>0){n.push(`[config/fileRefRenamed] ${r} still names ${i.join(", ")} \u2014 this bundle was exported before the file-field rename, or by a plexus-cli older than this release (now filename / sizeBytes). Update plexus-cli, export it again (plexus-cli --env <env> config export) and re-apply.`);continue}if(typeof t.filename!="string")n.push(`${r}: filename is missing.`);else{let o=Wo(t.filename);o!==null&&n.push(`${r}: filename ${o}.`)}km.includes(t.mimeType)||n.push(`${r}: mimeType "${t.mimeType}" is not allowed (${km.join(", ")}).`),YF.test(t.sha256??"")||n.push(`${r}: sha256 must be 64 lowercase hex chars.`),(!Number.isInteger(t.sizeBytes)||t.sizeBytes<=0)&&n.push(`${r}: sizeBytes must be a positive integer.`),"path"in t&&n.push(`${r}: "path" is a CLI snapshot field \u2014 resolve it with plexus-cli config apply.`)}}s(B3,"validateFiles");var U3=new WeakMap,G3=new WeakSet;function mb(e,n){n(e);let r=e.asOptional.bind(e);return Object.defineProperty(e,"asOptional",{value:s(()=>mb(r(),n),"value"),enumerable:!1}),e}s(mb,"carry");function Pa(e,n){return mb(e,t=>U3.set(t,n))}s(Pa,"tagged");var z3="tenant teardown drains every table explicitly (config/wipe.ts)",Ve={belongsTo:s(e=>Pa(e,{kind:"belongsTo"}),"belongsTo"),owns:s(e=>Pa(e,{kind:"owns"}),"owns"),holds:s(e=>Pa(e,{kind:"holds"}),"holds"),restrict:s((e,n)=>Pa(e,n?{kind:"restrict",unindexed:n.unindexed}:{kind:"restrict"}),"restrict"),history:s(e=>Pa(e,{kind:"history"}),"history"),tenant:s(e=>Pa(e,{kind:"restrict",unindexed:z3}),"tenant"),historyOf:s(e=>mb(e,n=>G3.add(n)),"historyOf")};var W3=m.object({street:m.string(),hausnr:m.string(),plz:m.string(),ort:m.string()}),HF=m.union(m.literal("school_operator"),m.literal("school_group"),m.literal("service_entity")),Jr=HF.members.map(e=>e.value),Y3={tenantId:Ve.tenant(m.id("tenants")),name:m.optional(m.string()),type:HF,parentLegalEntityId:m.optional(Ve.restrict(m.id("legal_entities"))),configKey:m.optional(m.string()),partyId:m.optional(Ve.restrict(m.id("parties"))),address:m.optional(W3),signatoryUserId:m.optional(Ve.restrict(m.id("users"))),terms:m.optional(AF)},KTe=Ct(Y3).index("by_tenantId",["tenantId"]).index("by_parentLegalEntityId",["parentLegalEntityId"]).index("by_tenantId_and_configKey",["tenantId","configKey"]).index("by_partyId",["partyId"]).index("by_signatoryUserId",["signatoryUserId"]);var H3=m.union(m.literal("school"),m.literal("kindergarten"),m.literal("after_school_care"),m.literal("department"),m.literal("site"),m.literal("other")),Kt=H3.members.map(e=>e.value),BTe=m.union(m.literal("school"),m.literal("vocational"),m.literal("care"),m.literal("seminar"),m.literal("other")),UTe=m.union(m.literal("none"),m.literal("manual"),m.literal("annual_rollover")),GTe=m.union(m.literal("grade_level"),m.literal("module"),m.literal("phase"),m.literal("other")),zTe=m.union(m.literal("school_year"),m.literal("cohort"),m.literal("seminar"),m.literal("care_period"),m.literal("other")),WTe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("archived")),YTe=m.union(m.literal("class"),m.literal("course"),m.literal("care_group"),m.literal("seminar_group"),m.literal("mixed_age_group"),m.literal("other")),HTe=m.union(m.literal("planned"),m.literal("active"),m.literal("completed"),m.literal("cancelled")),JTe=m.union(m.literal("class_teacher"),m.literal("teacher"),m.literal("mentor"),m.literal("instructor"),m.literal("assistant"),m.literal("other")),QTe=m.union(m.literal("units"),m.literal("unit_profiles"),m.literal("programs"),m.literal("program_stages"),m.literal("program_runs"),m.literal("learning_groups"),m.literal("enrollments"),m.literal("learning_group_staff_assignments")),ZTe=m.union(m.literal("open"),m.literal("mapped"),m.literal("ignored"));function QF(e){let n=["street","hausnr","plz","ort"].filter(t=>e[t]!==void 0);if(n.length!==0){if(n.length!==4)throw new Error(`config legal-entity add: an address needs all of --street, --hausnr, --plz and --ort (got ${n.map(t=>`--${t}`).join(", ")})`);return{street:e.street,hausnr:e.hausnr,plz:e.plz,ort:e.ort}}}s(QF,"addressFrom");function ZF(e){if(!Jr.includes(e))throw new Error(`config legal-entity add: --type "${e}" is none of ${Jr.join(", ")}`);return e}s(ZF,"legalEntityType");function XF(e){if(!Kt.includes(e))throw new Error(`config unit add: --kind "${e}" is none of ${Kt.join(", ")}`);return e}s(XF,"unitKind");function eL(e,n,t){let r=e.find(i=>i.key===n.key);if(r===void 0)return e.push(n),"create";if(Pe(r)===Pe(n))return"same";throw new Error(`${t} "${n.key}" already exists with other values \u2014 decide by hand, nothing written.
11305
11305
  in the file: ${JSON.stringify(r)}
11306
11306
  requested: ${JSON.stringify(n)}`)}s(eL,"addRow");function JF(e){return new Set(GF(e).errors)}s(JF,"findings");function nL(e,n){let t=s(()=>JSON.parse(he(e,"utf8")),"read"),r=t();if(typeof r!="object"||r===null||typeof r.foundation!="object")throw new Error(`config: ${e} is no exported tenant config (no "foundation" block) \u2014 export one with \`config export --out <file>\``);let i=JF(r),o=t(),a=n(o),l=[...JF(o)].filter(d=>!i.has(d));if(l.length>0)throw new Error(`config: the edit is refused by the config validator, nothing written:
11307
11307
  ${l.join(`
@@ -11358,7 +11358,7 @@ ${i.map(d=>` ${zd(d)}
11358
11358
  `),0}},zL=[fv,pv,mv];var hv=class extends C{static{s(this,"LeadsListCommand")}static paths=[["leads","list"],["interessenten","list"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.leads.listForManagement,{client:t});return this.print(r,i=>i.map(o=>({name:o.personDisplayName??"\u2014",angebot:o.programName===null?"\u2014":Ce(o.programName),stufe:o.stageName===null?"\u2014":Ce(o.stageName),lauf:o.runName===null?"\u2014":Ce(o.runName)})),["name","angebot","stufe","lauf"]),0}},WL=[hv];function Av(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(Av,"ts");function HL(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s(HL,"ago");var YL=["queued","running","succeeded","failed","canceled"];function L5(e){let n=YL.find(t=>t===e);if(n===void 0)throw new Error(`jobs list: --status must be one of ${YL.join(" | ")}, got "${e}".`);return n}s(L5,"jobStatus");var gv=class extends C{static{s(this,"JobsListCommand")}static paths=[["jobs","list"]];static usage=$.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 n=await this.caller(),t=this.all?void 0:mf(this.limit,100),r=await this.paginate(n,x.jobs.listPage,this.status?{status:L5(this.status)}:{},{max:t,pageSize:Math.min(t??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:HL(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},yv=class extends C{static{s(this,"JobsShowCommand")}static paths=[["jobs","show"]];static usage=$.Usage({category:"Jobs",description:"Show one job's full detail + per-attempt run timeline."});jobId=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.jobs.getDetail,{jobId:this.jobId});if(t===null)throw new Error(`Job ${this.jobId} not found.`);return this.print(t),0}},wv=class extends C{static{s(this,"JobsLogsCommand")}static paths=[["jobs","logs"]];static usage=$.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 t=await(await this.caller()).query(x.jobs.tailLog,{jobId:this.jobId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(t,r=>r.map(i=>({at:Av(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},kv=class extends C{static{s(this,"JobsCancelCommand")}static paths=[["jobs","cancel"]];static usage=$.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 n=await this.caller();if(!this.confirm){let t=await n.query(x.jobs.getDetail,{jobId:this.jobId});if(t===null)throw new Error(`Job ${this.jobId} not found.`);return this.print({jobId:this.jobId,kind:t.kind,status:t.status,canceled:!1},r=>[{key:"would cancel",value:`${r.jobId} (${r.kind}, ${r.status})`},{key:"next",value:"re-run with --confirm"}]),0}return await n.mutation(x.jobs.cancel,{jobId:this.jobId}),this.print({canceled:this.jobId}),0}},bv=class extends C{static{s(this,"WorkersLogsCommand")}static paths=[["platform","workers","logs"],["workers","logs"]];static usage=$.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 t=await(await this.caller()).query(x.workers.tailLog,{workerId:this.workerId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(t,r=>r.map(i=>({at:Av(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},vv=class extends C{static{s(this,"WorkersReaperStatusCommand")}static paths=[["platform","workers","reaper-status"],["workers","reaper-status"]];static usage=$.Usage({category:"Platform",description:"Show the last worker-reaper tick (confirm the cron is firing)."});async execute(){let t=await(await this.caller()).query(x.workers.reaperStatus,{});return t===null?(this.print({reaper:"no tick recorded yet"}),0):(this.print({...t,ranAt:Av(t.ranAt)}),0)}},xv=class extends C{static{s(this,"WorkersReapCommand")}static paths=[["platform","workers","reap"],["workers","reap"]];static usage=$.Usage({category:"Platform",description:"Force a reaper pass NOW (free dead leases / fail stalled jobs)."});async execute(){let t=await(await this.caller()).mutation(x.workers.reap,{});return this.print(t),0}},Sv=class extends C{static{s(this,"ImportsCleanupOrphansCommand")}static paths=[["platform","imports","cleanup-orphaned"],["imports","cleanup-orphaned"]];static usage=$.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 n=await this.caller(),t=this.allTenants?void 0:this.requireTenant(n),r=await n.mutation(x.imports.failOrphanedRuns,{...t?{tenantSlug:t}:{},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:HL(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},JL=[gv,yv,wv,kv,bv,vv,xv,Sv];var M5=/^(\d+)([mhd])$/,q5={m:6e4,h:36e5,d:864e5};function Km(e,n=Date.now()){let t=e.trim(),r=M5.exec(t);if(r!==null)return n-Number(r[1])*q5[r[2]];let i=/^\d{4}-\d{2}-\d{2}/.test(t)?Date.parse(t):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(Km,"parseSince");function jm(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(jm,"ts");function Fv(e,n){if(e===void 0)throw new Error(`notifications ${n}: --locale is required (${Ye.join("|")}) \u2014 every letter exists in each language, and each is worded on its own`);if(!bm(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${Ye.join("|")})`);return e}s(Fv,"parseLocale");function K5(e,n){let t={},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 t)throw new Error(`notifications letters: block "${d}" given twice \u2014 one value per block.`);t[d]=a(o.slice(l+1))},"put");for(let i of e??[])r("--slot",i,o=>o);for(let i of n??[])r("--slot-file",i,o=>he(o.trim(),"utf8"));return t}s(K5,"parseSlots");var Ev=class extends C{static{s(this,"NotificationsListCommand")}static paths=[["platform","notifications","list"],["notifications","list"]];static usage=$.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 n=await this.caller(),t=this.all?void 0:mf(this.limit,100),r=await this.paginate(n,x.notifications.listPage,{...this.status?{status:this.status}:{},...this.template?{templateId:this.template}:{},...this.to?{recipientEmail:this.to}:{},...this.since?{since:Km(this.since)}:{}},{max:t,pageSize:Math.min(t??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:jm(o.createdAt),settled:jm(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function j5(e){if(e.letter===null)return{...e,attachments:[]};let{attachments:n,...t}=e.letter;return{...e,attachments:n.map(({filename:r,contentType:i,size:o})=>({filename:r,contentType:i,size:o})),letter:t}}s(j5,"showView");var Tv=class extends C{static{s(this,"NotificationsShowCommand")}static paths=[["platform","notifications","show"],["notifications","show"]];static usage=$.Usage({category:"Notifications",description:"Show one delivery in full: SMTP evidence, lease, sweeper bookkeeping, template summary."});deliveryId=f.String({required:!0});async execute(){let t=await(await this.caller()).query(x.notifications.getDetail,{deliveryId:this.deliveryId});if(t===null)throw new Error(`Delivery ${this.deliveryId} not found.`);return this.print(j5(t)),0}},$v=class extends C{static{s(this,"NotificationsRetryCommand")}static paths=[["platform","notifications","retry"],["notifications","retry"]];static usage=$.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}},Rv=class extends C{static{s(this,"NotificationsSweeperStatusCommand")}static paths=[["platform","notifications","sweeper-status"],["notifications","sweeper-status"]];static usage=$.Usage({category:"Notifications",description:"Last tick of the notification sweeper cron (deadLastHour is the number to watch)."});async execute(){let t=await(await this.caller()).query(x.notifications.sweeperStatus,{});return t===null?(this.print({ranAt:null,note:"sweeper has not run since deploy"}),0):(this.print({...t,ranAt:jm(t.ranAt),lastDeadAt:jm(t.lastDeadAt)}),0)}},Iv=class extends C{static{s(this,"NotificationsSelfTestCommand")}static paths=[["platform","notifications","self-test"],["notifications","self-test"]];static usage=$.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 t=await(await this.caller()).action(x.notificationActions.selfTest,{recipient:this.to});return this.print(t),t.ok?0:1}},Ov=class extends C{static{s(this,"NotificationsLettersListCommand")}static paths=[["notifications","letters","list"]];static usage=$.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 n=await this.caller(),t=await n.query(x.notifications.letterWorkspace,{tenantSlug:this.requireTenant(n),locale:"de"});return this.print(t.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}},_v=class extends C{static{s(this,"NotificationsLettersShowCommand")}static paths=[["notifications","letters","show"]];static usage=$.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 (${Ye.join("|")}) \u2014 required; each language is worded on its own`});async execute(){let n=await this.caller(),t=await n.query(x.notifications.letterWorkspace,{tenantSlug:this.requireTenant(n),locale:Fv(this.locale,"letters show")}),r=t.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: ${t.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}
11359
11359
  Platzhalter: ${i||"\u2014"}
11360
11360
 
11361
- `)}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}},Pv=class extends C{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=$.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 (${Ye.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 n=K5(this.slot,this.slotFile);if(Object.keys(n).length===0)throw new Error("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let t=await this.caller(),r=await t.mutation(x.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(t),templateId:this.templateId,locale:Fv(this.locale,"letters set"),slots:n});return this.print({templateId:this.templateId,submitted:Object.keys(n),...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}},Nv=class extends C{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=$.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 (${Ye.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 n=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&n.length>0)throw new Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&n.length===0)throw new Error("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let t=await this.caller(),r=await t.mutation(x.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(t),templateId:this.templateId,locale:Fv(this.locale,"letters reset"),...this.all?{}:{slotKeys:n}});return this.print({templateId:this.templateId,reset:this.all?"all":n.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Hd=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Vm(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":Hd(n[r],""),...t===null?{}:{platform:Hd(t[r],"")}}))}s(Vm,"chromeTextRows");var Cv=class extends C{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=$.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 n=await this.caller(),t=await n.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(n)});return this.print(t,r=>[...Vm("greeting",r.greeting,r.defaults.greeting),...Vm("closing",r.closing,r.defaults.closing),{field:"senderName",school:Hd(r.senderName,"\u2014 (platform)"),platform:Hd(r.defaults.senderName,"")}],["field","school","platform"]),0}},Dv=class extends C{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=$.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 n=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"),t=n("greeting",this.greetingDe,this.greetingEn),r=n("closing",this.closingDe,this.closingEn);if(t===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,...t!==void 0?{greeting:t}:{},...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=>[...Vm("greeting",l.greeting,null),...Vm("closing",l.closing,null),{field:"senderName",school:Hd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},QL=[Ev,Tv,$v,Rv,Iv,Ov,_v,Pv,Nv,Cv,Dv];var V5={capacity:null,isOpen:!1},B5={capacity:null,isOpen:!0};function U5(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(U5,"isCapacity");function Bm(e,n){let t=[],r=n===void 0?void 0:new Set(n);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&t.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)){t.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)&&t.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"){t.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&t.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!U5(u.capacity))&&t.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),t}s(Bm,"capacitySpecIssues");function XL(e,n,t={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(t.stageKeys),a=new Set(t.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of n){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===Qt(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,b=y!==void 0?{capacity:y.capacity,isOpen:y.isOpen}:u===void 0?V5:B5;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:b,to:k})}}return d}s(XL,"planRunCapacities");function ZL(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(ZL,"describeCell");function Um(e){return`~cap ${e.run}\xD7${e.stageKey} ${ZL(e.from)} \u2192 ${ZL(e.to)}`}s(Um,"describeCapacityStep");function e0(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(e0,"assertBackendHasStageKeys");async function Lv(e,n,t,r){let i=await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,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}));e0(i);let a=Af(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:n,offerKey:t,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(Lv,"planStages");async function Gm(e,n,t,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=t===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t});e0(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 XL(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===Qt(d,c)))})}s(Gm,"planCapacities");async function G5(e,n,t,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===Qt(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(G5,"assertNoArchivedRunKey");var Mv={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...Sf(o??[]),...xf(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(y=>y.message.de).join("; ")}`);let l=Bm(t.program?.runs??[],o?.map(y=>y.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await G5(e,i,n,t);let d=await Gm(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=z5(t);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:n,unitId:p.unitId,...t.program?.key!==void 0?{programKey:t.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let y=await Lv(e,i,n,o);h.push(...y.map(Ef))}else{let y=await e.mutation(x.programAdmin.reconcileProgramStages,{client:i,offerKey:n,stages:o.map(b=>({key:b.key,name:b.name,...b.gradeLevel!==void 0?{gradeLevel:b.gradeLevel}:{}}))});h.push(...y.steps,...y.warnings.map(b=>`warning ${b}`))}let w=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let y of t.program?.runs??[]){let b=w.programKey===null?void 0:w.runs.find(E=>E.key===Qt(w.programKey,y.key));if(b!==void 0){Is(b.name,y.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:y.name}),h.push(`~run ${y.key} ("${Ce(b.name)}" \u2192 "${Ce(y.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,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} (${Ce(y.name)})`)}let k=r.dryRun?d:await Gm(e,i,n,t);if(!r.dryRun&&k.length>0){let y=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=y.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let E of k){let T=y.runs.find(D=>D.key===Qt(b,E.run))?.runId,R=y.stages.find(D=>Kr(b,D.key)===E.stageKey)?.stageId;if(T===void 0||R===void 0)throw new Error(`offer[admission]: cell ${E.run}\xD7${E.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:n,runId:T,stageId:R,capacity:E.to.capacity,isOpen:E.to.isOpen})}}return h.push(...k.map(Um)),h.join(", ")}};function z5(e){let n=e.program?.unitKey,t=e.links?.unitKey;if(n!==void 0&&t!==void 0&&n!==t)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${n}" and links.unitKey "${t}"; keep one`);return n??t}s(z5,"bundleUnitKey");var n0={role:"control",effect:"pure",cardinality:"N-to-1"};var zm=["add","remove","replace"];function t0(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(t0,"roleAssignLiteral");var r0={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,n,t)=>{let r=[],i=t0(e,"roleKey")?.trim()??"",o=t0(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"}):t?.roleKeys!==void 0&&!t.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: ${[...t.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: ${[...t.roleKeys].sort().join(", ")}.`},severity:"error"}):t?.assignableRoleKeys!==void 0&&!t.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: ${[...t.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: ${[...t.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),zm.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 ${zm.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${zm.join(" | ")}.`},severity:"error"}),r},"validate")};var W5=["event","effect","outcomes"],qv=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),i0={outcomes:[{id:vr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of W5)i in r&&t.push(qv(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${vr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${vr}" itself.`));return nr(n.nodes).some(i=>i.target===e.id)&&t.push(qv(`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?.[vr]===void 0&&t.push(qv(`nodes.${e.id}.next.${vr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${vr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${vr}" nowhere.`)),t},"validate")};var Y5="submit",o0=[{id:Y5,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function s0(e){return e==="draft"}s(s0,"isWritableSmartFormState");var Kv=["draft","committed"],__e=Kv.filter(e=>s0(e));async function a0(e,n,t){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",n).eq("formNodeId",t)).take(2);return r.length>1&&F(`application ${n}: two form instances for node "${t}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(a0,"getSmartFormInstance");var l0="form:fill",jv="request:collectPayment",Vv="request:collectPaymentSeparate",ki="confirmPayment";var H5={key:l0,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},d0={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},c0={[PI]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:d0,external:en(te("Entwurf","Draft"),"neutral",te("Bewerbung fortsetzen","Continue application"),te("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."),te("Bewerbung fortsetzen","Continue application"),"continue-form")},[Rf]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:d0,external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung ist eingereicht","Your application has been submitted"),te("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."))}},u0={role:"user-action",effect:"side-effect",progressDefaults:c0,progressEvents:qn(c0),actions:s(()=>o0,"actions"),workItemTemplates:s(()=>[H5],"workItemTemplates"),states:Kv,currentState:s(async(e,n)=>{let t=await a0(e,n.applicationId,n.node.id);return t===null?"draft":t.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=>At(e)?[]:[{id:If,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[],t=e.inputs?.smartForm,r=t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0,i=e.adoptForm!==void 0;return r&&i?n.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&&n.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"}),n},"validate")};var f0={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Pn.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Pn.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Pn.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:ZO(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[Pn.flagKey]?.kind==="literal"&&Jf(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Pn.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?.[Pn.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Pn.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"}),n},"validate")};var J5="true",Q5="false",Bv=[{id:J5,label:{de:"Ja",en:"Yes"}},{id:Q5,label:{de:"Nein",en:"No"}}];var p0={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Bv,validate:s((e,n,t)=>Z5(e,n,t),"validate")};function Z5(e,n,t){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=Bv.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,...Fp(e.condition,WI(n),t).map(r)]}s(Z5,"ifNodeIssues");var Da="decision",X5=new Set(["decision","review"]),nPe=new Set([...X5,"governedDocument"]);var h0=[{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"}],m0={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:en(te("Freigegeben","Released"),"green",te("Ihre Bewerbung wurde freigegeben","Your application has been released"),te("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."))}},ts={role:"user-action",effect:"side-effect",outcomes:h0,progressDefaults:m0,progressEvents:qn(m0),notificationEvents:s(e=>(e.outcomes??[]).map(n=>({id:n.id,label:n.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(n=>({id:n.id,kind:"advance",outcome:n.id,label:n.label,...Li(n.semantic)?{semantic:n.semantic}:{}})),...GN(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:Da,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,n)=>n===Da&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),taskView:s((e,n)=>n===Da?e.view:void 0,"taskView"),validate:Uv};function Uv(e,n,t){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 ${St.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${St.join(", ")}.`},severity:"error"}):Li(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: ${St.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${St.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(Uv,"validateDecisionNode");var Gv=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],g0=[{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 zv="promoted";var y0="promote",w0="Nachr\xFCcken",Fa="promoteLabel";var eQ={de:w0,en:"Promote from waitlist"};function nQ(e){let n=e.inputs?.[Fa];if(n===void 0||n.kind==="unset")return eQ;let t=n.kind==="literal"?n.value:void 0;return Oo(t)!==null&&F(`waitlist node ${e.id}: inputs.${Fa} ${JSON.stringify(n)} is not a { de, en } literal`),t}s(nQ,"promoteLabelOf");var Wv={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},k0={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:Wv,external:en(te("Warteliste","Waiting list"),"amber",te("Sie stehen auf der Warteliste","You are on the waiting list"),te("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:te("Nachger\xFCckt","Promoted"),tone:"green",phase:Wv,external:en(te("Nachger\xFCckt","Moved up"),"green",te("Sie sind nachger\xFCckt","You have moved up"),te("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:te("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:Wv,external:en(te("Warteliste geschlossen","Waiting list closed"),"red",te("Die Warteliste wurde geschlossen","The waiting list has been closed"),te("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},b0={outcomes:Gv,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Xt.map(e=>({value:e,label:oO[e]}))},{id:Fa,label:{de:"Beschriftung \u201ENachr\xFCcken\u201C",en:"Label of \u201CPromote\u201D"},type:"localizedText",required:!1,inspector:"literal-only"}],"inputs"),validate:s((e,n)=>{let t=e.inputs?.[Fa];if(t?.kind==="literal"){let a=Oo(t.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Fa}`,reason:{de:`[waitlist/promoteLabelText] Die Beschriftung \u201ENachr\xFCcken\u201C von "${e.id}" braucht einen Text auf Deutsch und auf Englisch (${a}).`,en:`[waitlist/promoteLabelText] The "Promote" label of "${e.id}" needs a text in German and in English (${a}).`},severity:"error"}]}let r=jy(e);if(r===null)return[];let i=n.nodes.filter(a=>a.type==="waitlist"&&a.id!==e.id),o=n.nodes.indexOf(e);for(let a of i){if(n.nodes.indexOf(a)>o)continue;let l=jy(a);if(l!==null&&l.waitlistOrder!==r.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${a.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 alle Wartelisten eines Prozesses ordnen gleich.`,en:`[waitlist/policyConflict] Waiting lists "${a.id}" and "${e.id}" state different orders \u2014 all waiting lists of a process order alike.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:k0,progressEvents:qn(k0),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:Gv).some(t=>t.id===zv)?[{id:y0,kind:"advance",outcome:zv,semantic:"other",label:nQ(e),surface:tr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var Yv="complete",Jd="acceptedIncomplete",Wm="rejected",tQ="absage",v0="closeWithoutDocuments",x0="rejectAtCompleteness",S0="Ohne Nachreichung abschlie\xDFen",A0="Ablehnen",E0="awaitingDocuments",Hv="documentsComplete",Jv="closedWithoutDocuments",Qv="rejected",Zv="withdrawn",T0="requested",APe={[Yv]:{event:Hv,status:"complete",endsRole:!0},[Jd]:{event:Jv,status:"acceptedIncomplete",endsRole:!1},[Wm]:{event:Qv,status:"rejected",endsRole:!0},[tQ]:{event:Zv,status:"withdrawn",endsRole:!0}};var Qd=s(()=>Dl[0],"beneficiary"),Xv=366;function rQ(e){let n=e.reads,t=Fl(e).flatMap(({address:r})=>un(r)&&!Dl.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(un):[],...t]}s(rQ,"printedFields");function iQ(e,n){let t=de(n);return e.nodes.filter(r=>r.type==="governedDocument"&&rQ(r).some(i=>de(i)===t))}s(iQ,"documentsPrinting");function oQ(e,n){if(!un(n)||n.path!==Qd())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!At(t)}s(oQ,"isCreatedFormBeneficiary");function Kn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Kn,"issue");function sQ(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Yv,Jd].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"&&we(d.form)&&Sr(d.form)&&d.form.owner===t)){if(d.type==="end"){if(No(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(sQ,"reachesApprovedEndUnreviewed");var ex={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},$0={[E0]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:ex,external:en(te("Unterlagen fehlen","Documents missing"),"amber",te("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),te("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."))},[Hv]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:ex,external:en(te("Unterlagen vollst\xE4ndig","Documents complete"),"green",te("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),te("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[Jv]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:ex,external:en(te("Abgeschlossen","Closed"),"neutral",te("Die Nachreichung ist abgeschlossen","The document request is closed"),te("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[Qv]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:iP,external:en(te("Abgelehnt","Rejected"),"red",te("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),te("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."))},[Zv]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:hp,external:en(te("Zur\xFCckgezogen","Withdrawn"),"red",te("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),te("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},R0={outcomes:g0,progressDefaults:$0,progressEvents:qn($0),notificationEvents:s(()=>[{id:T0,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 n=s(r=>e.next?.[r]!==void 0,"wired"),t=[];return n(Jd)&&t.push({id:v0,kind:"advance",outcome:Jd,semantic:"other",label:{de:S0,en:"Close without documents"},surface:tr,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"}}}),n(Wm)&&t.push({id:x0,kind:"advance",outcome:Wm,semantic:"rejected",label:{de:A0,en:"Reject application"},surface:tr,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"}}}),t},"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,n,t)=>{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(E=>je(n,E,"de"),"shown"),l=s(E=>je(n,E,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Kn(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 E=new Set;for(let T of d){if(!we(T))continue;let R=de(T);if(E.has(R)){r.push(Kn(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(T)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(T)} appears twice in \`requires\`.`}));continue}if(E.add(R),!un(T)){r.push(Kn(e,"requires",{de:`[completenessCheck/unknownField] ${a(T)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(T)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let D=Ur(t,T);if(D==null)continue;let L=Js("requires",Hs(D));L==="computed"||L==="repeated"?r.push(Kn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${D.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${D.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Kn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${Vi(D,"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(T)} ("${Vi(D,"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(Kn(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 E=u.inDays;(typeof E!="number"||!Number.isInteger(E)||E<0||E>Xv)&&r.push(Kn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(E)}" ist keine ganze Zahl von 0 bis ${Xv} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(E)}" is not a whole number from 0 to ${Xv} days.`}))}else typeof u.until!="string"||Dw(u.until)===null?r.push(Kn(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<EP(Date.now())&&r.push({...Kn(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 E=new Map(d.filter(un).map(T=>[de(T),T]));for(let T of E.values())for(let R of iQ(n,T))r.push(Kn(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(T)} flie\xDFt in das Dokument \u201E${R.label?.de??R.id}" (${R.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(T)} flows into the document "${R.label?.en||R.id}" (${R.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)&&t!==void 0){let E=d.filter(un).filter(D=>{let L=Ur(t,D);return L!=null&&Lp(L)}),R=[...new Set(E.map(D=>D.owner))].filter(D=>sQ(n,e,D));if(R.length>0){let D=E.filter(L=>R.includes(L.owner));r.push({...Kn(e,"next",{de:`[review/unreviewedAfterSupply] ${D.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] ${D.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,b=y?.kind==="binding"?y.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Kn(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."})):t?.roleKeys!==void 0&&!t.roleKeys.has(k)?r.push(Kn(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...t.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...t.roleKeys].sort().join(", ")}.`})):t?.assignableRoleKeys!==void 0&&!t.assignableRoleKeys.has(k)&&r.push(Kn(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.`})),b===null&&r.push(Kn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Mn}.${Qd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${Mn}.${Qd()}).`}))),we(b)&&!oQ(n,b)&&r.push(Kn(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(b)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${Mn}.${Qd()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(b)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${Mn}.${Qd()}).`})),b!==null&&k===void 0&&r.push(Kn(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 E of["complete","rejected"])e.next?.[E]===void 0&&r.push(Kn(e,`next.${E}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${E}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${E}" nowhere.`}));return r},"validate")};var aQ=[{id:aO,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Ym=s(e=>e,"asDecision"),I0={[lO]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),te("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."))}},O0={role:"user-action",effect:"side-effect",outcomes:aQ,progressDefaults:I0,progressEvents:qn(I0),notificationEvents:s(e=>ts.notificationEvents(Ym(e)),"notificationEvents"),inputs:s(()=>[{id:ir,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:zo.map(e=>({value:e,label:ZC[e]}))}],"inputs"),actions:s(e=>[...ts.actions(Ym(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Uy,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:ts.optionalActionKinds,workItemTemplates:s(e=>ts.workItemTemplates(Ym(e)).map(n=>n.key===Da?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Uy]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Uv(Ym(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!Vf.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?.[ir],a=XC(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${ir}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${zo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${zo.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"}),we(d)&&Sr(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Lp)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(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 ${de(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 ${de(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 ${de(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 _0=["awaitingAnswer","answered"];async function P0(e,n){return(await oa(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(P0,"externalRequestState");var D0=[{id:_o,label:{de:"Bezahlt",en:"Paid"}}],lNe=new Set(D0.map(e=>e.id));var lQ=_o,N0=[{id:lQ,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],dQ={id:yw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:tr,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"}}},cQ={id:gw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:tr,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"}}},uQ={id:gw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:tr,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 nx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(nx,"literalOf");function Qi(e){let n=nx(e,it);return Xf(n)?n:null}s(Qi,"modeOrNull");function fQ(e){let n=nx(e,Ki);return typeof n=="string"&&n.length>0?n:null}s(fQ,"articleKeyOrNull");function pQ(e){let n=nx(e,er);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(pQ,"payeeKeyOrNull");var mQ={id:Ki,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},hQ={id:it,label:{de:"Zahlungsweg",en:"Payment mode"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"manual",label:{de:"Manuell (\xDCberweisung an die Schule)",en:"Manual (transfer to the school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},gQ={id:ji,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},yQ={id:er,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function wQ(e){return[mQ,hQ,...Qi(e)==="online"?[yQ]:[],gQ]}s(wQ,"collectPaymentInputs");var kQ=["amount","currency","settlement"],bQ={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},vQ={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function xQ(e,n){if(Qi(e)!=="online")return[];let t=pQ(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${er}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return n?.traeger!==void 0&&!n.traeger.has(t)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${t}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...n.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${t}" is not a legal entity of this school \u2014 known: ${[...n.traeger.keys()].join(", ")||"(none)"}.`})]:n?.stripeReadyTraegerKeys!==void 0&&!n.stripeReadyTraegerKeys.has(t)?[i({de:`[collectPayment/onlineWithoutStripe] Zahlungsweg \u201Eonline" an \u201E${t}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${t}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Emanual" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Payment mode "online" to "${t}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${t}") \u2014 otherwise no family can pay. Until then, choose "manual".`})]:[]}s(xQ,"payeeIssues");var C0={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:en(te("Zahlung offen","Payment due"),"amber",te("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),te("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},F0={outputs:s(()=>[{name:VO,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>wQ(e),"inputs"),outcomes:D0,progressDefaults:C0,progressEvents:qn(C0),notificationEvents:s(e=>Qi(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 n=Qi(e);return n==="online"?[...N0,uQ]:n==="manual"?[dQ,cQ]:[]},"actions"),states:_0,currentState:s((e,n)=>P0(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:Qi(n.node)==="manual"?Vv:jv}),"currentState"),workItemTemplates:s(e=>{let n=e,t=Qi(n);return t==="manual"?[{key:ki,recipient:"internal",title:bQ,unlocks:[yw],advancesNode:!0},{key:Vv,recipient:"external",title:vQ,unlocks:[],informational:!0,advancesNode:!1}]:t!=="online"?[]:[{key:jv,recipient:"external",title:n.label,unlocks:N0.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,n,t)=>{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 kQ)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"), der Zahlungsweg ist der Parameter \u201EZahlungsweg" (inputs.mode).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and the payment mode is the parameter "Payment mode" (inputs.mode).`});r.push(...xQ(e,t)),Qi(e)==="manual"&&e.assign?.[ki]===void 0&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird manuell bezahlt, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is paid manually, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."}),Qi(e)===null&&i(`inputs.${it}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${Gs.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[it])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${Gs.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[it])}.`});let o=e.inputs?.[ji];if(o?.kind==="literal"){let d=Oo(o.value);d!==null&&i(`inputs.${ji}`,{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=fQ(e);if(a===null)return i(`inputs.${Ki}`,{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.${Ki}`;return t?.billingItemKeys!==void 0&&!t.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):(t?.oneTimeBillingItemKeys!==void 0&&!t.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${ww.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${ww.join(", ")}.`}),t?.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."}):t?.offerProgram?.directBillingItemKeys!==void 0&&!t.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${t.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 "${t.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function L0(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(L0,"localeFieldMissingText");var tx=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),M0=/^[a-z][a-z0-9_]*$/;function q0(e,n){let t=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${n}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${n}" 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"||!M0.test(a.key)||o.has(a.key)){t.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${n}" 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 "${n}" 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(!qi(a.type)){t.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${n}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Us.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${n}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${Us.join(", ")}).`}});continue}if(tx.has(a.type)||t.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${n}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...tx].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a letter only prints ${[...tx].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!M0.test(String(d.value)))&&t.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${n}" 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 "${n}" 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)&&t.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${n}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${n}" 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")&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${n}" 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 "${n}" 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&&t.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"?t.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&&!Wp.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Wp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Wp.join(", ")}.`}})}return t.push(...SQ(e,n)),t}s(q0,"templateParameterIssues");function SQ(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:L0(n)}];let t=e.fields.find(i=>i.key===e.localeField),r=t===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:t.type!=="enum"?{de:`ist ${t.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${t.type}, a select field (enum) is expected`}:t.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"}:(t.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(t.options??[]).some(i=>!Ye.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${Ye.join(", ")})`,en:`has options that are not a language (allowed: ${Ye.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${n}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${n}" ${r.en}.`}}]}s(SQ,"localeFieldIssues");function K0(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(K0,"applyTemplateStamp");var rx=50;async function Hm(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(rx+1);return t.length>rx&&F(`signing_returns: Vorgang ${n} has more than ${rx} returns`),t}s(Hm,"returnsOf");var ix=50;async function ox(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(ix+1);return t.length>ix&&F(`signing_returns: return ${n} has more than ${ix} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(ox,"returnDocumentsOf");async function j0(e,n){let t=await ox(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(j0,"soleReturnDocumentOf");var Jm=200,RNe=Jm*20;async function AQ(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(AQ,"processRedacted");async function sx(e,n){await AQ(e,n)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(sx,"assertProcessReadable");function EQ(e){let n={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...n,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...n,scope:"node",result:e.result}}s(EQ,"rowOf");async function V0(e,n,t){await sx(e,n);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",n).eq("scope",t.scope).eq("owner",t.owner).eq("key",t.key)).order("desc").take(Jm+1);return r.length>Jm&&F(`[process] application ${n} has more than ${Jm} results of ${t.scope}.${t.owner}.${t.key}`),r.map(EQ)}s(V0,"storeHistory");async function TQ(e,n,t){if(t.key===Mn){await sx(e,n);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",n).eq("formNodeId",t.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 V0(e,n,{scope:"node",owner:t.owner,key:t.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(TQ,"nodeResultAt");async function Qm(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return $Q(await TQ(e,n.applicationId,t),t,n.applicationId)}s(Qm,"readOwnResult");function $Q(e,n,t){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${de(n)} of application ${t} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s($Q,"refOf");var ax={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},RQ=Object.keys(ax),IQ=RQ.filter(e=>ax[e]==="open"),LNe=IQ.filter(e=>e!=="pending");function B0(e){return ax[e]==="terminal"}s(B0,"isTerminalSigningStatus");var Zi=["docusign","insign"];var Zd={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var _Q=B0;function G0(e){return!_Q(e.status)&&e.voidRequestedAt===void 0}s(G0,"holdsContract");async function z0(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(z0,"traegerLegalEntityOfParty");async function PQ(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(PQ,"isOrganizationParty");async function W0(e,n){return await z0(e,n)!==null?"traeger":await PQ(e,n)?"organization":"person"}s(W0,"signerKindOf");async function Y0(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await NQ(e,t.partyId)==="family")return"family";return"traeger"}s(Y0,"signingSideOf");async function NQ(e,n){return await W0(e,n)==="traeger"?"traeger":"family"}s(NQ,"sideOfParty");var vCe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),J0=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var lx=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Zm=m.object({period:lx,anchorDate:m.string()});var TCe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),$Ce=m.union(m.literal("line"),m.literal("aggregate")),Xm=m.record(m.string(),m.string());var CQ=m.union(m.literal("active"),m.literal("ended")),dx=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()})),DQ=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),FQ={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:dx,pricingSelections:m.optional(Xm),paymentSchedule:m.optional(Zm),resolvedSnapshot:m.any(),feeGroup:m.optional(J0),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},LQ={...FQ,period:DQ,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:CQ,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},DCe=Ct(LQ).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Tr=m.union(m.string(),m.null()),Q0=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),MQ=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()}))}),Z0=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(Q0)})),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:Tr}),X0=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(lx),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Tr,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),qQ={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Tr,pricing:dx,paymentSchedule:m.optional(Zm),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:Tr,endDate:Tr,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Tr,programName:Tr,runName:Tr,groupName:Tr}),m.null()),grants:m.array(X0),payerAllocations:m.array(Z0)},KQ=m.object({...qQ,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Tr,sourceValidTo:Tr})}),jQ=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(Q0),declaredSigners:m.array(MQ),payerAllocations:m.array(Z0),aggregateGrants:m.optional(m.array(X0)),lines:m.array(KQ)}),VQ=jQ;var BQ=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),UQ=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:Ji})),caption:m.string(),page:m.number(),box:BQ}))});var GQ=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(UQ)}))}),zQ=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()}),WQ={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:GQ,coverLetter:m.optional(zQ),snapshot:Ve.historyOf(VQ),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()}))},UCe=Ct(WQ).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 iDe=16*1024;var oDe=15*6e4;var sDe=10*6e4;var cx={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()}))},SDe=Ct({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...cx}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var RDe=m.object(cx);var ux=200;async function YQ(e,n,t,r){n.length>ux&&F(`${r} is carried by more than ${ux} signing requests`);let i=[],o=new Set;for(let l of n){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=t==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(YQ,"requestsOfMembers");async function eM(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(ux+1);return await YQ(e,r,t,`revision ${n}`)}s(eM,"requestsOfSnapshot");var nM=100;async function HQ(e,n){let t=await eM(e,n);t.length>nM&&F(`requestsBySideOf: revision ${n} has more than ${nM} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await Y0(e,i.signers)].push(i);return r}s(HQ,"requestsBySideOf");async function fx(e,n){return(await HQ(e,n)).family}s(fx,"familyRequestsOf");var px=100;async function JQ(e,n){let t=await e;return t.length>px&&F(`contractChain: more than ${px} ${n}`),t}s(JQ,"bounded");async function QQ(e,n,t){let r=await Qm(e,{applicationId:n,nodeId:t,key:Yf});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Yf} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(QQ,"nodeContractRef");async function tM(e,n){return await JQ(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",t=>t.eq("contractId",n)).take(px+1),`revisions on contract ${n}`)}s(tM,"snapshotsAsc");async function mx(e,n){let t=(await fx(e,n)).filter(G0);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(mx,"openFamilyRequest");async function ZQ(e,n){for(let t of await tM(e,n))if((await fx(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(ZQ,"familyRoute");async function rM(e,n){for(let t of n)if(await ZQ(e,t)==="paper")return"paper";return"provider"}s(rM,"familyRouteOf");async function XQ(e,n){let t=await j0(e,n._id),r=await e.db.system.get("_storage",t.storageId);return r===null&&F(`contractChain: return ${n._id} holds missing file ${t.storageId}`),{_id:n._id,_creationTime:n._creationTime,storageId:t.storageId,filename:t.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:n._id}}s(XQ,"toReturn");function eh(e){async function n(a,l){return await QQ(a,l,e.id)}s(n,"contractOrNull");async function t(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await n(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(t,"snapshotOf");async function r(a,l){let d=await n(a,l);return d===null?null:(await tM(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 t(a,l,d.askedAbout,`returned(${d.where})`),u=await mx(a,c._id);if(u===null)return null;let p=(await Hm(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 XQ(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:n,snapshotOf:t,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await n(a,l);return d===null?[]:[d]}}.contractsOf}}s(eh,"contractNodeReads");function nh(e){return e.addedParts??[]}s(nh,"addedPartsOf");var hx=50;async function e8(e,n){let t=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",n)).take(hx+1);return t.length>hx&&F(`groupRunsOf: generation group ${n} has more than ${hx} runs`),t.length===0&&F(`groupRunsOf: generation group ${n} has no run`),t.sort((r,i)=>r._creationTime-i._creationTime)}s(e8,"groupRunsOf");async function iM(e,n){let t=await e8(e,n),r=t[0].packageRunId;if(r!==void 0){(t.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(t.map(l=>l.partKey)).size!==t.length)&&F(`groupRunsInOrder: package group ${n} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${n} 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),...nh(i).map(l=>l.partKey)];return(o.length>50||t.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${n} names an unknown part`),t.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${n} has no package reference.`)}s(iM,"groupRunsInOrder");function oM(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(oM,"isCompleteGroup");var gx=200;function n8(e){let n=e.generatorStamp?.parts;return n===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),n.map(t=>t.partKey)}s(n8,"groupPartKeys");async function t8(e,n,t){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",n).eq("workflowNodeId",t)).take(gx+1);return r.length>gx&&F(`groupChain: more than ${gx} generation runs on node ${t}`),r}s(t8,"nodeRuns");async function r8(e,n,t){let r=n8(t),i=new Set;for(let a of await t8(e,n,t.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${t.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await iM(e,a);if(!oM(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(nh(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 "${t.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(r8,"groupRevisionRows");async function yx(e,n,t){let r=await Qm(e,{applicationId:n,nodeId:t,key:Hf});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${Hf} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(yx,"nodeGroupContracts");async function i8(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await mx(e,r._id);i!==null&&t.set(i._id,i)}return t.size>1&&F(`groupChain: generation group ${n.packageRunId} is held by ${t.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...t.values()][0]??null}s(i8,"openGroupRequest");async function o8(e,n){let t=[];for(let i of await ox(e,n._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${n._id} holds missing file ${i.storageId}`),t.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=t[0];return{_id:n._id,_creationTime:n._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:n._id,documents:t}}s(o8,"toGroupReturn");function sM(e){async function n(i,o,a,l){let d=(await r8(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(n,"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 n(i,o,a.askedAbout,`returned(${a.where})`),d=await i8(i,l);if(d===null)return null;let c=(await Hm(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 o8(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await yx(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(sM,"groupNodeReads");async function s8(e,n){let t=n.lifecycle.kind==="draft"?void 0:n.lifecycle.kind;return{_id:n._id,_creationTime:n._creationTime,versionNumber:n.versionNumber,...t!==void 0?{status:t}:{},origin:n.origin.kind,storageId:n.storageId,...await sb(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(s8,"toRevision");async function a8(e,n){let t=await s8(e,n);return{_id:t._id,_creationTime:t._creationTime,storageId:t.storageId,...t.filename!==void 0?{filename:t.filename}:{},...t.mimeType!==void 0?{mimeType:t.mimeType}:{},round:t.versionNumber}}s(a8,"toReturn");function aM(e){let n=Qp(e);async function t(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",n)).collect()}return s(t,"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 t(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 "${n}"`),c.versionNumber<=u.versionNumber)return null}return await a8(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(aM,"artifactNodeReads");function th(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(th,"documentChainKind");function lM(e){switch(th(e)){case"contract":return eh(e).reads;case"group":return sM(e).reads;case"artifact":return aM(e).reads}}s(lM,"documentReadsFor");var l8={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Xd(e){let n=e.responseStrategy;return typeof n=="string"&&n in hi?hi[n].producesResponseArtifact:!1}s(Xd,"returnsSignedCopy");function d8(e){return Xd(e)&&e.confirmContractTerms!==!1}s(d8,"asksContractTerms");function dM(e){return d8(e)?{title:e.contractTermsQuestionText??l8,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(dM,"contractTermsConfirm");function cM(e){let n=c8(e);return n.length>0&&n.every(t=>t.status==="blocked")}s(cM,"producerWindowHeld");function c8(e){return e.filter(n=>n.isOpen&&n.kind==="admission"&&n.templateKey!==void 0&&od.has(n.templateKey))}s(c8,"openProducerRows");async function u8(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:Ww(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Yr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${Yr} row`),a}s(u8,"rejectedReturnOfAsk");async function uM(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await u8(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(uM,"returnedCopyOfAsk");var wx=new Set([...od,Ar,Ko,Yi,Yr,ht]),gM={id:Un,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},yM={id:xo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function f8(e){let n=[],t=[{slot:gM,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:yM,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of t){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){n.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"){n.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=Ll(a.value,{type:r.type});d!==null&&n.push(Se(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return n}s(f8,"referenceInputIssues");var p8={id:mi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},m8={id:wa,type:"boolean",label:{de:"Coverletter best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},h8={id:Lt,type:"legalEntity",label:kC,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function g8(e,n){let t=`inputs.${Lt}`,r=e.inputs?.[Lt];if(r!==void 0&&r.kind==="binding")return[Se(e,t,{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=ya(e),o=n?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=n?.traeger?.get(l);n?.traeger!==void 0&&d===void 0?a.push(Se(e,t,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...n.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...n.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Se(e,t,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Kp.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 (${Kp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(g8,"traegerIssues");function rh(e){if(e.production==="template"){let t=e.templateStamp?.fields;return Array.isArray(t)?t:[]}if(e.production!=="resolver")return[];let n=e.generatorStamp?.inputSchema?.fields;return Array.isArray(n)?n.map(t=>{let{label:r}=t;return r===void 0?{...t,label:{de:t.key,en:t.key}}:(Ci(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${t.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...t,label:r})}):[]}s(rh,"generatorFields");function y8(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(y8,"deferredToCockpit");function w8(e){return qi(e.type)?e.type:void 0}s(w8,"resolverSlotType");function k8(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=va(e);return{confirm:{title:{de:`\u201E${n.de}\u201C jetzt senden?`,en:`Send "${n.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(k8,"issueConfirmation");function Se(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Se,"issue");function ih(e){return zp.includes(e.production)&&Go.includes(e.approval)&&Yp.includes(e.responseStrategy)}s(ih,"hasValidModes");async function kx(e,n){let t=await oa(e,{applicationId:n.applicationId,nodeId:n.node.id});if(t.length===0)return"pending";let r=t.filter(a=>a.isOpen&&a.kind==="admission");if(cM(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&od.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===Yi))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Ar);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===ht))return"signatureStalled";let o=r.find(a=>a.templateKey===Ko);if(o!==void 0){if(gi(n.node).issuesBy==="provider"){let l=th(n.node)==="group"?(await yx(e,n.applicationId,n.node.id)).map(d=>d.contractId):[await eh(n.node).contractOrNull(e,n.applicationId)].flatMap(d=>d===null?[]:[d]);if(l.length===0&&F(`governedDocCurrentState: eSignature node "${n.node.id}" has an open ask but no contract`),await rM(e,l)==="provider")return"awaitingSignature"}return gi(n.node).producesResponseArtifact?await uM(e,{chain:lM(n.node),applicationId:n.applicationId,ask:o,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${n.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(a=>a.templateKey===Yr)?"responseInCheck":"done"}s(kx,"governedDocCurrentState");function fM(e){return e.production!=="none"&&th(e)!=="artifact"}s(fM,"keepsDocumentInContractDomain");function b8(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!Zt(r.key))return[];let i=vo(r.key);if(n.type!==i.type)return[Se(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.key}" ist ${n.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${de(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${n.key}" is ${n.type}, the environment variable "${i.label.en}" (${de(r)}) supplies ${i.type}.`})];let o=new Set((n.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Se(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.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 "${n.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(b8,"envCoverageIssues");function wM(e,n){let t=[];for(let r of rh(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...b8(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${we(a.address)?de(a.address):JSON.stringify(a.address)}`,en:`a binding to ${we(a.address)?de(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:y8(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&t.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||t.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${n.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 ${n.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 t}s(wM,"fieldSourceIssues");function v8(e){let n=br(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=q0(e.templateStamp,n).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...wM(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(v8,"templateIssues");function x8(e,n){return(n?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(t=>{if(t.documentAnchors===null)return[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${t.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 "${t.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=t.signerAnchors.filter(i=>!t.documentAnchors.has(i));return r.length===0?[]:[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${t.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 "${t.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(x8,"eSignatureAnchorIssues");function S8(e,n){return n===void 0||n.sendable?[]:gi(e).issuesBy!=="provider"?[]:[Se(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${n.reason.en}`})]}s(S8,"eSignatureProviderIssues");var pM={key:"dokument",label:te("Dokument","Document"),scope:"node"},mM={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:pM,external:en(te("In Vorbereitung","In preparation"),"blue",te("Ihr Dokument wird vorbereitet","Your document is being prepared"),te("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:te("Dokument bereitgestellt","Document issued"),tone:"blue",phase:pM,external:en(te("Dokument bereit","Document ready"),"amber",te("Ihr Dokument liegt bereit","Your document is ready"),te("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."),te("Dokument beantworten","Respond to the document"))}};function hM(e,n){return!ih(e)||e.production==="none"?null:n===Yi||Jp(e).some(r=>r.key===n)?Qp(e):null}s(hM,"governedDocRowSlot");var kM={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>qo,"processHoldTemplate"),progressDefaults:mM,progressEvents:qn(mM),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(!ih(e))return[];let n=gi(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...Uo(e)?["awaitingCoverLetter"]:[],...i,...n.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(t.push({id:yk(e),kind:"internal",surface:ka,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Ar}:{},...k8(e)??{}}),t.push({id:SC,kind:"internal",surface:ka,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:AC,kind:"internal",surface:ka,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:Bp,kind:"internal",label:e.responseLabels?.accept??n.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:n.acceptOutcomeId,kind:"advance",outcome:n.acceptOutcomeId,semantic:n.outcomeSemantics.accept,label:e.responseLabels?.accept??n.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:n.declineOutcomeId,kind:"advance",outcome:n.declineOutcomeId,semantic:n.outcomeSemantics.decline,label:e.responseLabels?.decline??n.defaultLabels.decline,availableIn:Uo(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),Uo(e)&&(t.push({id:jp,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),t.push({id:Vp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),n.producesResponseArtifact&&t.push({id:Up,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Gp,kind:"internal",surface:ka,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:jo,kind:"internal",surface:ka,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:EC,currentState:kx,workItemTemplates:s(e=>{let n=e;return ih(n)?Jp(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e,r=hM(t,n);return r===null?[]:Jp(t).find(o=>o.key===n)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,n)=>{let t=hM(e,n);if(t!==null)return n===Yi?{kind:"artifact",slot:t,part:"coverLetter"}:{kind:"artifact",slot:t}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[gM,h8]:[],...e.production==="template"?[yM]:[],p8,...e.generatorStamp?.coverLetter===!0?[m8]:[],...rh(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=w8(n);return t===void 0?[]:[{field:n,type:t}]}).map(({field:n,type:t})=>({id:n.key,type:t,label:n.label,required:n.required===!0&&n.processSource===void 0,...n.processSource===void 0?{deferrable:!0}:{},...n.defaultValue!==void 0&&(typeof n.defaultValue=="string"||typeof n.defaultValue=="number"||typeof n.defaultValue=="boolean"||n.defaultValue===null||t==="pricedItem"&&Mi(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:ow,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Ko||n===Yi||n===id||n===Yr||n===ht){let t=n===Ko?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===Yr?{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"}:n===ht?{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 "${n}" (Knoten "${e.id}") ist verboten \u2014 ${t.de}; zul\xE4ssige intrinsische Ziele: ${qo}${e.approval==="release"?`, ${Ar}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${qo}${e.approval==="release"?`, ${Ar}`:""}.`}}return n===Ar&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Ar}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Ar}" 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,n)=>{if(fM(n.node))return!1;let t=await kx(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&gi(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=dM(n.node);if(t===null||fM(n.node))return null;let r=await kx(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!ih(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${zp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Go.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Yp.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 {${zp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Go.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Yp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=hi[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 E of o)E.visibility!=="external"&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${E.key}" auf Knoten "${e.id}" hat visibility "${E.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${E.key}" on node "${e.id}" has visibility "${E.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(E=>E.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(E=>l.includes(E)))&&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(E=>`"${E}"`).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(E=>`"${E}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(E=>{let T=c?.[E];return T===null||typeof T!="object"||!Object.values(T??{}).some(R=>typeof R=="string"&&R.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"&&w.prepareDocument===void 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.`})),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)w.responseCheck===void 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[E,T]of[["assign.responseCheck",w.responseCheck!==void 0],["titles.check",c?.check!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${E} \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 ${E} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"?w.signingRecovery===void 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.`})):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'.`})),i.issuesBy==="provider"&&r.push(...x8(e,t),...S8(e,t?.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.`})),Xd(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[E,T]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${E} \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 ${E} \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[E,T]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",w.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${E} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${E} \u2014 without a production phase there is nothing to carry it.`}));for(let E of e.tasks??[])wx.has(E.key)&&r.push(Se(e,`tasks.${E.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${E.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...wx].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${E.key}" on node "${e.id}" collides with an intrinsic template (${[...wx].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...g8(e,t)):e.inputs?.[Lt]!==void 0&&r.push(Se(e,`inputs.${Lt}`,{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(...f8(e)),e.production==="resolver"){let E=oi(e);if(E!==null){let T=eO(E);for(let R of rh(e)){if(!qi(R.type)){r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/unknownFieldType] Generator "${T}" typisiert das Feld "${R.key}" als "${String(R.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Us.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${T}" types the field "${R.key}" as "${String(R.type)}" \u2014 that is not part of the platform's value vocabulary (${Us.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(R.type==="personList"){r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${T}" deklariert das Feld "${R.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 "${T}" declares the field "${R.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}R.type==="party"&&(R.key.endsWith("PartyId")||r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${R.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 "${R.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...wM(e,{de:`"${T}"`,en:`"${T}"`}))}}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(...v8(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?.[wa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${wa}`,{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.`})),Uo(e)&&(t!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${wa}`,{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.`})),gi(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?.[mi],b=y===void 0||y.kind==="unset"?void 0:y.kind==="literal"?y.value:y;return b!==void 0&&!ad(b)&&r.push(Se(e,`inputs.${mi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(b)} \u2014 erlaubt ist eine ganze Zahl von ${Vo} bis ${Bo} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(b)} \u2014 a whole number from ${Vo} to ${Bo} days is allowed.`})),b===void 0&&rh(e).some(E=>E.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${mi}`,{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 bM={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 Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Bt,"isRecord");var bx=["field","join","literal","address","payment","contract"],A8=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),E8=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ar(e){return typeof e=="string"&&e.trim().length>0}s(ar,"nonEmptyString");function oh(e,n,t,r,i="value"){if(!Bt(e)||!Bt(e.from)){r.push({path:n,code:"mappingShape",message:{de:`${n}: eine Zuordnung braucht \`from\`.`,en:`${n}: a mapping needs \`from\`.`}});return}let o=e.from,a=bx.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${bx.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${bx.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ar(o.field)&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.field\` ist leer.`,en:`${n}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(ar))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${n}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${n}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${n}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||ar(e.whenEmpty)||r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${n}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(we(o.address)&&o.address.scope==="env"&&Zt(o.address.key))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${n}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.payment\` ist amount oder settledAt.`,en:`${n}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${n}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${n}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!A8.has(String(e.format))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekanntes Format \u201E${String(e.format)}".`,en:`${n}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(ar(e.lookup)&&Bt(t[e.lookup]))&&r.push({path:n,code:"unknownLookup",message:{de:`${n}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${n}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||Bt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Bt(d)&&E8.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(oh,"checkMapping");function Xi(e,n,t,r,i){if(!Bt(e)){i.push({path:n,code:"bodyShape",message:{de:`${n}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${n}: expects an object field \u2192 mapping.`}});return}let o=bM[t];for(let a of o.required)a in e||i.push({path:`${n}.${a}`,code:"missingRequired",message:{de:`${n}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${n}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))oh(l,`${n}.${a}`,r,i)}s(Xi,"checkBody");function vM(e,n,t,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:n,code:"bodyShape",message:{de:`${n}: erwartet eine Liste.`,en:`${n}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${n}[${a}]`;if(!Bt(o)||!ar(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),oh(o.value,`${l}.value`,t,r),o.unless!==void 0&&oh(o.unless,`${l}.unless`,t,r,"condition")})}s(vM,"checkAif");function vx(e){let n=[];if(!Bt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Bt(e.lookups)?e.lookups:{};Bt(e.lookups)||n.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(t))(!Bt(i)||!Object.values(i).every(ar))&&n.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(ar(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Xi(e.pupil,"engage.pupil","addPupil",t,n),Xi(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&Xi(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&Xi(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&Xi(e.medical,"engage.medical","addMedical",t,n),vM(e.pupilAif,"engage.pupilAif",t,n),!Array.isArray(e.contacts))n.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(!Bt(i)||!ar(i.key)||!ar(i.presentIf)){n.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&n.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Xi(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&Xi(i.address,`${a}.address`,"addContactAddress",t,n);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){n.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Xi(u,`${a}.${l}[${p}]`,d,t,n))}}vM(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&oh(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Bt(r)||!ar(r.repeated)||!ar(r.field)||!ar(r.equals))&&n.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return n}s(vx,"engagePushConfigIssues");function*xx(e){let n=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let t of n)for(let r of Object.values(t??{}))yield{mapping:r};for(let t of e.pupilAif??[])yield{mapping:t.value},t.unless!==void 0&&(yield{mapping:t.unless});for(let t of e.contacts){let r=[t.basic,t.address,...t.emails??[],...t.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:t.key};for(let i of t.aif??[])yield{mapping:i.value,contactKey:t.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:t.key});t.linkAddressToPupilIf!==void 0&&(yield{mapping:t.linkAddressToPupilIf,contactKey:t.key})}}s(xx,"mappingsOf");function xM(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of xx(e))for(let i of T8(t.from))n.add($8(i,r));return[...n]}s(xM,"configFieldKeys");function T8(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(T8,"formFieldsOf");function $8(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s($8,"resolveFieldKey");function SM(e,n){for(let{mapping:t}of xx(e))if(n in t.from)return!0;return!1}s(SM,"configReadsSource");function AM(e){let n=new Set;for(let{mapping:t}of xx(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(AM,"configEnvLeaves");var EM="done",TM=["sandbox","production"];var sh="engagePush",ELe=660*1e3;function eo(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(eo,"issue");function Sx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Sx,"literal");function $M(e){return vx(e.engage).length===0?e.engage:null}s($M,"validConfig");function R8(e,n){let t=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===n||i.has(a))continue;i.add(a);let l=t.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(R8,"bypassingPath");var RM={role:"system-action",effect:"side-effect",outcomes:[{id:EM,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=$M(e);return n===null?[]:AM(n)},"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,n,t)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=Sx(e,"target");TM.includes(a)||o.push(eo(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=Sx(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(eo(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`})),e.assign?.[sh]===void 0&&o.push(eo(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${sh}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${sh}\` names the team.`}));for(let k of vx(e.engage))o.push(eo(e,k.path,{de:`[engagePush/config] \u201E${r}": ${k.message.de}`,en:`[engagePush/config] "${i}": ${k.message.en}`}));let d=n.nodes.filter(k=>k.id!==e.id&&k.type==="engagePush"&&Sx(k,"target")===a);d.length>0&&o.push(eo(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${d.map(k=>`"${k.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${d.map(k=>`"${k.id}"`).join(", ")} already transfers to the same target.`})),R8(n,e.id)&&o.push(eo(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 c=$M(e),u=e;for(let[k,y,b,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!SM(c,k)||u[y]!==void 0||o.push(eo(e,y,{de:Ws("address/missing",{where:`\u201E${r}\u201C \u203A ${b}`},"de"),en:Ws("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let p=u.form,h=we(p)&&p.scope==="node"?p.owner:void 0,w=h===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&w!==void 0){let k=new Set(w.keys()),y=xM(c).filter(b=>!k.has(b)&&!/\[\d+\]\./.test(b));if(y.length>0){let b=n.nodes.find(E=>E.id===h);o.push(eo(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${b?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${y.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${b?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${y.join(", ")}.`},"warning"))}}return o},"validate")};var rs={join:n0,end:sP,roleAssign:r0,eventTrigger:i0,waitlist:b0,completenessCheck:R0,form:u0,setFlag:f0,if:p0,decision:ts,review:O0,collectPayment:F0,governedDocument:kM,countersign:qC,engagePush:RM};LO(rs);function IM(e,n){let t=e;if(t==null||!Array.isArray(t.nodes))throw new Error(`offer plan: the ${n} carries no workflow graph with nodes`);return e}s(IM,"graphOf");function OM(e){let n=new Map;for(let t of e.nodes)for(let r of Vr(e,t))n.set(de(r.address),r.nodeId);return n}s(OM,"producedOf");function _M(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(Ro(e,t).map(r=>de(r.address))));return n}s(_M,"readsOf");function PM(e,n){let t=IM(e,"bundle"),r=IM(n.graph,"live head"),i=OM(t),o=OM(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=_M(t),d=_M(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:n.revision,pinnedApplications:n.pinnedApplications,produced:a,reads:c}}s(PM,"planAddresses");function NM(e){let n=[...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(n.length===0)return[];let{real:t,test:r}=e.pinnedApplications;return n.push({icon:"!",target:"pinned",status:`${t+r} Anmeldungen (${t} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),n}s(NM,"addressPlanRows");function CM(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(CM,"changed");async function DM(e,n,t){if(n.index.module!==Mv.name)throw new Error(`offer: unknown module "${n.index.module}"`);return wD(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return Mv.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(DM,"applyOffer");async function FM(e,n,t,r="published"){let i=await e.query(x.setup.offerBundle.exportOfferBundle,{client:n,offerKey:t,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(FM,"exportOffer");async function Ax(e,n){let{index:t}=n,i=(await e.query(x.workflow.listManifests,{client:t.tenant})).find(w=>w.offerKey===t.slugs.manifest),o="create";i&&(o="same");let a={};for(let[w,k]of Object.entries(n.smartforms??{})){let y=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:w}):null;a[w]=y?.def?CM(k,{label:y.def.label,...y.def.definition})?"change":"same":"create"}let l="absent",d=null;if(n.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=CM(k&&{graph:Ds(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:Ds(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let w=await e.query(x.workflow.getOfferHeadPins,{client:t.tenant,offerKey:t.slugs.manifest});w!==null&&(d=PM(n.workflow.graph,w))}}let c=t.program?.stages,u=c===void 0?[]:i?await Lv(e,t.tenant,t.slugs.manifest,c):Af(null,[],c),p=await Gm(e,t.tenant,i?t.slugs.manifest:null,t),h=i?await e.query(x.workflow.getOfferPublishState,{client:t.tenant,offerKey:t.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(Ax,"diffOffer");function ah(e){if(e.type==="governedDocument"){let n=e.production;return n==="resolver"?"resolver":n==="template"?"template":n==="upload"||n==="none"?"manual":"unauthored"}return null}s(ah,"contractProductionModeOf");function LM(e){return ah(e)==="resolver"}s(LM,"isResolverCarrierNode");function lh(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=oi(t);return!LM(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(lh,"authoredPins");var MM={type:"address",dataType:"composite"};var qM={type:"boolean",dataType:"boolean"};var KM={type:"consent",dataType:"boolean"};var jM={type:"date",dataType:"date"};var VM={type:"docRef",dataType:"file"};var BM={type:"email",dataType:"text"};var UM={type:"string",dataType:"text"};var GM={type:"tel",dataType:"text"};var dh={address:MM.dataType,boolean:qM.dataType,consent:KM.dataType,date:jM.dataType,docRef:VM.dataType,email:BM.dataType,enum:U_.dataType,string:UM.dataType,tel:GM.dataType};function Ex(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Ex,"shapeOf");function zM(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,Ex(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,Ex(l)))),o.repeated?.forEach(a=>t.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:n}];for(let o of t){let a=new Map(n);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,Ex(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(zM,"fieldMapScopes");function I8(e){let n=new Set,t=s(r=>{r.computed?.forEach(i=>n.add(i.key)),r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(I8,"computedKeysOf");function WM(e){let n=[],t=I8(e);for(let r of zM(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}]`;t.has(l.from)&&n.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?n.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 n}s(WM,"validateFieldMapSources");function YM(e){let n=[],t=new Set;for(let o of zM(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)t.add(l.from);let r=s((o,a)=>{let l=a.some(d=>t.has(d));o.kind==="cf_value"&&!l?n.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&&n.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),n}s(YM,"validateFieldPersistence");var O8="$";function _8(e){return typeof e=="string"&&e.startsWith(O8)}s(_8,"isRef");function ch(e){return e.slice(1)}s(ch,"stripRef");function*P8(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let n of Object.values(e.meta))yield n;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(P8,"refSlots");function N8(e){let n=new Set;for(let t of P8(e))_8(t)&&n.add(ch(t));return[...n]}s(N8,"collectRefs");function C8(e){let n=new Set(e.map(o=>o.id)),t=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),t.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of N8(o))n.has(a)&&(t.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=ch(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&ch(l.target)===a||l.kind==="shareValue"&&ch(l.to)===a)||t.get(o.id).includes(l.id)||(t.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:t,successors:r,byId:i}}s(C8,"buildAdjacency");function HM(e){let{refsOf:n}=C8(e),r=Np(e.map(i=>i.id),i=>(n.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(HM,"detectCycle");function JM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(JM,"escapeRegExp");function no(e){return new RegExp(`^${JM(e)}\\[(\\d+)\\]\\.(.+)$`)}s(no,"repeatedRowKeyPattern");function Tx(e,n){let t=no(n),r=0;for(let i of Object.keys(e)){let o=i.match(t);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(Tx,"countRepeatedRows");function QM(e,n,t){let r=no(n);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==t)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(QM,"repeatedRowHasData");function ZM(e){return e.endsWith(".count")?e.slice(0,-6):e}s(ZM,"readKeyOf");function $x(e){return{sections:e,fields:[]}}s($x,"hiddenSectionsOnly");function XM(e,n,t){for(let r of e.fields)n.add(r.key);for(let r of e.groups??[])for(let i of r.fields)n.add(i.key);for(let r of e.computed??[])n.add(r.key);for(let r of e.repeated??[])t.add(r.key);for(let r of e.subsections??[])XM(r,n,t)}s(XM,"collectKeys");function eq(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;XM(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(no)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(eq,"restrictedSectionsOf");function nq(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(nq,"matchesKey");function D8(e,n){return n.find(t=>nq(e,t))??null}s(D8,"hiddenSectionOfKey");function F8(e,n){for(let t=e;;){if(nq(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(F8,"fieldOwnsKey");function L8(e,n){return n.find(t=>F8(e,t))??null}s(L8,"restrictedFieldOfKey");function M8(e,n){let t=D8(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=L8(e,n.fields);return r===null?null:{kind:"field",field:r}}s(M8,"hiddenOwnerOfKey");function uh(e,n){return M8(e,n)!==null}s(uh,"isKeyHidden");function q8(e,n,t,r,i){let o=[];r&&o.push({severity:"error",path:t,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((n.length===0||n.some(a)||new Set(n).size!==n.length)&&o.push({severity:"error",path:t,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 n)a(l)||i.has(l)||o.push({severity:"error",path:t,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(q8,"visibleToListIssues");function tq(e,n,t){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...q8(c.id,h,`${u}.visibleTo`,p,t));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=eq(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=$x(p);for(let w of _n(c)){let k=ZM(w);(uh(w,h)||uh(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&&uh(c.sameAs.source,$x(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((b,E)=>l(b,`${u}.groups[${y}].fields[${E}]`,w))}),c.repeated?.forEach((k,y)=>{a(k.itemVisibleIf,`${u}.repeated[${y}].itemVisibleIf`,w),k.itemTemplate.forEach((b,E)=>l(b,`${u}.repeated[${y}].itemTemplate[${E}]`,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 n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(tq,"sectionVisibilityIssues");var Qr="#";var rq=s(e=>{let n=ib.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),$r={firstName:rq("persons.firstName"),lastName:rq("persons.lastName")};function iq(e,n){let t={firstName:[],lastName:[]},r=`$${e}`;for(let i of n)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===$r.firstName?t.firstName.push(o):a===$r.lastName&&t.lastName.push(o);return t}s(iq,"personNameKeys");function oq(e){return[...e.firstName,...e.lastName]}s(oq,"personNameKeyList");function sq(e){return e.firstName.length>0||e.lastName.length>0}s(sq,"hasPersonName");function La(e,n=[],t){let r=[];return e.forEach((i,o)=>{let a=[...n,o];r.push({section:i,path:a,parentId:t});for(let l of La(i.subsections??[],a,i.id))r.push(l)}),r}s(La,"walkSections");function K8(e,n){for(let t of e.fields)if(t.key===n)return t;for(let t of e.groups??[])for(let r of t.fields)if(r.key===n)return r;for(let t of e.repeated??[])for(let r of t.itemTemplate)if(r.key===n)return r;return null}s(K8,"findFieldInSection");function aq(e,n){for(let t of La(e.sections)){let r=K8(t.section,n);if(r)return{section:t.section,field:r}}return null}s(aq,"findField");var j8=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],V8=["blue","rose","amber","violet","teal","emerald","slate"];function lq(e){return j8.includes(e)}s(lq,"isBucketIconName");function dq(e){return V8.includes(e)}s(dq,"isBucketColorName");var B8="__clear__";function cq(e){return e===""?"empty":e===B8?"reserved":null}s(cq,"selectOptionValueDefect");var Rx=bF.docRef.allowedMime;function gq(e,n={}){let t=fa(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(I,O){if(i.has(I))return;i.add(I);let j=o.get(I.id);j&&j!==I?r.push({severity:"error",path:`sections[${O.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${I.id}' ist mehrfach deklariert.`,en:`Section id '${I.id}' is declared more than once.`}}):o.set(I.id,I);let N=`sections[${O.join(".")}]`;I.fields.forEach((z,le)=>{Ma(a,z.key,`${N}.fields[${le}]`,"duplicate.field-key",r),l.add(z.key),u.set(z.key,z),c.set(z.key,Ox(z)),z.externalFlag&&(z.type!=="boolean"&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${z.key}' muss den Typ 'boolean' haben (ist '${z.type}').`,en:`External flag '${z.key}' must be type 'boolean' (got '${z.type}').`}}),z.reviewRequired!==void 0&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"review.on-flag",message:{de:`Externes Flag '${z.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 '${z.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),z.notice!==void 0&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${z.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${z.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),z.defaultValue==null&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"flag.missing-default",message:{de:`Externes Flag '${z.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${z.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...fq(z,`${N}.fields[${le}]`)),r.push(...uq(z,`${N}.fields[${le}]`))}),I.groups?.forEach((z,le)=>{z.fields.forEach((ce,De)=>{Ma(a,ce.key,`${N}.groups[${le}].fields[${De}]`,"duplicate.field-key",r),l.add(ce.key),u.set(ce.key,ce),c.set(ce.key,Ox(ce)),ce.externalFlag&&r.push({severity:"error",path:`${N}.groups[${le}].fields[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ce.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${ce.key}' must be a direct section field, not a group field.`}}),r.push(...fq(ce,`${N}.groups[${le}].fields[${De}]`)),r.push(...uq(ce,`${N}.groups[${le}].fields[${De}]`))})}),I.repeated?.forEach((z,le)=>{z.itemTemplate.forEach((ce,De)=>{Ma(a,ce.key,`${N}.repeated[${le}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(ce.key,Ox(ce)),ce.externalFlag&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ce.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${ce.key}' must be a direct section field, not a repeated item field.`}}),ce.export&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"export.in-repeated",message:{de:`Feld '${ce.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${ce.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),ce.sameAs&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${ce.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${ce.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),ce.reviewRequired!==void 0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"review.in-repeated",message:{de:`Feld '${ce.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 '${ce.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.`}}),ce.notice!==void 0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.notice-in-repeated",message:{de:`Feld '${ce.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 '${ce.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),ce.type==="docRef"&&ce.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${ce.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${ce.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),I.computed?.forEach(z=>{d.add(z.key),Ma(a,z.key,`${N}.computed[${z.key}]`,"duplicate.field-key",r),z.exportType==="consent"&&r.push({severity:"error",path:`${N}.computed[${z.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${z.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${z.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),z.export===!0&&z.exportType===void 0&&r.push({severity:"error",path:`${N}.computed[${z.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${z.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${z.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),I.subsections?.forEach((z,le)=>p(z,[...O,le]))}s(p,"visitRawSection"),e.sections.forEach((I,O)=>p(I,[O]));let h=new Set;t.effects.forEach((I,O)=>{Ma(h,I.id,`effects[${O}]`,"duplicate.effect-id",r)});let w=new Set;t.outcomes.forEach((I,O)=>{Ma(w,I.id,`outcomes[${O}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((I,O)=>{I.output.effectRefs?.forEach((j,N)=>{h.has(j.effect)||r.push({severity:"error",path:`outcomes[${O}].output.effectRefs[${N}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${I.id}' verweist auf den unbekannten Effekt '${j.effect}'.`,en:`Outcome '${I.id}' references unknown effect '${j.effect}'.`}})})}),t.outcomes.forEach((I,O)=>{I.output.fields?.forEach((j,N)=>{aq(t,j.path)||r.push({severity:"error",path:`outcomes[${O}].output.fields[${N}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${I.id}' verweist auf das unbekannte Feld '${j.path}'.`,en:`Outcome '${I.id}' references unknown field '${j.path}'.`}})})});let k=new Set;for(let I of La(t.sections))for(let O of I.section.repeated??[])k.add(`${O.key}.count`);for(let I of k)(a.has(I)||d.has(I))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${I}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${I}' 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:n.stageKeys};r.push(...NN(e)),r.push(...tq(e,t,n.visibleToKeys)),r.push(...gC(e)),r.push(...ON(e,n.stageKeys));for(let I of La(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.visibleIf&&(Rr(O.visibleIf,`${j}.visibleIf`,y,!1,r),qa(O.visibleIf,`${j}.visibleIf`,c,r)),O.fields.forEach((N,z)=>Ix(N,`${j}.fields[${z}]`,y,!1,c,r)),O.groups?.forEach((N,z)=>{N.visibleIf&&(Rr(N.visibleIf,`${j}.groups[${z}].visibleIf`,y,!1,r),qa(N.visibleIf,`${j}.groups[${z}].visibleIf`,c,r)),N.fields.forEach((le,ce)=>Ix(le,`${j}.groups[${z}].fields[${ce}]`,y,!1,c,r))}),O.repeated?.forEach((N,z)=>{N.itemVisibleIf&&(Rr(N.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,y,!0,r),qa(N.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,c,r)),N.itemTemplate.forEach((le,ce)=>Ix(le,`${j}.repeated[${z}].itemTemplate[${ce}]`,y,!0,c,r)),N.effects?.forEach((le,ce)=>{le.when&&Rr(le.when,`${j}.repeated[${z}].effects[${ce}].when`,y,!0,r)})}),O.computed?.forEach((N,z)=>Rr(N.expression,`${j}.computed[${z}].expression`,y,!1,r))}t.effects.forEach((I,O)=>{I.when&&Rr(I.when,`effects[${O}].when`,y,!1,r)}),t.outcomes.forEach((I,O)=>{Rr(I.when,`outcomes[${O}].when`,y,!1,r)});let b=new Set(t.outcomes.map(I=>I.id));function E(I,O){I.requiredFor&&I.requiredFor.forEach((j,N)=>{b.has(j)||r.push({severity:"error",path:`${O}.requiredFor[${N}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${I.key}": requiredFor verweist auf das unbekannte Ergebnis "${j}"`,en:`field "${I.key}": requiredFor references unknown outcome "${j}"`}})})}s(E,"checkRequiredFor");for(let I of La(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.fields.forEach((N,z)=>E(N,`${j}.fields[${z}]`)),O.groups?.forEach((N,z)=>{N.fields.forEach((le,ce)=>E(le,`${j}.groups[${z}].fields[${ce}]`))}),O.repeated?.forEach((N,z)=>{N.itemTemplate.forEach((le,ce)=>E(le,`${j}.repeated[${z}].itemTemplate[${ce}]`))})}function T(I,O){let j=s((N,z)=>{let le=(N.type==="docRef"?N.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!Rx.includes(Ee));le.length>0&&r.push({severity:"error",path:z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${N.key}' erlaubt ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Rx.join(", ")}).`,en:`Field '${N.key}' allows ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Rx.join(", ")}).`}});let ce=N.type==="docRef"?N.docRefConstraints?.minFiles:void 0;if(ce!==void 0){let Ee=N.docRefConstraints?.multiple===!0,mn=typeof ce=="number"&&Number.isInteger(ce)&&ce>=2;(!Ee||!mn)&&r.push({severity:"error",path:z,code:"config.docref-min-files",message:Ee?{de:`Feld '${N.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(ce)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${N.key}' sets docRefConstraints.minFiles to ${JSON.stringify(ce)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${N.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${N.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}N.multiple===!0&&N.type!=="enum"&&r.push({severity:"error",path:z,code:"config.multiple-non-enum",message:{de:`Feld '${N.key}' setzt multiple: true, hat aber den Typ '${N.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(N.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${N.key}' sets multiple: true but is type '${N.type}' \u2014 only 'enum' supports multi-select.`+(N.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),N.presentation==="yesNo"&&N.type!=="boolean"&&r.push({severity:"error",path:z,code:"config.yesno-non-boolean",message:{de:`Feld '${N.key}' setzt presentation: 'yesNo', hat aber den Typ '${N.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${N.key}' sets presentation: 'yesNo' but is type '${N.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),N.presentation==="yesNo"&&N.defaultValue!=null&&r.push({severity:"error",path:z,code:"config.yesno-default",message:{de:`Feld '${N.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 '${N.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...G8(N,z)),typeof N.minSelections=="number"&&typeof N.maxSelections=="number"&&N.minSelections>N.maxSelections&&r.push({severity:"error",path:z,code:"config.min-gt-max-selections",message:{de:`Feld '${N.key}' hat minSelections (${N.minSelections}) > maxSelections (${N.maxSelections}).`,en:`Field '${N.key}' has minSelections (${N.minSelections}) > maxSelections (${N.maxSelections}).`}}),r.push(...z8(N,z));let De=N.enumRef;De!==void 0&&r.push({severity:"error",path:`${z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${N.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 '${N.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(N.enumOptions??[]).forEach((Ee,mn)=>{let Qe=cq(Ee);Qe!==null&&r.push({severity:"error",path:`${z}.enumOptions[${mn}]`,code:"config.enum-option-value",message:{de:Qe==="empty"?`Feld '${N.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 '${N.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Qe==="empty"?`Field '${N.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 '${N.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(N.attachments??[]).forEach((Ee,mn)=>{if("storageId"in Ee){r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${N.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 '${N.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 Qe=Ee.fileKey!==void 0&&Ee.fileKey!=="",Sn=Ee.url!==void 0&&Ee.url!=="";Qe===Sn&&r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${N.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Qe&&Sn?"beide":"keines"}).`,en:`Field '${N.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Qe&&Sn?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${N.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${N.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");I.fields.forEach((N,z)=>j(N,`${O}.fields[${z}]`)),I.groups?.forEach((N,z)=>{N.fields.forEach((le,ce)=>j(le,`${O}.groups[${z}].fields[${ce}]`))}),I.repeated?.forEach((N,z)=>{N.itemTemplate.forEach((le,ce)=>{let De=`${O}.repeated[${z}].itemTemplate[${ce}]`;j(le,De),le.type==="consent"&&r.push({severity:"error",path:De,code:"config.consent-in-repeated",message:{de:`Feld '${le.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${le.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),I.subsections?.forEach((N,z)=>T(N,`${O}.subsections[${z}]`))}s(T,"visitFieldConfig"),e.sections.forEach((I,O)=>T(I,`sections[${O}]`)),e.effects.forEach((I,O)=>{if(I.kind==="person"){r.push(...hq(I,e.effects,`effects[${O}]`,j=>l.has(j)));return}I.kind==="organization"&&I.nameFrom?.forEach((j,N)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nameFrom[${N}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${I.id}': nameFrom verweist auf das unbekannte Feld '${j}'.`,en:`Effect '${I.id}' nameFrom references unknown field '${j}'.`}})})});let R=s((I,O)=>{if(I.kind!=="person"&&I.kind!=="organization")return;let j=I.display;if(!j){r.push({severity:"error",path:`${O}.display`,code:"display.missing",message:{de:`Effekt '${I.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${I.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}lq(j.icon)||r.push({severity:"error",path:`${O}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${I.id}': display.icon '${j.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${I.id}' display.icon '${j.icon}' is not a known bucket icon.`}}),dq(j.color)||r.push({severity:"error",path:`${O}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${I.id}': display.color '${j.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${I.id}' display.color '${j.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((I,O)=>R(I,`effects[${O}]`));let D=new Set,L=s(I=>{I.kind==="person"?D.add(I.bucket):I.kind==="organization"&&D.add(I.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let _=new Set,v=s(I=>{for(let O of I)O.repeated?.forEach(j=>j.effects?.forEach(N=>L(N))),v(O.subsections??[])},"collectRepeatedBuckets");v(e.sections);let P=s((I,O)=>{D.size!==0&&I.forEach((j,N)=>{j.bucket===void 0||D.has(j.bucket)||r.push({severity:"error",path:`${O}[${N}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${j.key}' geh\xF6rt zum Bucket '${j.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${j.key}' belongs to bucket '${j.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),A=s((I,O)=>{if(_.has(I))return;_.add(I);let j=`sections[${O.join(".")}]`;P(I.fields,`${j}.fields`),I.groups?.forEach((N,z)=>P(N.fields,`${j}.groups[${z}].fields`)),I.repeated?.forEach((N,z)=>P(N.itemTemplate,`${j}.repeated[${z}].itemTemplate`)),I.subsections?.forEach((N,z)=>A(N,[...O,z]))},"visitBucketSection");e.sections.forEach((I,O)=>A(I,[O]));let M=e.effects.flatMap((I,O)=>I.kind==="person"&&I.subject===!0?[{e:I,i:O}]:[]);M.length>1&&M.slice(1).forEach(({e:I,i:O})=>{r.push({severity:"error",path:`effects[${O}].subject`,code:"subject.duplicate",message:{de:`Effekt '${I.id}' deklariert subject:true, aber '${M[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${I.id}' declares subject:true, but '${M[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((I,O)=>{if(!(I.kind!=="person"||I.nationalityFrom===void 0)){if(I.subject!==!0){r.push({severity:"error",path:`effects[${O}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${I.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 '${I.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(I.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${O}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${I.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${I.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}I.nationalityFrom.forEach((j,N)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nationalityFrom[${N}]`,code:"nationality.unknown-field",message:{de:`Effekt '${I.id}': nationalityFrom verweist auf das unbekannte Feld '${j}'.`,en:`Effect '${I.id}' nationalityFrom references unknown field '${j}'.`}})})}});let U=e.effects.flatMap((I,O)=>I.kind==="person"&&I.contractParty!==void 0?[{e:I,i:O,decl:I.contractParty}]:[]);if(U.length>0){let I=new Map;U.forEach(({e:j,i:N})=>{let z=I.get(j.bucket);if(z===void 0){I.set(j.bucket,j.id);return}r.push({severity:"error",path:`effects[${N}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${j.id}' deklariert eine Vertragspartei auf Bucket '${j.bucket}', aber '${z}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${j.id}' declares a contract party on bucket '${j.bucket}', but '${z}' already does. A bucket is at most one contract party.`}})});let O=U.filter(({decl:j})=>j.role==="beneficiary");O.slice(1).forEach(({e:j,i:N})=>{r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${j.id}' deklariert contractParty.role 'beneficiary', aber '${O[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${j.id}' declares contractParty.role 'beneficiary', but '${O[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),O.forEach(({e:j,i:N})=>{j.subject!==!0&&r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${j.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 '${j.id}' setzen.`,en:`Effect '${j.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 '${j.id}'.`}})}),M.forEach(({e:j,i:N})=>{let z=j.contractParty?.role;z!==void 0&&z!=="beneficiary"&&r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${j.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${z}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${j.id}' is the application subject but declares contractParty.role '${z}'. The application subject is the contract beneficiary.`}})}),U.some(({decl:j})=>j.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((I,O)=>{I.kind==="fieldMap"&&I.mappings.forEach((j,N)=>{a.has(j.from)||r.push({severity:"error",path:`effects[${O}].mappings[${N}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${I.id}': fieldMap from '${j.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${I.id}' fieldMap from '${j.from}' references unknown field.`}})})});for(let[I,O]of u){if(!O.sameAs)continue;let j=`fields[${I}].sameAs`,N=u.get(O.sameAs.source);N===void 0||O.sameAs.source===I?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:O.sameAs.source===I?`Feld '${I}': sameAs.source verweist auf sich selbst.`:`Feld '${I}': sameAs.source verweist auf das unbekannte Feld '${O.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:O.sameAs.source===I?`Field '${I}' sameAs.source references itself.`:`Field '${I}' sameAs.source references unknown field '${O.sameAs.source}' (must be a top-level or group field).`}}):N.type!==O.type?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${I}' (${O.type}): sameAs.source '${O.sameAs.source}' hat einen anderen Typ (${N.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${I}' (${O.type}) sameAs.source '${O.sameAs.source}' has a different type (${N.type}) \u2014 the mirror must be shape-identical.`}}):N.sameAs&&r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${I}': sameAs.source '${O.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${I}' sameAs.source '${O.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let z=u.get(O.sameAs.toggle);(z===void 0||z.type!=="boolean")&&r.push({severity:"error",path:`${j}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:z===void 0?`Feld '${I}': sameAs.toggle verweist auf das unbekannte Feld '${O.sameAs.toggle}'.`:`Feld '${I}': sameAs.toggle '${O.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${z.type}').`,en:z===void 0?`Field '${I}' sameAs.toggle references unknown field '${O.sameAs.toggle}'.`:`Field '${I}' sameAs.toggle '${O.sameAs.toggle}' must be type 'boolean' (got '${z.type}').`}}),O.required===!0&&r.push({severity:"error",path:`fields[${I}].required`,code:"config.sameas-static-required",message:{de:`Feld '${I}' 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: "${O.sameAs.toggle} != true" verwenden.`,en:`Field '${I}' 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: "${O.sameAs.toggle} != true".`}})}{let I=new Map;e.effects.forEach(O=>I.set(O.id,O.kind)),e.effects.forEach((O,j)=>{if(O.kind!=="shareValue")return;[["from",O.from],["to",O.to]].forEach(([le,ce])=>{let De=I.get(ce.slice(1));De!==void 0&&De!=="person"&&De!=="organization"&&r.push({severity:"error",path:`effects[${j}].${le}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${O.id}': shareValue ${le} '${ce}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${De}').`,en:`Effect '${O.id}' shareValue ${le} '${ce}' must reference a person/organization effect (got '${De}').`}})});let N=O.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===N&&le.mappings.some(ce=>ce.to===O.field)||le.kind==="shareValue"&&le.id!==O.id&&le.to.slice(1)===N&&le.field===O.field)||r.push({severity:"error",path:`effects[${j}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${O.id}' teilt das Feld '${O.field}' aus '${O.from}', aber kein fieldMap mit Ziel '${O.from}' bildet auf '${O.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${O.id}' shares field '${O.field}' from '${O.from}', but no fieldMap targeting '${O.from}' maps to '${O.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((I,O)=>{I.kind==="person"&&I.bucket.includes(Qr)&&r.push({severity:"error",path:`effects[${O}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': bucket '${I.bucket}' darf '${Qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' bucket '${I.bucket}' must not contain '${Qr}' (reserved for the per-row namespace).`}}),I.kind==="organization"&&I.orgKind.includes(Qr)&&r.push({severity:"error",path:`effects[${O}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': orgKind '${I.orgKind}' darf '${Qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' orgKind '${I.orgKind}' must not contain '${Qr}' (reserved for the per-row namespace).`}})});let oe=new Set;function Q(I,O){I.repeated?.forEach((j,N)=>{let z=j.effects??[];if(z.length>0){let le=`${O}.repeated[${N}]`,ce=new Set(z.map(se=>se.id)),De=new Set(j.itemTemplate.map(se=>se.key)),Ee=(j.uniqueBy?.length??0)>0,mn=s(se=>se.startsWith("$item.")?De.has(se.slice(6)):l.has(se),"resolvesName"),Qe=s(se=>se.startsWith("$item.")?De.has(se.slice(6)):a.has(se),"resolvesFrom"),Sn=s(se=>{let jn=se.slice(1);return ce.has(jn)||h.has(jn)},"resolvesRef");z.forEach((se,jn)=>{let hn=`${le}.effects[${jn}]`;if(h.has(se.id)||oe.has(se.id)?r.push({severity:"error",path:hn,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${se.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${se.id}' is declared more than once.`}}):oe.add(se.id),se.kind==="person"||se.kind==="organization"){R(se,hn),se.kind==="person"&&se.subject===!0&&r.push({severity:"error",path:`${hn}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${se.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 '${se.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.`}}),se.kind==="person"&&se.nationalityFrom!==void 0&&r.push({severity:"error",path:`${hn}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${se.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${se.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),se.kind==="person"&&se.contractParty!==void 0&&r.push({severity:"error",path:`${hn}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${se.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 '${se.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:le,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${j.key}' hat einen Parteien erzeugenden Effekt '${se.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${j.key}' has a party-creating effect '${se.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Fe=se.kind==="person"?se.bucket:se.orgKind;Fe.includes(Qr)&&r.push({severity:"error",path:`${hn}.${se.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${se.id}' der Wiederholung: ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' darf '${Qr}' nicht enthalten.`,en:`Repeated effect '${se.id}' ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${Qr}'.`}}),se.kind==="person"&&r.push(...hq(se,z,hn,mn)),se.kind==="organization"&&se.nameFrom?.forEach((Be,Pt)=>{mn(Be)||r.push({severity:"error",path:`${hn}.nameFrom[${Pt}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${se.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${se.id}' nameFrom references unknown field '${Be}'.`}})}),se.identity?.strategy==="keyed"&&se.identity.keyFrom.forEach((Be,Pt)=>{Qe(Be)||r.push({severity:"error",path:`${hn}.identity.keyFrom[${Pt}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${se.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${se.id}' identity.keyFrom references unknown field '${Be}'.`}})})}else if(se.kind==="relationship"){if([["from",se.from],["to",se.to]].forEach(([Fe,Be])=>{Sn(Be)||r.push({severity:"error",path:`${hn}.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${se.id}' der Wiederholung: ${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${se.id}' ${Fe} references unknown effect '${Be}'.`}})}),se.meta)for(let[Fe,Be]of Object.entries(se.meta))typeof Be=="string"&&Be.startsWith("$")&&!Sn(Be)&&r.push({severity:"error",path:`${hn}.meta.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${se.id}' der Wiederholung: meta.${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${se.id}' meta.${Fe} references unknown effect '${Be}'.`}})}else se.kind==="fieldMap"?(Sn(se.target)||r.push({severity:"error",path:`${hn}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${se.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${se.target}'.`,en:`Repeated fieldMap '${se.id}' target references unknown effect '${se.target}'.`}}),se.mappings.forEach((Fe,Be)=>{Qe(Fe.from)||r.push({severity:"error",path:`${hn}.mappings[${Be}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${se.id}' der Wiederholung: from '${Fe.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${se.id}' from '${Fe.from}' references unknown field.`}})})):se.kind==="shareValue"&&r.push({severity:"error",path:hn,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${se.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${se.id}': shareValue is not supported inside repeated row effects.`}})})}}),I.subsections?.forEach((j,N)=>Q(j,`${O}.subsections[${N}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((I,O)=>Q(I,`sections[${O}]`));let re=HM(t.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(...U8(e)),r}s(gq,"validateForm");function U8(e){let n={...e,effects:e.effects.map(yq),sections:e.sections.map(wq),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return qp(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:sk(t)}))}s(U8,"missingTranslationIssues");function yq(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(yq,"withoutSubjectFlag");function wq(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(yq)})),subsections:e.subsections?.map(wq)}}s(wq,"withoutRowSubjectFlags");function uq(e,n){let t=e.reviewRequired;return t===void 0||t===!0?[]:[{severity:"error",path:n,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(t)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(t)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(uq,"reviewRequiredShapeIssues");function fq(e,n){if(!e.export)return[];let t=[];return e.type==="docRef"&&t.push({severity:"error",path:n,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&&t.push({severity:"error",path:n,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.`}}),t}s(fq,"exportGateIssues");function Ma(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${pq(r,"de")} '${n}'`,en:`Duplicate ${pq(r,"en")}: '${n}'`}}):e.add(n)}s(Ma,"reportIfDup");function pq(e,n){let t=s((r,i)=>n==="de"?r:i,"label");switch(e){case"duplicate.section-id":return t("Abschnitts-ID","section id");case"duplicate.field-key":return t("Feldschl\xFCssel","field key");case"duplicate.effect-id":return t("Effekt-ID","effect id");case"duplicate.outcome-id":return t("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return t("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s(pq,"labelForCode");function Ix(e,n,t,r,i,o){e.visibleIf&&(Rr(e.visibleIf,`${n}.visibleIf`,t,r,o),qa(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(Rr(e.requiredIf,`${n}.requiredIf`,t,r,o),qa(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(Rr(e.disabledIf,`${n}.disabledIf`,t,r,o),qa(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&Rr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s(Ix,"checkFieldAsts");function Ox(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Ox,"gatingMeta");function qa(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(mq(o.left,o.right,o.op,n,t,r),mq(o.right,o.left,o.op,n,t,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(qa,"checkGatingExpr");function mq(e,n,t,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&n.kind==="bool"&&n.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||n.kind!=="null"&&n.kind==="bool"&&(a.isYesNo&&t==="=="||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 '${t}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${t} ${n.value}' ${t==="=="?"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 '${t}'. In three-valued logic, 'undefined ${t} ${n.value}' is ${t==="=="?"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(mq,"inspectEqualityOperand");function Rr(e,n,t,r,i){i.push(...PN(e,t.declaredContext,n)),i.push(...Dp(e,t.stageKeys,n));for(let o of _n(e))t.known.has(o)||tk(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:n,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(Rr,"checkAst");function hq(e,n,t,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${t}.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 ${$r.firstName} / ${$r.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${$r.firstName} / ${$r.lastName}. Remove nameFrom.`}});let o=iq(e.id,n);sq(o)||i.push({severity:"error",path:t,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${$r.firstName} oder ${$r.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${$r.firstName} or ${$r.lastName} \u2014 the person would get no name.`}});for(let a of oq(o))r(a)||i.push({severity:"error",path:t,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(hq,"personNameIssues");function G8(e,n){let t=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&t.push({severity:"error",path:n,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&&t.push({severity:"error",path:n,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||t.push({severity:"error",path:n,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"&&t.push({severity:"warning",path:n,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'.`}}),t}s(G8,"consentConfigIssues");function z8(e,n){let t=e.exclusiveOptions;if(t===void 0)return[];let r=s((a,l)=>[{severity:"error",path:n,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(t)||t.length===0||t.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(t)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(t)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=t.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(t).size!==t.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(z8,"exclusiveOptionIssues");var W8="blocked";function kq(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=wn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(Y8(i))return r.id===W8?null:r.id}return null}s(kq,"resolveActiveOutcome");function Y8(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(Y8,"truthy");function bq(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(bq,"isScalar");function H8(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(bq(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))bq(a)&&(n[`${r}.${o}`]=a)}J8(e,n,t)}s(H8,"mergeRecord");function J8(e,n,t){let r=new Set(t);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);no(a).test(i)&&r.add(a)}for(let i of r){let o=Tx(e,i),a=0;for(let l=0;l<o;l++)QM(e,i,l)&&a++;n[`${i}.count`]=a}}s(J8,"mergeRepeatedCounts");function vq(e,n,t){let r={...t};return H8(e,r,n),r}s(vq,"flattenValues");function _x(e,n,t){return{code:e,fieldKey:n,text:t}}s(_x,"submitIssue");function xq(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(xq,"truthyEval");function Sq(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 n=e;if("storageId"in n)return!(typeof n.storageId=="string"&&n.storageId.trim()!=="");let t=n;return!t.street?.trim()||!t.hausnr?.trim()||!t.plz?.trim()||!t.ort?.trim()||!t.land?.trim()}return!1}s(Sq,"isEmptyValue");function Q8(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=xq(wn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(Q8,"fieldIsLiveRequired");function Z8(e,n,t){return Aq(e,n,t).evalCtx}s(Z8,"buildSubmitEvalContext");function Aq(e,n,t){let r=X8(e),i=Object.keys(n).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[w,k]of Object.entries(n))(r(w)===null||o.has(w))&&(l[w]=k);let d=Eq(e,l,t),c=new Set,u=new Set;$q(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]=n[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(Aq,"splitWithContext");function X8(e){let n=new Map,t=[];for(let r of ph(e.sections)){for(let i of r.fields)n.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)n.set(o.key,o);for(let i of r.repeated??[])t.push({key:i.key,pattern:no(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=n.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of t){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(X8,"fieldOwnership");function Eq(e,n,t){let r=[];for(let o of ph(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=vq(n,r,t);for(let o of ph(e.sections))for(let a of o.computed??[])try{i[a.key]=wn(a.expression,{values:i})}catch{}return i}s(Eq,"rawEvalContext");function Tq(e,n,t){let{values:r,defaulted:i}=eZ(e,n,t),o=Aq(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(Tq,"splitDraftValues");function eZ(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of ph(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||n[d.key]!=null||r?.(d.key))continue;a??=Eq(e,n,t);let c;try{c=wn(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(eZ,"applyFieldDefaults");function ph(e){let n=[],t=s(r=>{n.push(r);for(let i of r.subsections??[])t(i)},"walk");for(let r of e)t(r);return n}s(ph,"walkSectionsDeep");function nZ(e,n,t,r=!1){if(Sq(n))return null;let i=t.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,n,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(nZ,"fieldFormatIssue");function tZ(e,n){return Sq(n)||e.type==="consent"&&n!==!0}s(tZ,"isUnanswered");function fh(e,n){if(!e)return!0;try{return xq(wn(e,{values:n}))}catch{return!1}}s(fh,"isVisibleUnder");function $q(e,n,t,r){let i=s(o=>{if(fh(o.visibleIf,n)){for(let a of o.fields)fh(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(fh(a.visibleIf,n))for(let l of a.fields)fh(l.visibleIf,n)&&t(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($q,"forEachVisibleField");function Rq(e,n,t,r={}){let i=Z8(e,n,t),o=[],a=kq(e,i);a===null&&r.requireOutcome!==!1&&o.push(_x("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 $q(e,i,d=>{let c=n[d.key];if(tZ(d,c)){!l.has(d.type)&&Q8(d,i,a)&&o.push(_x("required",d.key,Rl([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=nZ(d,c,r.registry,r.testMode===!0);u!==null&&o.push(_x("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(Rq,"checkSubmittable");function Iq(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=fa(e),r=[];for(let i of n){let o=i.prefill??{};if(!$N(e,i.env))continue;let a=IN(e,i.env),{visible:l}=Tq(t,o,a),d=Rq(t,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:Rl([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(Iq,"validateScenarios");function mh(e){return e.filter(n=>(n.severity??"error")==="error")}s(mh,"blockingIssues");function hh(e,n={}){return[...gq(e,n),...Iq(e)]}s(hh,"runFormValidators");function gh(e){return mh(e)}s(gh,"blockingFormErrors");function Oq(e,n,t){return UC(e,n,t)}s(Oq,"runWorkflowValidators");function _q(e){return mh(e)}s(_q,"blockingWorkflowErrors");var rZ=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var Pq={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","reads","requiresOneOf","view"]},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"]}},yt={id:m.string(),label:Ji,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())},iZ=m.object({...yt,type:m.literal("join")}),oZ=m.object({...yt,type:m.literal("end")}),sZ=m.object({...yt,type:m.literal("eventTrigger")}),aZ=m.object({...yt,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),lZ=m.object({...yt,type:m.literal("roleAssign")}),dZ=m.object({...yt,type:m.literal("setFlag")}),cZ=m.object({...yt,type:m.literal("if"),condition:m.optional(m.any())}),uZ=m.object({...yt,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),fZ=m.object({...yt,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),pZ=m.object({...yt,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),view:m.optional(m.any()),formView:m.optional(m.any())}),mZ=m.object({...yt,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),hZ=m.object({...yt,type:m.literal("waitlist")}),gZ=m.object({...yt,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),yZ=m.object({...yt,type:m.literal("collectPayment")}),wZ=m.object({...yt,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())}),xqe=m.union(iZ,oZ,sZ,aZ,lZ,dZ,cZ,uZ,fZ,pZ,mZ,hZ,gZ,yZ,wZ);function Nq(e){let n=[];return e.forEach((t,r)=>{if(t===null||typeof t!="object"||Array.isArray(t)){n.push(`graph.nodes[${r}]: a node must be an object`);return}let i=t,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&n.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in Pq)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=Pq[a],d=new Set(["id","type","label",...rZ,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||n.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),n}s(Nq,"workflowNodeEnvelopeIssues");var Cq=s(e=>e,"asEffectId"),to=s(e=>e,"asOutcomeId"),Ka=s(e=>e,"asSectionId"),ot=s(e=>e,"asFieldKey");var Ir=["string","boolean","consent","date","enum","email","tel","address","docRef"],ec=["person","organization","relationship","fieldMap"],ro=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],ja=["fresh","keyed","manual"];function is(e,n,t,r){if(e===void 0||e===""){if(n!==void 0&&n!=="")throw new Error(`${t}: ${r}-en needs ${r} too`);return}return dn(e,n,t,r)}s(is,"optionalLocalizedText");function Hn(e,n){if(!(e===void 0||e===""))try{On(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(Hn,"assertExpression");function nc(e){return Object.keys(e.smartforms??{})}s(nc,"carriedFormSlugs");function Px(e){let t=e.workflow?.graph?.nodes??[],r=[];for(let i of t){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(Px,"boundFormSlugs");function yh(e,n){let t=nc(e);if(n){if(!t.includes(n))throw new Error(`offer form: no smartform "${n}" in this bundle (have: ${t.join(", ")||"none"})`);return n}if(t.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(t.length>1)throw new Error(`offer form: bundle carries ${t.length} smartforms \u2014 pass --form <key> (one of: ${t.join(", ")})`);return t[0]}s(yh,"resolveFormSlug");function wh(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(wh,"getForm");function Ut(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(Ut,"walkSections");function lr(e,n){return Ut(e).find(t=>t.id===n)}s(lr,"findSection");function os(e,n){for(let t of Ut(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(os,"findField");function ss(e){let n=new Set;for(let t of Ut(e))t.fields.forEach(r=>n.add(r.key)),t.groups?.forEach(r=>r.fields.forEach(i=>n.add(i.key))),t.repeated?.forEach(r=>r.itemTemplate.forEach(i=>n.add(i.key))),t.computed?.forEach(r=>n.add(r.key));return n}s(ss,"allFieldKeys");function kZ(e){let n=dn(e.label,e.labelEn,"offer form add"),t={id:Ka("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:to("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(kZ,"buildSkeletonSmartForm");function kh(e,n){let{key:t,label:r}=n;if(nc(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=kZ({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(kh,"addForm");function Dq(e,n){if(!nc(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(Px(e).includes(n))throw new Error(`offer form rm: smartform "${n}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[n],e.index.smartforms&&delete e.index.smartforms[n],n}s(Dq,"removeForm");function Fq(e,n){let t=wh(e,n.slug);if(n.label===void 0&&n.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(n.label==="")throw new Error("offer form set: --label cannot be empty");bn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(Fq,"setForm");function Lq(e,n){let t=e.workflow?.graph?.nodes;if(!Array.isArray(t))throw new Error(`${n}: the bundle carries no workflow graph (workflow.json)`);return t}s(Lq,"nodesOf");function Mq(e,n,t){let r=Lq(e,t),i=r.find(o=>o.id===n);if(i===void 0)throw new Error(`${t}: no node "${n}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(Mq,"nodeOf");function qq(e){return e.flatMap(n=>{if(n.type!=="form"||At(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s(qq,"creatingFormNodes");function Kq(e){return gh(hh(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(Kq,"formErrors");function bh(e){let n="offer workflow restamp-exports",t=Lq(e,n),r=[];for(let{node:i,slug:o}of qq(t)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${n}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=Kq(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11361
+ `)}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}},Pv=class extends C{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=$.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 (${Ye.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 n=K5(this.slot,this.slotFile);if(Object.keys(n).length===0)throw new Error("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let t=await this.caller(),r=await t.mutation(x.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(t),templateId:this.templateId,locale:Fv(this.locale,"letters set"),slots:n});return this.print({templateId:this.templateId,submitted:Object.keys(n),...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}},Nv=class extends C{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=$.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 (${Ye.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 n=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&n.length>0)throw new Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&n.length===0)throw new Error("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let t=await this.caller(),r=await t.mutation(x.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(t),templateId:this.templateId,locale:Fv(this.locale,"letters reset"),...this.all?{}:{slotKeys:n}});return this.print({templateId:this.templateId,reset:this.all?"all":n.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},Hd=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function Vm(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":Hd(n[r],""),...t===null?{}:{platform:Hd(t[r],"")}}))}s(Vm,"chromeTextRows");var Cv=class extends C{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=$.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 n=await this.caller(),t=await n.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(n)});return this.print(t,r=>[...Vm("greeting",r.greeting,r.defaults.greeting),...Vm("closing",r.closing,r.defaults.closing),{field:"senderName",school:Hd(r.senderName,"\u2014 (platform)"),platform:Hd(r.defaults.senderName,"")}],["field","school","platform"]),0}},Dv=class extends C{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=$.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 n=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"),t=n("greeting",this.greetingDe,this.greetingEn),r=n("closing",this.closingDe,this.closingEn);if(t===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,...t!==void 0?{greeting:t}:{},...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=>[...Vm("greeting",l.greeting,null),...Vm("closing",l.closing,null),{field:"senderName",school:Hd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},QL=[Ev,Tv,$v,Rv,Iv,Ov,_v,Pv,Nv,Cv,Dv];var V5={capacity:null,isOpen:!1},B5={capacity:null,isOpen:!0};function U5(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(U5,"isCapacity");function Bm(e,n){let t=[],r=n===void 0?void 0:new Set(n);return e.forEach((i,o)=>{if(i.capacities===void 0)return;let a=`program.runs[${o}] ("${i.key}")`;if(i.isOpen!==void 0&&t.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)){t.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)&&t.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"){t.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&t.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!U5(u.capacity))&&t.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),t}s(Bm,"capacitySpecIssues");function XL(e,n,t={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(t.stageKeys),a=new Set(t.runKeys),l=new Map(e.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of n){if(c.capacities===void 0)continue;let u=r===null?void 0:e.runs.find(p=>p.key===Qt(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,b=y!==void 0?{capacity:y.capacity,isOpen:y.isOpen}:u===void 0?V5:B5;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:b,to:k})}}return d}s(XL,"planRunCapacities");function ZL(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(ZL,"describeCell");function Um(e){return`~cap ${e.run}\xD7${e.stageKey} ${ZL(e.from)} \u2192 ${ZL(e.to)}`}s(Um,"describeCapacityStep");function e0(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(e0,"assertBackendHasStageKeys");async function Lv(e,n,t,r){let i=await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,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}));e0(i);let a=Af(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:n,offerKey:t,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(Lv,"planStages");async function Gm(e,n,t,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let o=t===null?{programKey:null,stages:[],runs:[],runStages:[]}:await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t});e0(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 XL(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===Qt(d,c)))})}s(Gm,"planCapacities");async function G5(e,n,t,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let o=await e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0}),a=o.programKey;if(a===null)return;let l=i.filter(d=>o.runs.some(c=>c.key===Qt(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(G5,"assertNoArchivedRunKey");var Mv={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...Sf(o??[]),...xf(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(y=>y.message.de).join("; ")}`);let l=Bm(t.program?.runs??[],o?.map(y=>y.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await G5(e,i,n,t);let d=await Gm(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=z5(t);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:n,unitId:p.unitId,...t.program?.key!==void 0?{programKey:t.program.key}:{}})),h.push(`unit=${u}`),o!==void 0)if(r.dryRun){let y=await Lv(e,i,n,o);h.push(...y.map(Ef))}else{let y=await e.mutation(x.programAdmin.reconcileProgramStages,{client:i,offerKey:n,stages:o.map(b=>({key:b.key,name:b.name,...b.gradeLevel!==void 0?{gradeLevel:b.gradeLevel}:{}}))});h.push(...y.steps,...y.warnings.map(b=>`warning ${b}`))}let w=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let y of t.program?.runs??[]){let b=w.programKey===null?void 0:w.runs.find(E=>E.key===Qt(w.programKey,y.key));if(b!==void 0){Is(b.name,y.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:y.name}),h.push(`~run ${y.key} ("${Ce(b.name)}" \u2192 "${Ce(y.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,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} (${Ce(y.name)})`)}let k=r.dryRun?d:await Gm(e,i,n,t);if(!r.dryRun&&k.length>0){let y=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=y.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let E of k){let T=y.runs.find(D=>D.key===Qt(b,E.run))?.runId,R=y.stages.find(D=>Kr(b,D.key)===E.stageKey)?.stageId;if(T===void 0||R===void 0)throw new Error(`offer[admission]: cell ${E.run}\xD7${E.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:n,runId:T,stageId:R,capacity:E.to.capacity,isOpen:E.to.isOpen})}}return h.push(...k.map(Um)),h.join(", ")}};function z5(e){let n=e.program?.unitKey,t=e.links?.unitKey;if(n!==void 0&&t!==void 0&&n!==t)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${n}" and links.unitKey "${t}"; keep one`);return n??t}s(z5,"bundleUnitKey");var n0={role:"control",effect:"pure",cardinality:"N-to-1"};var zm=["add","remove","replace"];function t0(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(t0,"roleAssignLiteral");var r0={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,n,t)=>{let r=[],i=t0(e,"roleKey")?.trim()??"",o=t0(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"}):t?.roleKeys!==void 0&&!t.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: ${[...t.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: ${[...t.roleKeys].sort().join(", ")}.`},severity:"error"}):t?.assignableRoleKeys!==void 0&&!t.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: ${[...t.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: ${[...t.assignableRoleKeys].sort().join(", ")}.`},severity:"error"}),zm.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 ${zm.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${zm.join(" | ")}.`},severity:"error"}),r},"validate")};var W5=["event","effect","outcomes"],qv=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),i0={outcomes:[{id:vr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of W5)i in r&&t.push(qv(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${vr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${vr}" itself.`));return nr(n.nodes).some(i=>i.target===e.id)&&t.push(qv(`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?.[vr]===void 0&&t.push(qv(`nodes.${e.id}.next.${vr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${vr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${vr}" nowhere.`)),t},"validate")};var Y5="submit",o0=[{id:Y5,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function s0(e){return e==="draft"}s(s0,"isWritableSmartFormState");var Kv=["draft","committed"],__e=Kv.filter(e=>s0(e));async function a0(e,n,t){let r=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",n).eq("formNodeId",t)).take(2);return r.length>1&&F(`application ${n}: two form instances for node "${t}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r[0]??null}s(a0,"getSmartFormInstance");var l0="form:fill",jv="request:collectPayment",Vv="request:collectPaymentSeparate",ki="confirmPayment";var H5={key:l0,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},d0={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},c0={[PI]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:d0,external:en(te("Entwurf","Draft"),"neutral",te("Bewerbung fortsetzen","Continue application"),te("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."),te("Bewerbung fortsetzen","Continue application"),"continue-form")},[Rf]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:d0,external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung ist eingereicht","Your application has been submitted"),te("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."))}},u0={role:"user-action",effect:"side-effect",progressDefaults:c0,progressEvents:qn(c0),actions:s(()=>o0,"actions"),workItemTemplates:s(()=>[H5],"workItemTemplates"),states:Kv,currentState:s(async(e,n)=>{let t=await a0(e,n.applicationId,n.node.id);return t===null?"draft":t.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=>At(e)?[]:[{id:If,label:{de:"Formular abgesendet",en:"Form submitted"},audience:"external",args:[{key:"applicationId",type:"string",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[],t=e.inputs?.smartForm,r=t?.kind==="literal"&&typeof t.value=="string"&&t.value.length>0,i=e.adoptForm!==void 0;return r&&i?n.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&&n.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"}),n},"validate")};var f0={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Pn.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Pn.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Pn.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:ZO(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[Pn.flagKey]?.kind==="literal"&&Jf(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Pn.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?.[Pn.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Pn.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"}),n},"validate")};var J5="true",Q5="false",Bv=[{id:J5,label:{de:"Ja",en:"Yes"}},{id:Q5,label:{de:"Nein",en:"No"}}];var p0={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Bv,validate:s((e,n,t)=>Z5(e,n,t),"validate")};function Z5(e,n,t){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=Bv.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,...Fp(e.condition,WI(n),t).map(r)]}s(Z5,"ifNodeIssues");var Da="decision",X5=new Set(["decision","review"]),nPe=new Set([...X5,"governedDocument"]);var h0=[{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"}],m0={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:en(te("Freigegeben","Released"),"green",te("Ihre Bewerbung wurde freigegeben","Your application has been released"),te("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."))}},ts={role:"user-action",effect:"side-effect",outcomes:h0,progressDefaults:m0,progressEvents:qn(m0),notificationEvents:s(e=>(e.outcomes??[]).map(n=>({id:n.id,label:n.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:s(e=>[...(e.outcomes??[]).map(n=>({id:n.id,kind:"advance",outcome:n.id,label:n.label,...Li(n.semantic)?{semantic:n.semantic}:{}})),...GN(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:Da,recipient:"internal",title:e.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(e.outcomes??[]).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0),gatesNode:!1,advancesNode:!0,dueInDays:e.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:s((e,n)=>n===Da&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),taskView:s((e,n)=>n===Da?e.view:void 0,"taskView"),validate:Uv};function Uv(e,n,t){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 ${St.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${St.join(", ")}.`},severity:"error"}):Li(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: ${St.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${St.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(Uv,"validateDecisionNode");var Gv=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],g0=[{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 zv="promoted";var y0="promote",w0="Nachr\xFCcken",Fa="promoteLabel";var eQ={de:w0,en:"Promote from waitlist"};function nQ(e){let n=e.inputs?.[Fa];if(n===void 0||n.kind==="unset")return eQ;let t=n.kind==="literal"?n.value:void 0;return Oo(t)!==null&&F(`waitlist node ${e.id}: inputs.${Fa} ${JSON.stringify(n)} is not a { de, en } literal`),t}s(nQ,"promoteLabelOf");var Wv={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},k0={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:Wv,external:en(te("Warteliste","Waiting list"),"amber",te("Sie stehen auf der Warteliste","You are on the waiting list"),te("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:te("Nachger\xFCckt","Promoted"),tone:"green",phase:Wv,external:en(te("Nachger\xFCckt","Moved up"),"green",te("Sie sind nachger\xFCckt","You have moved up"),te("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:te("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:Wv,external:en(te("Warteliste geschlossen","Waiting list closed"),"red",te("Die Warteliste wurde geschlossen","The waiting list has been closed"),te("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},b0={outcomes:Gv,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Xt.map(e=>({value:e,label:oO[e]}))},{id:Fa,label:{de:"Beschriftung \u201ENachr\xFCcken\u201C",en:"Label of \u201CPromote\u201D"},type:"localizedText",required:!1,inspector:"literal-only"}],"inputs"),validate:s((e,n)=>{let t=e.inputs?.[Fa];if(t?.kind==="literal"){let a=Oo(t.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Fa}`,reason:{de:`[waitlist/promoteLabelText] Die Beschriftung \u201ENachr\xFCcken\u201C von "${e.id}" braucht einen Text auf Deutsch und auf Englisch (${a}).`,en:`[waitlist/promoteLabelText] The "Promote" label of "${e.id}" needs a text in German and in English (${a}).`},severity:"error"}]}let r=jy(e);if(r===null)return[];let i=n.nodes.filter(a=>a.type==="waitlist"&&a.id!==e.id),o=n.nodes.indexOf(e);for(let a of i){if(n.nodes.indexOf(a)>o)continue;let l=jy(a);if(l!==null&&l.waitlistOrder!==r.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${a.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 alle Wartelisten eines Prozesses ordnen gleich.`,en:`[waitlist/policyConflict] Waiting lists "${a.id}" and "${e.id}" state different orders \u2014 all waiting lists of a process order alike.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:k0,progressEvents:qn(k0),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:Gv).some(t=>t.id===zv)?[{id:y0,kind:"advance",outcome:zv,semantic:"other",label:nQ(e),surface:tr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var Yv="complete",Jd="acceptedIncomplete",Wm="rejected",tQ="absage",v0="closeWithoutDocuments",x0="rejectAtCompleteness",S0="Ohne Nachreichung abschlie\xDFen",A0="Ablehnen",E0="awaitingDocuments",Hv="documentsComplete",Jv="closedWithoutDocuments",Qv="rejected",Zv="withdrawn",T0="requested",APe={[Yv]:{event:Hv,status:"complete",endsRole:!0},[Jd]:{event:Jv,status:"acceptedIncomplete",endsRole:!1},[Wm]:{event:Qv,status:"rejected",endsRole:!0},[tQ]:{event:Zv,status:"withdrawn",endsRole:!0}};var Qd=s(()=>Dl[0],"beneficiary"),Xv=366;function rQ(e){let n=e.reads,t=Fl(e).flatMap(({address:r})=>un(r)&&!Dl.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(un):[],...t]}s(rQ,"printedFields");function iQ(e,n){let t=de(n);return e.nodes.filter(r=>r.type==="governedDocument"&&rQ(r).some(i=>de(i)===t))}s(iQ,"documentsPrinting");function oQ(e,n){if(!un(n)||n.path!==Qd())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!At(t)}s(oQ,"isCreatedFormBeneficiary");function Kn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Kn,"issue");function sQ(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Yv,Jd].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"&&we(d.form)&&Sr(d.form)&&d.form.owner===t)){if(d.type==="end"){if(No(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(sQ,"reachesApprovedEndUnreviewed");var ex={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},$0={[E0]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:ex,external:en(te("Unterlagen fehlen","Documents missing"),"amber",te("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),te("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."))},[Hv]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:ex,external:en(te("Unterlagen vollst\xE4ndig","Documents complete"),"green",te("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),te("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[Jv]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:ex,external:en(te("Abgeschlossen","Closed"),"neutral",te("Die Nachreichung ist abgeschlossen","The document request is closed"),te("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[Qv]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:iP,external:en(te("Abgelehnt","Rejected"),"red",te("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),te("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."))},[Zv]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:hp,external:en(te("Zur\xFCckgezogen","Withdrawn"),"red",te("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),te("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},R0={outcomes:g0,progressDefaults:$0,progressEvents:qn($0),notificationEvents:s(()=>[{id:T0,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 n=s(r=>e.next?.[r]!==void 0,"wired"),t=[];return n(Jd)&&t.push({id:v0,kind:"advance",outcome:Jd,semantic:"other",label:{de:S0,en:"Close without documents"},surface:tr,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"}}}),n(Wm)&&t.push({id:x0,kind:"advance",outcome:Wm,semantic:"rejected",label:{de:A0,en:"Reject application"},surface:tr,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"}}}),t},"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,n,t)=>{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(E=>je(n,E,"de"),"shown"),l=s(E=>je(n,E,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Kn(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 E=new Set;for(let T of d){if(!we(T))continue;let R=de(T);if(E.has(R)){r.push(Kn(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a(T)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l(T)} appears twice in \`requires\`.`}));continue}if(E.add(R),!un(T)){r.push(Kn(e,"requires",{de:`[completenessCheck/unknownField] ${a(T)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l(T)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let D=Ur(t,T);if(D==null)continue;let L=Js("requires",Hs(D));L==="computed"||L==="repeated"?r.push(Kn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${D.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${D.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(Kn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${Vi(D,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 die Benachrichtigung \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l(T)} ("${Vi(D,"de")}") has no English name (field or person/section) \u2014 the notification "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(Kn(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 E=u.inDays;(typeof E!="number"||!Number.isInteger(E)||E<0||E>Xv)&&r.push(Kn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(E)}" ist keine ganze Zahl von 0 bis ${Xv} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(E)}" is not a whole number from 0 to ${Xv} days.`}))}else typeof u.until!="string"||Dw(u.until)===null?r.push(Kn(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<EP(Date.now())&&r.push({...Kn(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 E=new Map(d.filter(un).map(T=>[de(T),T]));for(let T of E.values())for(let R of iQ(n,T))r.push(Kn(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a(T)} flie\xDFt in das Dokument \u201E${R.label?.de??R.id}" (${R.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(T)} flows into the document "${R.label?.en||R.id}" (${R.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)&&t!==void 0){let E=d.filter(un).filter(D=>{let L=Ur(t,D);return L!=null&&Lp(L)}),R=[...new Set(E.map(D=>D.owner))].filter(D=>sQ(n,e,D));if(R.length>0){let D=E.filter(L=>R.includes(L.owner));r.push({...Kn(e,"next",{de:`[review/unreviewedAfterSupply] ${D.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] ${D.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,b=y?.kind==="binding"?y.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Kn(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."})):t?.roleKeys!==void 0&&!t.roleKeys.has(k)?r.push(Kn(e,"inputs.guestRole",{de:`[completenessCheck/unknownRole] Rolle "${k}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...t.roleKeys].sort().join(", ")}.`,en:`[completenessCheck/unknownRole] Role "${k}" does not exist in this school's role catalog. Known roles: ${[...t.roleKeys].sort().join(", ")}.`})):t?.assignableRoleKeys!==void 0&&!t.assignableRoleKeys.has(k)&&r.push(Kn(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.`})),b===null&&r.push(Kn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Mn}.${Qd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${Mn}.${Qd()}).`}))),we(b)&&!oQ(n,b)&&r.push(Kn(e,"inputs.person",{de:`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${a(b)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${Mn}.${Qd()}).`,en:`[completenessCheck/personNotFormParty] The input "person" is bound to ${l(b)} \u2014 the check assigns the role to the person a form was submitted for ($node.<creating form node>.${Mn}.${Qd()}).`})),b!==null&&k===void 0&&r.push(Kn(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 E of["complete","rejected"])e.next?.[E]===void 0&&r.push(Kn(e,`next.${E}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${E}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${E}" nowhere.`}));return r},"validate")};var aQ=[{id:aO,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Ym=s(e=>e,"asDecision"),I0={[lO]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),te("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."))}},O0={role:"user-action",effect:"side-effect",outcomes:aQ,progressDefaults:I0,progressEvents:qn(I0),notificationEvents:s(e=>ts.notificationEvents(Ym(e)),"notificationEvents"),inputs:s(()=>[{id:ir,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:zo.map(e=>({value:e,label:ZC[e]}))}],"inputs"),actions:s(e=>[...ts.actions(Ym(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Uy,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:ts.optionalActionKinds,workItemTemplates:s(e=>ts.workItemTemplates(Ym(e)).map(n=>n.key===Da?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Uy]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Uv(Ym(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!Vf.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?.[ir],a=XC(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${ir}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${zo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${zo.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"}),we(d)&&Sr(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Lp)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${de(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 ${de(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 ${de(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 ${de(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 _0=["awaitingAnswer","answered"];async function P0(e,n){return(await oa(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(P0,"externalRequestState");var D0=[{id:_o,label:{de:"Bezahlt",en:"Paid"}}],lNe=new Set(D0.map(e=>e.id));var lQ=_o,N0=[{id:lQ,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],dQ={id:yw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:tr,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"}}},cQ={id:gw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:tr,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"}}},uQ={id:gw,kind:"advance",outcome:_o,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:tr,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 nx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(nx,"literalOf");function Qi(e){let n=nx(e,it);return Xf(n)?n:null}s(Qi,"modeOrNull");function fQ(e){let n=nx(e,Ki);return typeof n=="string"&&n.length>0?n:null}s(fQ,"articleKeyOrNull");function pQ(e){let n=nx(e,er);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(pQ,"payeeKeyOrNull");var mQ={id:Ki,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},hQ={id:it,label:{de:"Zahlungsweg",en:"Payment mode"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"manual",label:{de:"Manuell (\xDCberweisung an die Schule)",en:"Manual (transfer to the school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},gQ={id:ji,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},yQ={id:er,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function wQ(e){return[mQ,hQ,...Qi(e)==="online"?[yQ]:[],gQ]}s(wQ,"collectPaymentInputs");var kQ=["amount","currency","settlement"],bQ={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},vQ={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function xQ(e,n){if(Qi(e)!=="online")return[];let t=pQ(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${er}`,i=s(o=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:o,severity:"error"}),"at");return n?.traeger!==void 0&&!n.traeger.has(t)?[i({de:`[collectPayment/unknownPayee] Zahlungsempf\xE4nger \u201E${t}" ist kein Tr\xE4ger dieses Mandanten \u2014 bekannt: ${[...n.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[collectPayment/unknownPayee] Payee "${t}" is not a legal entity of this school \u2014 known: ${[...n.traeger.keys()].join(", ")||"(none)"}.`})]:n?.stripeReadyTraegerKeys!==void 0&&!n.stripeReadyTraegerKeys.has(t)?[i({de:`[collectPayment/onlineWithoutStripe] Zahlungsweg \u201Eonline" an \u201E${t}" setzt voraus, dass dieser Tr\xE4ger ein einsatzbereites Stripe-Konto hat (Administration \u2192 Integrationen \u2192 Stripe, Tr\xE4ger \u201E${t}") \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Emanual" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Payment mode "online" to "${t}" requires this legal entity to have a ready Stripe account (Administration \u2192 Integrations \u2192 Stripe, legal entity "${t}") \u2014 otherwise no family can pay. Until then, choose "manual".`})]:[]}s(xQ,"payeeIssues");var C0={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:en(te("Zahlung offen","Payment due"),"amber",te("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),te("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},F0={outputs:s(()=>[{name:VO,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>wQ(e),"inputs"),outcomes:D0,progressDefaults:C0,progressEvents:qn(C0),notificationEvents:s(e=>Qi(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 n=Qi(e);return n==="online"?[...N0,uQ]:n==="manual"?[dQ,cQ]:[]},"actions"),states:_0,currentState:s((e,n)=>P0(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:Qi(n.node)==="manual"?Vv:jv}),"currentState"),workItemTemplates:s(e=>{let n=e,t=Qi(n);return t==="manual"?[{key:ki,recipient:"internal",title:bQ,unlocks:[yw],advancesNode:!0},{key:Vv,recipient:"external",title:vQ,unlocks:[],informational:!0,advancesNode:!1}]:t!=="online"?[]:[{key:jv,recipient:"external",title:n.label,unlocks:N0.map(r=>r.id),advancesNode:!0}]},"workItemTemplates"),validate:s((e,n,t)=>{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 kQ)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"), der Zahlungsweg ist der Parameter \u201EZahlungsweg" (inputs.mode).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and the payment mode is the parameter "Payment mode" (inputs.mode).`});r.push(...xQ(e,t)),Qi(e)==="manual"&&e.assign?.[ki]===void 0&&i("assign",{de:"[collectPayment/assign] Die Geb\xFChr wird manuell bezahlt, aber kein Team best\xE4tigt den Zahlungseingang \u2014 `assign.confirmPayment` nennt das Team.",en:"[collectPayment/assign] The fee is paid manually, but no team confirms the payment \u2014 `assign.confirmPayment` names the team."}),Qi(e)===null&&i(`inputs.${it}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${Gs.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[it])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${Gs.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[it])}.`});let o=e.inputs?.[ji];if(o?.kind==="literal"){let d=Oo(o.value);d!==null&&i(`inputs.${ji}`,{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=fQ(e);if(a===null)return i(`inputs.${Ki}`,{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.${Ki}`;return t?.billingItemKeys!==void 0&&!t.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):(t?.oneTimeBillingItemKeys!==void 0&&!t.oneTimeBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotOneTime] Artikel \u201E${a}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${ww.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${ww.join(", ")}.`}),t?.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."}):t?.offerProgram?.directBillingItemKeys!==void 0&&!t.offerProgram.directBillingItemKeys.has(a)&&i(l,{de:`[collectPayment/articleNotInProgram] Artikel \u201E${a}" ist dem Programm \u201E${t.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 "${t.offerProgram.nameDe}" \u2014 assign it under Finance \u2192 Articles (a package does not count: it can price the article differently).`}),r)},"validate")};function L0(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(L0,"localeFieldMissingText");var tx=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),M0=/^[a-z][a-z0-9_]*$/;function q0(e,n){let t=[],r=e?.fields;if(!Array.isArray(r))return[{path:"",reason:{de:`[governedDocument/missingTemplateFields] Die Vorlage "${n}" deklariert keine Parameter \u2014 erwartet wird { fields } (die Platzhalter input.<schl\xFCssel>, die ein Knoten f\xFCllt).`,en:`[governedDocument/missingTemplateFields] The template "${n}" 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"||!M0.test(a.key)||o.has(a.key)){t.push({path:`fields.${String(a?.key)}`,reason:{de:`[governedDocument/templateFieldKey] Feld "${String(a?.key)}" der Vorlage "${n}" 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 "${n}" 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(!qi(a.type)){t.push({path:l,reason:{de:`[governedDocument/unknownFieldType] Vorlage "${n}" typisiert das Feld "${a.key}" als "${String(a.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Us.join(", ")}).`,en:`[governedDocument/unknownFieldType] Template "${n}" types the field "${a.key}" as "${String(a.type)}" \u2014 that is not part of the platform's value vocabulary (${Us.join(", ")}).`}});continue}if(tx.has(a.type)||t.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${n}" hat den Typ "${a.type}" \u2014 ein Dokument aus einer Vorlage druckt nur ${[...tx].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a document from a template only prints ${[...tx].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!M0.test(String(d.value)))&&t.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${n}" 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 "${n}" 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)&&t.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${n}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${n}" 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")&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${n}" 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 "${n}" 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&&t.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"?t.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Dokument aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a document from a template is not countersigned.`}}):a.processSource!==void 0&&!Wp.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Wp.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Wp.join(", ")}.`}})}return t.push(...SQ(e,n)),t}s(q0,"templateParameterIssues");function SQ(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:L0(n)}];let t=e.fields.find(i=>i.key===e.localeField),r=t===void 0?{de:"nennt kein Feld der Vorlage",en:"names no field of the template"}:t.type!=="enum"?{de:`ist ${t.type}, erwartet wird ein Auswahlfeld (enum)`,en:`is ${t.type}, a select field (enum) is expected`}:t.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"}:(t.options??[]).length===0?{de:"hat keine Optionen",en:"has no options"}:(t.options??[]).some(i=>!Ye.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${Ye.join(", ")})`,en:`has options that are not a language (allowed: ${Ye.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${n}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${n}" ${r.en}.`}}]}s(SQ,"localeFieldIssues");function K0(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(K0,"applyTemplateStamp");var rx=50;async function Hm(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(rx+1);return t.length>rx&&F(`signing_returns: Vorgang ${n} has more than ${rx} returns`),t}s(Hm,"returnsOf");var ix=50;async function ox(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(ix+1);return t.length>ix&&F(`signing_returns: return ${n} has more than ${ix} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(ox,"returnDocumentsOf");async function j0(e,n){let t=await ox(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(j0,"soleReturnDocumentOf");var Jm=200,RNe=Jm*20;async function AQ(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(AQ,"processRedacted");async function sx(e,n){await AQ(e,n)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(sx,"assertProcessReadable");function EQ(e){let n={_id:e._id,_creationTime:e._creationTime,owner:e.owner,key:e.key};return e.scope==="task"?{...n,scope:"task",result:{kind:"value",value:e.value},writtenByTaskId:e.writtenByTaskId}:{...n,scope:"node",result:e.result}}s(EQ,"rowOf");async function V0(e,n,t){await sx(e,n);let r=await e.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",i=>i.eq("applicationId",n).eq("scope",t.scope).eq("owner",t.owner).eq("key",t.key)).order("desc").take(Jm+1);return r.length>Jm&&F(`[process] application ${n} has more than ${Jm} results of ${t.scope}.${t.owner}.${t.key}`),r.map(EQ)}s(V0,"storeHistory");async function TQ(e,n,t){if(t.key===Mn){await sx(e,n);let i=await e.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",o=>o.eq("applicationId",n).eq("formNodeId",t.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 V0(e,n,{scope:"node",owner:t.owner,key:t.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}s(TQ,"nodeResultAt");async function Qm(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return $Q(await TQ(e,n.applicationId,t),t,n.applicationId)}s(Qm,"readOwnResult");function $Q(e,n,t){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${de(n)} of application ${t} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s($Q,"refOf");var ax={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},RQ=Object.keys(ax),IQ=RQ.filter(e=>ax[e]==="open"),LNe=IQ.filter(e=>e!=="pending");function B0(e){return ax[e]==="terminal"}s(B0,"isTerminalSigningStatus");var Zi=["docusign","insign"];var Zd={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var _Q=B0;function G0(e){return!_Q(e.status)&&e.voidRequestedAt===void 0}s(G0,"holdsContract");async function z0(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(z0,"traegerLegalEntityOfParty");async function PQ(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(PQ,"isOrganizationParty");async function W0(e,n){return await z0(e,n)!==null?"traeger":await PQ(e,n)?"organization":"person"}s(W0,"signerKindOf");async function Y0(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await NQ(e,t.partyId)==="family")return"family";return"traeger"}s(Y0,"signingSideOf");async function NQ(e,n){return await W0(e,n)==="traeger"?"traeger":"family"}s(NQ,"sideOfParty");var vCe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),J0=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var lx=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Zm=m.object({period:lx,anchorDate:m.string()});var TCe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),$Ce=m.union(m.literal("line"),m.literal("aggregate")),Xm=m.record(m.string(),m.string());var CQ=m.union(m.literal("active"),m.literal("ended")),dx=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()})),DQ=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),FQ={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:dx,pricingSelections:m.optional(Xm),paymentSchedule:m.optional(Zm),resolvedSnapshot:m.any(),feeGroup:m.optional(J0),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},LQ={...FQ,period:DQ,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:CQ,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},DCe=Ct(LQ).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Tr=m.union(m.string(),m.null()),Q0=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),MQ=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()}))}),Z0=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(Q0)})),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:Tr}),X0=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(lx),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Tr,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),qQ={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Tr,pricing:dx,paymentSchedule:m.optional(Zm),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:Tr,endDate:Tr,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Tr,programName:Tr,runName:Tr,groupName:Tr}),m.null()),grants:m.array(X0),payerAllocations:m.array(Z0)},KQ=m.object({...qQ,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Tr,sourceValidTo:Tr})}),jQ=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(Q0),declaredSigners:m.array(MQ),payerAllocations:m.array(Z0),aggregateGrants:m.optional(m.array(X0)),lines:m.array(KQ)}),VQ=jQ;var BQ=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),UQ=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:Ji})),caption:m.string(),page:m.number(),box:BQ}))});var GQ=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(UQ)}))}),zQ=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()}),WQ={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:GQ,coverLetter:m.optional(zQ),snapshot:Ve.historyOf(VQ),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()}))},UCe=Ct(WQ).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 iDe=16*1024;var oDe=15*6e4;var sDe=10*6e4;var cx={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()}))},SDe=Ct({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...cx}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var RDe=m.object(cx);var ux=200;async function YQ(e,n,t,r){n.length>ux&&F(`${r} is carried by more than ${ux} signing requests`);let i=[],o=new Set;for(let l of n){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=t==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}s(YQ,"requestsOfMembers");async function eM(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(ux+1);return await YQ(e,r,t,`revision ${n}`)}s(eM,"requestsOfSnapshot");var nM=100;async function HQ(e,n){let t=await eM(e,n);t.length>nM&&F(`requestsBySideOf: revision ${n} has more than ${nM} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await Y0(e,i.signers)].push(i);return r}s(HQ,"requestsBySideOf");async function fx(e,n){return(await HQ(e,n)).family}s(fx,"familyRequestsOf");var px=100;async function JQ(e,n){let t=await e;return t.length>px&&F(`contractChain: more than ${px} ${n}`),t}s(JQ,"bounded");async function QQ(e,n,t){let r=await Qm(e,{applicationId:n,nodeId:t,key:Yf});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Yf} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(QQ,"nodeContractRef");async function tM(e,n){return await JQ(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",t=>t.eq("contractId",n)).take(px+1),`revisions on contract ${n}`)}s(tM,"snapshotsAsc");async function mx(e,n){let t=(await fx(e,n)).filter(G0);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(mx,"openFamilyRequest");async function ZQ(e,n){for(let t of await tM(e,n))if((await fx(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(ZQ,"familyRoute");async function rM(e,n){for(let t of n)if(await ZQ(e,t)==="paper")return"paper";return"provider"}s(rM,"familyRouteOf");async function XQ(e,n){let t=await j0(e,n._id),r=await e.db.system.get("_storage",t.storageId);return r===null&&F(`contractChain: return ${n._id} holds missing file ${t.storageId}`),{_id:n._id,_creationTime:n._creationTime,storageId:t.storageId,filename:t.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:n._id}}s(XQ,"toReturn");function eh(e){async function n(a,l){return await QQ(a,l,e.id)}s(n,"contractOrNull");async function t(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),p=u===null?null:await a.db.get(u),h=await n(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(t,"snapshotOf");async function r(a,l){let d=await n(a,l);return d===null?null:(await tM(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 t(a,l,d.askedAbout,`returned(${d.where})`),u=await mx(a,c._id);if(u===null)return null;let p=(await Hm(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 XQ(a,p[0])},pinOf(a){return a.contractSnapshotId},returnPinOf(a){return a.signingReturnId}},contractOrNull:n,snapshotOf:t,newestSnapshot:r,contractsOf:{async contractsOf(a,l){let d=await n(a,l);return d===null?[]:[d]}}.contractsOf}}s(eh,"contractNodeReads");function nh(e){return e.addedParts??[]}s(nh,"addedPartsOf");var hx=50;async function e8(e,n){let t=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",n)).take(hx+1);return t.length>hx&&F(`groupRunsOf: generation group ${n} has more than ${hx} runs`),t.length===0&&F(`groupRunsOf: generation group ${n} has no run`),t.sort((r,i)=>r._creationTime-i._creationTime)}s(e8,"groupRunsOf");async function iM(e,n){let t=await e8(e,n),r=t[0].packageRunId;if(r!==void 0){(t.some(l=>l.packageRunId!==r||l.partKey===void 0)||new Set(t.map(l=>l.partKey)).size!==t.length)&&F(`groupRunsInOrder: package group ${n} has inconsistent members`);let i=await e.db.get(r);i===null&&F(`groupRunsInOrder: package run ${n} 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),...nh(i).map(l=>l.partKey)];return(o.length>50||t.some(l=>!a.includes(l.partKey)))&&F(`groupRunsInOrder: package group ${n} names an unknown part`),t.sort((l,d)=>a.indexOf(l.partKey)-a.indexOf(d.partKey))}F(`Package run ${n} has no package reference.`)}s(iM,"groupRunsInOrder");function oM(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(oM,"isCompleteGroup");var gx=200;function n8(e){let n=e.generatorStamp?.parts;return n===void 0&&F(`groupChain: node "${e.id}" names no combined generator \u2014 only a combined generator keeps a group chain`),n.map(t=>t.partKey)}s(n8,"groupPartKeys");async function t8(e,n,t){let r=await e.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",n).eq("workflowNodeId",t)).take(gx+1);return r.length>gx&&F(`groupChain: more than ${gx} generation runs on node ${t}`),r}s(t8,"nodeRuns");async function r8(e,n,t){let r=n8(t),i=new Set;for(let a of await t8(e,n,t.id))a.packageRunId===void 0&&F(`groupChain: run ${a._id} on the combined node "${t.id}" carries no generation group`),i.add(a.packageRunId);let o=[];for(let a of i){let l=await iM(e,a);if(!oM(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(nh(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 "${t.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(r8,"groupRevisionRows");async function yx(e,n,t){let r=await Qm(e,{applicationId:n,nodeId:t,key:Hf});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${Hf} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(yx,"nodeGroupContracts");async function i8(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await mx(e,r._id);i!==null&&t.set(i._id,i)}return t.size>1&&F(`groupChain: generation group ${n.packageRunId} is held by ${t.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...t.values()][0]??null}s(i8,"openGroupRequest");async function o8(e,n){let t=[];for(let i of await ox(e,n._id)){let o=await e.db.system.get("_storage",i.storageId);o===null&&F(`groupChain: return ${n._id} holds missing file ${i.storageId}`),t.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...o.contentType!==void 0?{mimeType:o.contentType}:{}})}let r=t[0];return{_id:n._id,_creationTime:n._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:n._id,documents:t}}s(o8,"toGroupReturn");function sM(e){async function n(i,o,a,l){let d=(await r8(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(n,"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 n(i,o,a.askedAbout,`returned(${a.where})`),d=await i8(i,l);if(d===null)return null;let c=(await Hm(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 o8(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await yx(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(sM,"groupNodeReads");async function s8(e,n){let t=n.lifecycle.kind==="draft"?void 0:n.lifecycle.kind;return{_id:n._id,_creationTime:n._creationTime,versionNumber:n.versionNumber,...t!==void 0?{status:t}:{},origin:n.origin.kind,storageId:n.storageId,...await sb(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(s8,"toRevision");async function a8(e,n){let t=await s8(e,n);return{_id:t._id,_creationTime:t._creationTime,storageId:t.storageId,...t.filename!==void 0?{filename:t.filename}:{},...t.mimeType!==void 0?{mimeType:t.mimeType}:{},round:t.versionNumber}}s(a8,"toReturn");function aM(e){let n=Qp(e);async function t(o,a){return await o.db.query("admission_documents").withIndex("by_applicationId_and_slotKey_and_versionNumber",l=>l.eq("applicationId",a).eq("slotKey",n)).collect()}return s(t,"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 t(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 "${n}"`),c.versionNumber<=u.versionNumber)return null}return await a8(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(aM,"artifactNodeReads");function th(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(th,"documentChainKind");function lM(e){switch(th(e)){case"contract":return eh(e).reads;case"group":return sM(e).reads;case"artifact":return aM(e).reads}}s(lM,"documentReadsFor");var l8={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Xd(e){let n=e.responseStrategy;return typeof n=="string"&&n in hi?hi[n].producesResponseArtifact:!1}s(Xd,"returnsSignedCopy");function d8(e){return Xd(e)&&e.confirmContractTerms!==!1}s(d8,"asksContractTerms");function dM(e){return d8(e)?{title:e.contractTermsQuestionText??l8,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(dM,"contractTermsConfirm");function cM(e){let n=c8(e);return n.length>0&&n.every(t=>t.status==="blocked")}s(cM,"producerWindowHeld");function c8(e){return e.filter(n=>n.isOpen&&n.kind==="admission"&&n.templateKey!==void 0&&od.has(n.templateKey))}s(c8,"openProducerRows");async function u8(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:Ww(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Yr||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${Yr} row`),a}s(u8,"rejectedReturnOfAsk");async function uM(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await u8(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(uM,"returnedCopyOfAsk");var wx=new Set([...od,Ar,Ko,Yi,Yr,ht]),gM={id:Un,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},yM={id:xo,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function f8(e){let n=[],t=[{slot:gM,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:yM,production:"template",de:{a:"eine",the:"die",it:"sie"}}];for(let{slot:r,production:i,de:o}of t){let a=e.inputs?.[r.id];if(a===void 0||a.kind==="unset")continue;let l=`inputs.${r.id}`;if(e.production!==i){n.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"){n.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=Ll(a.value,{type:r.type});d!==null&&n.push(Se(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return n}s(f8,"referenceInputIssues");var p8={id:mi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},m8={id:wa,type:"boolean",label:{de:"Coverletter best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},h8={id:Lt,type:"legalEntity",label:kC,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function g8(e,n){let t=`inputs.${Lt}`,r=e.inputs?.[Lt];if(r!==void 0&&r.kind==="binding")return[Se(e,t,{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=ya(e),o=n?.resolverPrintsTraegerAddress?.get(e.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...o])){let d=n?.traeger?.get(l);n?.traeger!==void 0&&d===void 0?a.push(Se(e,t,{de:`[governedDocument/unknownTraeger] Knoten "${e.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...n.traeger.keys()].join(", ")||"(keiner)"}.`,en:`[governedDocument/unknownTraeger] Node "${e.id}" names the legal entity "${l}", which does not exist in this school \u2014 known: ${[...n.traeger.keys()].join(", ")||"(none)"}.`})):d!==void 0&&!d.hasAddress&&o.has(l)&&a.push(Se(e,t,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Kp.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 (${Kp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(g8,"traegerIssues");function rh(e){if(e.production==="template"){let t=e.templateStamp?.fields;return Array.isArray(t)?t:[]}if(e.production!=="resolver")return[];let n=e.generatorStamp?.inputSchema?.fields;return Array.isArray(n)?n.map(t=>{let{label:r}=t;return r===void 0?{...t,label:{de:t.key,en:t.key}}:(Ci(r)||F(`governedDocument "${e.id}": the stamped generator parameter "${t.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 rebuild local fixtures or obtain a reviewed repair of this retained workflow stamp.`),{...t,label:r})}):[]}s(rh,"generatorFields");function y8(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(y8,"deferredToCockpit");function w8(e){return qi(e.type)?e.type:void 0}s(w8,"resolverSlotType");function k8(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=va(e);return{confirm:{title:{de:`\u201E${n.de}\u201C jetzt senden?`,en:`Send "${n.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(k8,"issueConfirmation");function Se(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Se,"issue");function ih(e){return zp.includes(e.production)&&Go.includes(e.approval)&&Yp.includes(e.responseStrategy)}s(ih,"hasValidModes");async function kx(e,n){let t=await oa(e,{applicationId:n.applicationId,nodeId:n.node.id});if(t.length===0)return"pending";let r=t.filter(a=>a.isOpen&&a.kind==="admission");if(cM(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&od.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===Yi))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Ar);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===ht))return"signatureStalled";let o=r.find(a=>a.templateKey===Ko);if(o!==void 0){if(gi(n.node).issuesBy==="provider"){let l=th(n.node)==="group"?(await yx(e,n.applicationId,n.node.id)).map(d=>d.contractId):[await eh(n.node).contractOrNull(e,n.applicationId)].flatMap(d=>d===null?[]:[d]);if(l.length===0&&F(`governedDocCurrentState: eSignature node "${n.node.id}" has an open ask but no contract`),await rM(e,l)==="provider")return"awaitingSignature"}return gi(n.node).producesResponseArtifact?await uM(e,{chain:lM(n.node),applicationId:n.applicationId,ask:o,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${n.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(a=>a.templateKey===Yr)?"responseInCheck":"done"}s(kx,"governedDocCurrentState");function fM(e){return e.production!=="none"&&th(e)!=="artifact"}s(fM,"keepsDocumentInContractDomain");function b8(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!Zt(r.key))return[];let i=vo(r.key);if(n.type!==i.type)return[Se(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.key}" ist ${n.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${de(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${n.key}" is ${n.type}, the environment variable "${i.label.en}" (${de(r)}) supplies ${i.type}.`})];let o=new Set((n.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!o.has(l.value));return a.length===0?[]:[Se(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.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 "${n.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(b8,"envCoverageIssues");function wM(e,n){let t=[];for(let r of rh(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...b8(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${we(a.address)?de(a.address):JSON.stringify(a.address)}`,en:`a binding to ${we(a.address)?de(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:y8(e,r.key)?{de:"eine Erg\xE4nzung im Cockpit",en:"a completion in the cockpit"}:null;l!==null&&t.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||t.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${e.id}.inputs.${r.key}`,reason:{de:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${r.label.de}" des Generators ${n.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 ${n.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 t}s(wM,"fieldSourceIssues");function v8(e){let n=br(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=q0(e.templateStamp,n).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...wM(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(v8,"templateIssues");function x8(e,n){return(n?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(t=>{if(t.documentAnchors===null)return[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${t.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 "${t.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})];let r=t.signerAnchors.filter(i=>!t.documentAnchors.has(i));return r.length===0?[]:[Se(e,"resolver",{de:`[governedDocument/eSignatureAnchorMissing] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${t.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 "${t.pin}" has no anchor for ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 the provider would find no signature field for these people.`})]})}s(x8,"eSignatureAnchorIssues");function S8(e,n){return n===void 0||n.sendable?[]:gi(e).issuesBy!=="provider"?[]:[Se(e,"responseStrategy",{de:`[signing/noActiveProvider] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[signing/noActiveProvider] Node "${e.id}" is signed electronically, but the school cannot send: ${n.reason.en}`})]}s(S8,"eSignatureProviderIssues");var pM={key:"dokument",label:te("Dokument","Document"),scope:"node"},mM={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:pM,external:en(te("In Vorbereitung","In preparation"),"blue",te("Ihr Dokument wird vorbereitet","Your document is being prepared"),te("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:te("Dokument bereitgestellt","Document issued"),tone:"blue",phase:pM,external:en(te("Dokument bereit","Document ready"),"amber",te("Ihr Dokument liegt bereit","Your document is ready"),te("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."),te("Dokument beantworten","Respond to the document"))}};function hM(e,n){return!ih(e)||e.production==="none"?null:n===Yi||Jp(e).some(r=>r.key===n)?Qp(e):null}s(hM,"governedDocRowSlot");var kM={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>qo,"processHoldTemplate"),progressDefaults:mM,progressEvents:qn(mM),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(!ih(e))return[];let n=gi(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...Uo(e)?["awaitingCoverLetter"]:[],...i,...n.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(t.push({id:yk(e),kind:"internal",surface:ka,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Ar}:{},...k8(e)??{}}),t.push({id:SC,kind:"internal",surface:ka,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:AC,kind:"internal",surface:ka,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:Bp,kind:"internal",label:e.responseLabels?.accept??n.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:n.acceptOutcomeId,kind:"advance",outcome:n.acceptOutcomeId,semantic:n.outcomeSemantics.accept,label:e.responseLabels?.accept??n.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:n.declineOutcomeId,kind:"advance",outcome:n.declineOutcomeId,semantic:n.outcomeSemantics.decline,label:e.responseLabels?.decline??n.defaultLabels.decline,availableIn:Uo(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),Uo(e)&&(t.push({id:jp,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),t.push({id:Vp,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),n.producesResponseArtifact&&t.push({id:Up,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Gp,kind:"internal",surface:ka,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:jo,kind:"internal",surface:ka,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:EC,currentState:kx,workItemTemplates:s(e=>{let n=e;return ih(n)?Jp(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e,r=hM(t,n);return r===null?[]:Jp(t).find(o=>o.key===n)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,n)=>{let t=hM(e,n);if(t!==null)return n===Yi?{kind:"artifact",slot:t,part:"coverLetter"}:{kind:"artifact",slot:t}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[gM,h8]:[],...e.production==="template"?[yM]:[],p8,...e.generatorStamp?.coverLetter===!0?[m8]:[],...rh(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=w8(n);return t===void 0?[]:[{field:n,type:t}]}).map(({field:n,type:t})=>({id:n.key,type:t,label:n.label,required:n.required===!0&&n.processSource===void 0,...n.processSource===void 0?{deferrable:!0}:{},...n.defaultValue!==void 0&&(typeof n.defaultValue=="string"||typeof n.defaultValue=="number"||typeof n.defaultValue=="boolean"||n.defaultValue===null||t==="pricedItem"&&Mi(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:ow,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Ko||n===Yi||n===id||n===Yr||n===ht){let t=n===Ko?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===Yr?{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"}:n===ht?{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 "${n}" (Knoten "${e.id}") ist verboten \u2014 ${t.de}; zul\xE4ssige intrinsische Ziele: ${qo}${e.approval==="release"?`, ${Ar}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${qo}${e.approval==="release"?`, ${Ar}`:""}.`}}return n===Ar&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Ar}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Ar}" 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,n)=>{if(fM(n.node))return!1;let t=await kx(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&gi(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=dM(n.node);if(t===null||fM(n.node))return null;let r=await kx(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!ih(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${zp.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Go.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Yp.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 {${zp.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Go.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Yp.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=hi[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 E of o)E.visibility!=="external"&&r.push(Se(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${E.key}" auf Knoten "${e.id}" hat visibility "${E.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${E.key}" on node "${e.id}" has visibility "${E.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(E=>E.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(E=>l.includes(E)))&&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(E=>`"${E}"`).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(E=>`"${E}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(E=>{let T=c?.[E];return T===null||typeof T!="object"||!Object.values(T??{}).some(R=>typeof R=="string"&&R.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"&&w.prepareDocument===void 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.`})),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)w.responseCheck===void 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[E,T]of[["assign.responseCheck",w.responseCheck!==void 0],["titles.check",c?.check!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${E} \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 ${E} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"?w.signingRecovery===void 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.`})):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'.`})),i.issuesBy==="provider"&&r.push(...x8(e,t),...S8(e,t?.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.`})),Xd(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[E,T]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${E} \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 ${E} \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[E,T]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",w.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])T&&r.push(Se(e,E,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${E} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${E} \u2014 without a production phase there is nothing to carry it.`}));for(let E of e.tasks??[])wx.has(E.key)&&r.push(Se(e,`tasks.${E.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${E.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...wx].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${E.key}" on node "${e.id}" collides with an intrinsic template (${[...wx].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...g8(e,t)):e.inputs?.[Lt]!==void 0&&r.push(Se(e,`inputs.${Lt}`,{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(...f8(e)),e.production==="resolver"){let E=oi(e);if(E!==null){let T=eO(E);for(let R of rh(e)){if(!qi(R.type)){r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/unknownFieldType] Generator "${T}" typisiert das Feld "${R.key}" als "${String(R.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Us.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${T}" types the field "${R.key}" as "${String(R.type)}" \u2014 that is not part of the platform's value vocabulary (${Us.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if(R.type==="personList"){r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${T}" deklariert das Feld "${R.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 "${T}" declares the field "${R.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}R.type==="party"&&(R.key.endsWith("PartyId")||r.push(Se(e,`generatorStamp.inputSchema.${R.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${R.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 "${R.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...wM(e,{de:`"${T}"`,en:`"${T}"`}))}}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(...v8(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?.[wa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${wa}`,{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.`})),Uo(e)&&(t!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${wa}`,{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.`})),gi(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?.[mi],b=y===void 0||y.kind==="unset"?void 0:y.kind==="literal"?y.value:y;return b!==void 0&&!ad(b)&&r.push(Se(e,`inputs.${mi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(b)} \u2014 erlaubt ist eine ganze Zahl von ${Vo} bis ${Bo} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(b)} \u2014 a whole number from ${Vo} to ${Bo} days is allowed.`})),b===void 0&&rh(e).some(E=>E.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${mi}`,{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 bM={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 Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Bt,"isRecord");var bx=["field","join","literal","address","payment","contract"],A8=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),E8=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ar(e){return typeof e=="string"&&e.trim().length>0}s(ar,"nonEmptyString");function oh(e,n,t,r,i="value"){if(!Bt(e)||!Bt(e.from)){r.push({path:n,code:"mappingShape",message:{de:`${n}: eine Zuordnung braucht \`from\`.`,en:`${n}: a mapping needs \`from\`.`}});return}let o=e.from,a=bx.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${bx.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${bx.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ar(o.field)&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.field\` ist leer.`,en:`${n}: \`from.field\` is empty.`}}),l==="join"&&!(Array.isArray(o.join)&&o.join.length>=2&&o.join.every(ar))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.join\` nennt mindestens zwei Formularfelder.`,en:`${n}: \`from.join\` names at least two form fields.`}}),e.whenEmpty!==void 0&&(i==="condition"?r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`,en:`${n}: \`whenEmpty\` does not apply to a condition (\`unless\`, \`linkAddressToPupilIf\`).`}}):l!=="field"&&l!=="join"?r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`,en:`${n}: \`whenEmpty\` applies only to a form answer (\`field\`, \`join\`).`}}):typeof e.whenEmpty=="boolean"||Number.isFinite(e.whenEmpty)||ar(e.whenEmpty)||r.push({path:n,code:"mappingShape",message:{de:`${n}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`,en:`${n}: \`whenEmpty\` is an Engage value (text, number or yes/no).`}})),l==="address"&&!(we(o.address)&&o.address.scope==="env"&&Zt(o.address.key))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`,en:`${n}: \`from.address\` is an environment value (\`{ scope: 'env', key: 'stage.key' }\`).`}}),l==="payment"&&o.payment!=="amount"&&o.payment!=="settledAt"&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.payment\` ist amount oder settledAt.`,en:`${n}: \`from.payment\` is amount or settledAt.`}}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(o.contract))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.contract\` ist startDate, signedAt oder createdAt.`,en:`${n}: \`from.contract\` is startDate, signedAt or createdAt.`}}),l==="literal"&&!["string","number","boolean"].includes(typeof o.literal)&&r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from.literal\` ist Text, Zahl oder ja/nein.`,en:`${n}: \`from.literal\` is text, a number or yes/no.`}}),e.format!==void 0&&!A8.has(String(e.format))&&r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekanntes Format \u201E${String(e.format)}".`,en:`${n}: unknown format "${String(e.format)}".`}}),e.lookup!==void 0&&!(ar(e.lookup)&&Bt(t[e.lookup]))&&r.push({path:n,code:"unknownLookup",message:{de:`${n}: die Lookup-Tabelle \u201E${String(e.lookup)}" fehlt in \`lookups\`.`,en:`${n}: the lookup table "${String(e.lookup)}" is missing from \`lookups\`.`}});let d=e.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||Bt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Bt(d)&&E8.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(oh,"checkMapping");function Xi(e,n,t,r,i){if(!Bt(e)){i.push({path:n,code:"bodyShape",message:{de:`${n}: erwartet ein Objekt Feld \u2192 Zuordnung.`,en:`${n}: expects an object field \u2192 mapping.`}});return}let o=bM[t];for(let a of o.required)a in e||i.push({path:`${n}.${a}`,code:"missingRequired",message:{de:`${n}: Engage verlangt \u201E${a}" (${o.body}) \u2014 es fehlt eine Zuordnung.`,en:`${n}: Engage requires "${a}" (${o.body}) \u2014 a mapping is missing.`}});for(let[a,l]of Object.entries(e))oh(l,`${n}.${a}`,r,i)}s(Xi,"checkBody");function vM(e,n,t,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:n,code:"bodyShape",message:{de:`${n}: erwartet eine Liste.`,en:`${n}: expects a list.`}});return}let i=new Set;e.forEach((o,a)=>{let l=`${n}[${a}]`;if(!Bt(o)||!ar(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),oh(o.value,`${l}.value`,t,r),o.unless!==void 0&&oh(o.unless,`${l}.unless`,t,r,"condition")})}s(vM,"checkAif");function vx(e){let n=[];if(!Bt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Bt(e.lookups)?e.lookups:{};Bt(e.lookups)||n.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(t))(!Bt(i)||!Object.values(i).every(ar))&&n.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(ar(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Xi(e.pupil,"engage.pupil","addPupil",t,n),Xi(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&Xi(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&Xi(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&Xi(e.medical,"engage.medical","addMedical",t,n),vM(e.pupilAif,"engage.pupilAif",t,n),!Array.isArray(e.contacts))n.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(!Bt(i)||!ar(i.key)||!ar(i.presentIf)){n.push({path:a,code:"contactShape",message:{de:`${a}: \`key\` und \`presentIf\` fehlen.`,en:`${a}: \`key\` and \`presentIf\` are missing.`}});return}r.has(i.key)&&n.push({path:a,code:"contactDuplicate",message:{de:`${a}: Kontakt \u201E${i.key}" doppelt.`,en:`${a}: contact "${i.key}" appears twice.`}}),r.add(i.key),Xi(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&Xi(i.address,`${a}.address`,"addContactAddress",t,n);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){n.push({path:`${a}.${l}`,code:"bodyShape",message:{de:`${a}.${l}: erwartet eine Liste.`,en:`${a}.${l}: expects a list.`}});continue}c.forEach((u,p)=>Xi(u,`${a}.${l}[${p}]`,d,t,n))}}vM(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&oh(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Bt(r)||!ar(r.repeated)||!ar(r.field)||!ar(r.equals))&&n.push({path:"engage.siblingsAttending",code:"bodyShape",message:{de:"`engage.siblingsAttending` braucht repeated, field und equals.",en:"`engage.siblingsAttending` needs repeated, field and equals."}})}return n}s(vx,"engagePushConfigIssues");function*xx(e){let n=[e.pupil,e.admission,e.nationality,e.visa,e.medical];for(let t of n)for(let r of Object.values(t??{}))yield{mapping:r};for(let t of e.pupilAif??[])yield{mapping:t.value},t.unless!==void 0&&(yield{mapping:t.unless});for(let t of e.contacts){let r=[t.basic,t.address,...t.emails??[],...t.telephones??[]];for(let i of r)for(let o of Object.values(i??{}))yield{mapping:o,contactKey:t.key};for(let i of t.aif??[])yield{mapping:i.value,contactKey:t.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:t.key});t.linkAddressToPupilIf!==void 0&&(yield{mapping:t.linkAddressToPupilIf,contactKey:t.key})}}s(xx,"mappingsOf");function xM(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of xx(e))for(let i of T8(t.from))n.add($8(i,r));return[...n]}s(xM,"configFieldKeys");function T8(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(T8,"formFieldsOf");function $8(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s($8,"resolveFieldKey");function SM(e,n){for(let{mapping:t}of xx(e))if(n in t.from)return!0;return!1}s(SM,"configReadsSource");function AM(e){let n=new Set;for(let{mapping:t}of xx(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(AM,"configEnvLeaves");var EM="done",TM=["sandbox","production"];var sh="engagePush",ELe=660*1e3;function eo(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(eo,"issue");function Sx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Sx,"literal");function $M(e){return vx(e.engage).length===0?e.engage:null}s($M,"validConfig");function R8(e,n){let t=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===n||i.has(a))continue;i.add(a);let l=t.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(R8,"bypassingPath");var RM={role:"system-action",effect:"side-effect",outcomes:[{id:EM,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=$M(e);return n===null?[]:AM(n)},"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,n,t)=>{let r=e.label?.de??e.id,i=e.label?.en||e.id,o=[],a=Sx(e,"target");TM.includes(a)||o.push(eo(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=Sx(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(eo(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`})),e.assign?.[sh]===void 0&&o.push(eo(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${sh}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${sh}\` names the team.`}));for(let k of vx(e.engage))o.push(eo(e,k.path,{de:`[engagePush/config] \u201E${r}": ${k.message.de}`,en:`[engagePush/config] "${i}": ${k.message.en}`}));let d=n.nodes.filter(k=>k.id!==e.id&&k.type==="engagePush"&&Sx(k,"target")===a);d.length>0&&o.push(eo(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${d.map(k=>`"${k.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${d.map(k=>`"${k.id}"`).join(", ")} already transfers to the same target.`})),R8(n,e.id)&&o.push(eo(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 c=$M(e),u=e;for(let[k,y,b,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!SM(c,k)||u[y]!==void 0||o.push(eo(e,y,{de:Ws("address/missing",{where:`\u201E${r}\u201C \u203A ${b}`},"de"),en:Ws("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let p=u.form,h=we(p)&&p.scope==="node"?p.owner:void 0,w=h===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&w!==void 0){let k=new Set(w.keys()),y=xM(c).filter(b=>!k.has(b)&&!/\[\d+\]\./.test(b));if(y.length>0){let b=n.nodes.find(E=>E.id===h);o.push(eo(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${b?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${y.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${b?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${y.join(", ")}.`},"warning"))}}return o},"validate")};var rs={join:n0,end:sP,roleAssign:r0,eventTrigger:i0,waitlist:b0,completenessCheck:R0,form:u0,setFlag:f0,if:p0,decision:ts,review:O0,collectPayment:F0,governedDocument:kM,countersign:qC,engagePush:RM};LO(rs);function IM(e,n){let t=e;if(t==null||!Array.isArray(t.nodes))throw new Error(`offer plan: the ${n} carries no workflow graph with nodes`);return e}s(IM,"graphOf");function OM(e){let n=new Map;for(let t of e.nodes)for(let r of Vr(e,t))n.set(de(r.address),r.nodeId);return n}s(OM,"producedOf");function _M(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(Ro(e,t).map(r=>de(r.address))));return n}s(_M,"readsOf");function PM(e,n){let t=IM(e,"bundle"),r=IM(n.graph,"live head"),i=OM(t),o=OM(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=_M(t),d=_M(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:n.revision,pinnedApplications:n.pinnedApplications,produced:a,reads:c}}s(PM,"planAddresses");function NM(e){let n=[...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(n.length===0)return[];let{real:t,test:r}=e.pinnedApplications;return n.push({icon:"!",target:"pinned",status:`${t+r} Anmeldungen (${t} echt, ${r} Test) auf Fassung ${e.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),n}s(NM,"addressPlanRows");function CM(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(CM,"changed");async function DM(e,n,t){if(n.index.module!==Mv.name)throw new Error(`offer: unknown module "${n.index.module}"`);return wD(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return Mv.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(DM,"applyOffer");async function FM(e,n,t,r="published"){let i=await e.query(x.setup.offerBundle.exportOfferBundle,{client:n,offerKey:t,generation:r});return{bundle:i.bundle,generation:i.generation,revision:i.revision}}s(FM,"exportOffer");async function Ax(e,n){let{index:t}=n,i=(await e.query(x.workflow.listManifests,{client:t.tenant})).find(w=>w.offerKey===t.slugs.manifest),o="create";i&&(o="same");let a={};for(let[w,k]of Object.entries(n.smartforms??{})){let y=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:w}):null;a[w]=y?.def?CM(k,{label:y.def.label,...y.def.definition})?"change":"same":"create"}let l="absent",d=null;if(n.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=CM(k&&{graph:Ds(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:Ds(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let w=await e.query(x.workflow.getOfferHeadPins,{client:t.tenant,offerKey:t.slugs.manifest});w!==null&&(d=PM(n.workflow.graph,w))}}let c=t.program?.stages,u=c===void 0?[]:i?await Lv(e,t.tenant,t.slugs.manifest,c):Af(null,[],c),p=await Gm(e,t.tenant,i?t.slugs.manifest:null,t),h=i?await e.query(x.workflow.getOfferPublishState,{client:t.tenant,offerKey:t.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(Ax,"diffOffer");function ah(e){if(e.type==="governedDocument"){let n=e.production;return n==="resolver"?"resolver":n==="template"?"template":n==="upload"||n==="none"?"manual":"unauthored"}return null}s(ah,"contractProductionModeOf");function LM(e){return ah(e)==="resolver"}s(LM,"isResolverCarrierNode");function lh(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=oi(t);return!LM(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(lh,"authoredPins");var MM={type:"address",dataType:"composite"};var qM={type:"boolean",dataType:"boolean"};var KM={type:"consent",dataType:"boolean"};var jM={type:"date",dataType:"date"};var VM={type:"docRef",dataType:"file"};var BM={type:"email",dataType:"text"};var UM={type:"string",dataType:"text"};var GM={type:"tel",dataType:"text"};var dh={address:MM.dataType,boolean:qM.dataType,consent:KM.dataType,date:jM.dataType,docRef:VM.dataType,email:BM.dataType,enum:U_.dataType,string:UM.dataType,tel:GM.dataType};function Ex(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(Ex,"shapeOf");function zM(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,Ex(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,Ex(l)))),o.repeated?.forEach(a=>t.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:n}];for(let o of t){let a=new Map(n);o.itemTemplate.forEach(l=>a.set(`$item.${l.key}`,Ex(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(zM,"fieldMapScopes");function I8(e){let n=new Set,t=s(r=>{r.computed?.forEach(i=>n.add(i.key)),r.subsections?.forEach(t)},"visit");return e.sections.forEach(t),n}s(I8,"computedKeysOf");function WM(e){let n=[],t=I8(e);for(let r of zM(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}]`;t.has(l.from)&&n.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?n.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 n}s(WM,"validateFieldMapSources");function YM(e){let n=[],t=new Set;for(let o of zM(e))for(let a of o.effects)if(a.kind==="fieldMap")for(let l of a.mappings)t.add(l.from);let r=s((o,a)=>{let l=a.some(d=>t.has(d));o.kind==="cf_value"&&!l?n.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&&n.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),n}s(YM,"validateFieldPersistence");var O8="$";function _8(e){return typeof e=="string"&&e.startsWith(O8)}s(_8,"isRef");function ch(e){return e.slice(1)}s(ch,"stripRef");function*P8(e){switch(e.kind){case"relationship":if(yield e.from,yield e.to,e.meta)for(let n of Object.values(e.meta))yield n;return;case"fieldMap":yield e.target;return;case"shareValue":yield e.from,yield e.to;return;case"person":case"organization":return}}s(P8,"refSlots");function N8(e){let n=new Set;for(let t of P8(e))_8(t)&&n.add(ch(t));return[...n]}s(N8,"collectRefs");function C8(e){let n=new Set(e.map(o=>o.id)),t=new Map,r=new Map,i=new Map;for(let o of e)i.set(o.id,o),t.set(o.id,[]),r.set(o.id,[]);for(let o of e)for(let a of N8(o))n.has(a)&&(t.get(o.id).push(a),r.get(a).push(o.id));for(let o of e){if(o.kind!=="shareValue")continue;let a=ch(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&ch(l.target)===a||l.kind==="shareValue"&&ch(l.to)===a)||t.get(o.id).includes(l.id)||(t.get(o.id).push(l.id),r.get(l.id).push(o.id))}return{refsOf:t,successors:r,byId:i}}s(C8,"buildAdjacency");function HM(e){let{refsOf:n}=C8(e),r=Np(e.map(i=>i.id),i=>(n.get(i)??[]).map(o=>({target:o,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}s(HM,"detectCycle");function JM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(JM,"escapeRegExp");function no(e){return new RegExp(`^${JM(e)}\\[(\\d+)\\]\\.(.+)$`)}s(no,"repeatedRowKeyPattern");function Tx(e,n){let t=no(n),r=0;for(let i of Object.keys(e)){let o=i.match(t);if(!o)continue;let a=Number(o[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}s(Tx,"countRepeatedRows");function QM(e,n,t){let r=no(n);for(let[i,o]of Object.entries(e)){let a=i.match(r);if(!(!a||Number(a[1])!==t)&&o!=null&&!(typeof o=="string"&&o.trim()==="")&&!(Array.isArray(o)&&o.length===0))return!0}return!1}s(QM,"repeatedRowHasData");function ZM(e){return e.endsWith(".count")?e.slice(0,-6):e}s(ZM,"readKeyOf");function $x(e){return{sections:e,fields:[]}}s($x,"hiddenSectionsOnly");function XM(e,n,t){for(let r of e.fields)n.add(r.key);for(let r of e.groups??[])for(let i of r.fields)n.add(i.key);for(let r of e.computed??[])n.add(r.key);for(let r of e.repeated??[])t.add(r.key);for(let r of e.subsections??[])XM(r,n,t)}s(XM,"collectKeys");function eq(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;XM(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(no)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(eq,"restrictedSectionsOf");function nq(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(nq,"matchesKey");function D8(e,n){return n.find(t=>nq(e,t))??null}s(D8,"hiddenSectionOfKey");function F8(e,n){for(let t=e;;){if(nq(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(F8,"fieldOwnsKey");function L8(e,n){return n.find(t=>F8(e,t))??null}s(L8,"restrictedFieldOfKey");function M8(e,n){let t=D8(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=L8(e,n.fields);return r===null?null:{kind:"field",field:r}}s(M8,"hiddenOwnerOfKey");function uh(e,n){return M8(e,n)!==null}s(uh,"isKeyHidden");function q8(e,n,t,r,i){let o=[];r&&o.push({severity:"error",path:t,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((n.length===0||n.some(a)||new Set(n).size!==n.length)&&o.push({severity:"error",path:t,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 n)a(l)||i.has(l)||o.push({severity:"error",path:t,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(q8,"visibleToListIssues");function tq(e,n,t){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...q8(c.id,h,`${u}.visibleTo`,p,t));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=eq(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=$x(p);for(let w of _n(c)){let k=ZM(w);(uh(w,h)||uh(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&&uh(c.sameAs.source,$x(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((b,E)=>l(b,`${u}.groups[${y}].fields[${E}]`,w))}),c.repeated?.forEach((k,y)=>{a(k.itemVisibleIf,`${u}.repeated[${y}].itemVisibleIf`,w),k.itemTemplate.forEach((b,E)=>l(b,`${u}.repeated[${y}].itemTemplate[${E}]`,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 n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(tq,"sectionVisibilityIssues");var Qr="#";var rq=s(e=>{let n=ib.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),$r={firstName:rq("persons.firstName"),lastName:rq("persons.lastName")};function iq(e,n){let t={firstName:[],lastName:[]},r=`$${e}`;for(let i of n)if(!(i.kind!=="fieldMap"||i.target!==r))for(let{from:o,to:a}of i.mappings??[])a===$r.firstName?t.firstName.push(o):a===$r.lastName&&t.lastName.push(o);return t}s(iq,"personNameKeys");function oq(e){return[...e.firstName,...e.lastName]}s(oq,"personNameKeyList");function sq(e){return e.firstName.length>0||e.lastName.length>0}s(sq,"hasPersonName");function La(e,n=[],t){let r=[];return e.forEach((i,o)=>{let a=[...n,o];r.push({section:i,path:a,parentId:t});for(let l of La(i.subsections??[],a,i.id))r.push(l)}),r}s(La,"walkSections");function K8(e,n){for(let t of e.fields)if(t.key===n)return t;for(let t of e.groups??[])for(let r of t.fields)if(r.key===n)return r;for(let t of e.repeated??[])for(let r of t.itemTemplate)if(r.key===n)return r;return null}s(K8,"findFieldInSection");function aq(e,n){for(let t of La(e.sections)){let r=K8(t.section,n);if(r)return{section:t.section,field:r}}return null}s(aq,"findField");var j8=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],V8=["blue","rose","amber","violet","teal","emerald","slate"];function lq(e){return j8.includes(e)}s(lq,"isBucketIconName");function dq(e){return V8.includes(e)}s(dq,"isBucketColorName");var B8="__clear__";function cq(e){return e===""?"empty":e===B8?"reserved":null}s(cq,"selectOptionValueDefect");var Rx=bF.docRef.allowedMime;function gq(e,n={}){let t=fa(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(I,O){if(i.has(I))return;i.add(I);let j=o.get(I.id);j&&j!==I?r.push({severity:"error",path:`sections[${O.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${I.id}' ist mehrfach deklariert.`,en:`Section id '${I.id}' is declared more than once.`}}):o.set(I.id,I);let N=`sections[${O.join(".")}]`;I.fields.forEach((z,le)=>{Ma(a,z.key,`${N}.fields[${le}]`,"duplicate.field-key",r),l.add(z.key),u.set(z.key,z),c.set(z.key,Ox(z)),z.externalFlag&&(z.type!=="boolean"&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${z.key}' muss den Typ 'boolean' haben (ist '${z.type}').`,en:`External flag '${z.key}' must be type 'boolean' (got '${z.type}').`}}),z.reviewRequired!==void 0&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"review.on-flag",message:{de:`Externes Flag '${z.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 '${z.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),z.notice!==void 0&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${z.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${z.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),z.defaultValue==null&&r.push({severity:"error",path:`${N}.fields[${le}]`,code:"flag.missing-default",message:{de:`Externes Flag '${z.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${z.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...fq(z,`${N}.fields[${le}]`)),r.push(...uq(z,`${N}.fields[${le}]`))}),I.groups?.forEach((z,le)=>{z.fields.forEach((ce,De)=>{Ma(a,ce.key,`${N}.groups[${le}].fields[${De}]`,"duplicate.field-key",r),l.add(ce.key),u.set(ce.key,ce),c.set(ce.key,Ox(ce)),ce.externalFlag&&r.push({severity:"error",path:`${N}.groups[${le}].fields[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ce.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${ce.key}' must be a direct section field, not a group field.`}}),r.push(...fq(ce,`${N}.groups[${le}].fields[${De}]`)),r.push(...uq(ce,`${N}.groups[${le}].fields[${De}]`))})}),I.repeated?.forEach((z,le)=>{z.itemTemplate.forEach((ce,De)=>{Ma(a,ce.key,`${N}.repeated[${le}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(ce.key,Ox(ce)),ce.externalFlag&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${ce.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${ce.key}' must be a direct section field, not a repeated item field.`}}),ce.export&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"export.in-repeated",message:{de:`Feld '${ce.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${ce.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),ce.sameAs&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${ce.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${ce.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),ce.reviewRequired!==void 0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"review.in-repeated",message:{de:`Feld '${ce.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 '${ce.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.`}}),ce.notice!==void 0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.notice-in-repeated",message:{de:`Feld '${ce.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 '${ce.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),ce.type==="docRef"&&ce.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${N}.repeated[${le}].itemTemplate[${De}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${ce.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${ce.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),I.computed?.forEach(z=>{d.add(z.key),Ma(a,z.key,`${N}.computed[${z.key}]`,"duplicate.field-key",r),z.exportType==="consent"&&r.push({severity:"error",path:`${N}.computed[${z.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${z.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${z.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),z.export===!0&&z.exportType===void 0&&r.push({severity:"error",path:`${N}.computed[${z.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${z.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${z.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),I.subsections?.forEach((z,le)=>p(z,[...O,le]))}s(p,"visitRawSection"),e.sections.forEach((I,O)=>p(I,[O]));let h=new Set;t.effects.forEach((I,O)=>{Ma(h,I.id,`effects[${O}]`,"duplicate.effect-id",r)});let w=new Set;t.outcomes.forEach((I,O)=>{Ma(w,I.id,`outcomes[${O}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((I,O)=>{I.output.effectRefs?.forEach((j,N)=>{h.has(j.effect)||r.push({severity:"error",path:`outcomes[${O}].output.effectRefs[${N}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${I.id}' verweist auf den unbekannten Effekt '${j.effect}'.`,en:`Outcome '${I.id}' references unknown effect '${j.effect}'.`}})})}),t.outcomes.forEach((I,O)=>{I.output.fields?.forEach((j,N)=>{aq(t,j.path)||r.push({severity:"error",path:`outcomes[${O}].output.fields[${N}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${I.id}' verweist auf das unbekannte Feld '${j.path}'.`,en:`Outcome '${I.id}' references unknown field '${j.path}'.`}})})});let k=new Set;for(let I of La(t.sections))for(let O of I.section.repeated??[])k.add(`${O.key}.count`);for(let I of k)(a.has(I)||d.has(I))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${I}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${I}' 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:n.stageKeys};r.push(...NN(e)),r.push(...tq(e,t,n.visibleToKeys)),r.push(...gC(e)),r.push(...ON(e,n.stageKeys));for(let I of La(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.visibleIf&&(Rr(O.visibleIf,`${j}.visibleIf`,y,!1,r),qa(O.visibleIf,`${j}.visibleIf`,c,r)),O.fields.forEach((N,z)=>Ix(N,`${j}.fields[${z}]`,y,!1,c,r)),O.groups?.forEach((N,z)=>{N.visibleIf&&(Rr(N.visibleIf,`${j}.groups[${z}].visibleIf`,y,!1,r),qa(N.visibleIf,`${j}.groups[${z}].visibleIf`,c,r)),N.fields.forEach((le,ce)=>Ix(le,`${j}.groups[${z}].fields[${ce}]`,y,!1,c,r))}),O.repeated?.forEach((N,z)=>{N.itemVisibleIf&&(Rr(N.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,y,!0,r),qa(N.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,c,r)),N.itemTemplate.forEach((le,ce)=>Ix(le,`${j}.repeated[${z}].itemTemplate[${ce}]`,y,!0,c,r)),N.effects?.forEach((le,ce)=>{le.when&&Rr(le.when,`${j}.repeated[${z}].effects[${ce}].when`,y,!0,r)})}),O.computed?.forEach((N,z)=>Rr(N.expression,`${j}.computed[${z}].expression`,y,!1,r))}t.effects.forEach((I,O)=>{I.when&&Rr(I.when,`effects[${O}].when`,y,!1,r)}),t.outcomes.forEach((I,O)=>{Rr(I.when,`outcomes[${O}].when`,y,!1,r)});let b=new Set(t.outcomes.map(I=>I.id));function E(I,O){I.requiredFor&&I.requiredFor.forEach((j,N)=>{b.has(j)||r.push({severity:"error",path:`${O}.requiredFor[${N}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${I.key}": requiredFor verweist auf das unbekannte Ergebnis "${j}"`,en:`field "${I.key}": requiredFor references unknown outcome "${j}"`}})})}s(E,"checkRequiredFor");for(let I of La(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.fields.forEach((N,z)=>E(N,`${j}.fields[${z}]`)),O.groups?.forEach((N,z)=>{N.fields.forEach((le,ce)=>E(le,`${j}.groups[${z}].fields[${ce}]`))}),O.repeated?.forEach((N,z)=>{N.itemTemplate.forEach((le,ce)=>E(le,`${j}.repeated[${z}].itemTemplate[${ce}]`))})}function T(I,O){let j=s((N,z)=>{let le=(N.type==="docRef"?N.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!Rx.includes(Ee));le.length>0&&r.push({severity:"error",path:z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${N.key}' erlaubt ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Rx.join(", ")}).`,en:`Field '${N.key}' allows ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Rx.join(", ")}).`}});let ce=N.type==="docRef"?N.docRefConstraints?.minFiles:void 0;if(ce!==void 0){let Ee=N.docRefConstraints?.multiple===!0,mn=typeof ce=="number"&&Number.isInteger(ce)&&ce>=2;(!Ee||!mn)&&r.push({severity:"error",path:z,code:"config.docref-min-files",message:Ee?{de:`Feld '${N.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(ce)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${N.key}' sets docRefConstraints.minFiles to ${JSON.stringify(ce)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${N.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${N.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}N.multiple===!0&&N.type!=="enum"&&r.push({severity:"error",path:z,code:"config.multiple-non-enum",message:{de:`Feld '${N.key}' setzt multiple: true, hat aber den Typ '${N.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(N.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${N.key}' sets multiple: true but is type '${N.type}' \u2014 only 'enum' supports multi-select.`+(N.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),N.presentation==="yesNo"&&N.type!=="boolean"&&r.push({severity:"error",path:z,code:"config.yesno-non-boolean",message:{de:`Feld '${N.key}' setzt presentation: 'yesNo', hat aber den Typ '${N.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${N.key}' sets presentation: 'yesNo' but is type '${N.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),N.presentation==="yesNo"&&N.defaultValue!=null&&r.push({severity:"error",path:z,code:"config.yesno-default",message:{de:`Feld '${N.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 '${N.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...G8(N,z)),typeof N.minSelections=="number"&&typeof N.maxSelections=="number"&&N.minSelections>N.maxSelections&&r.push({severity:"error",path:z,code:"config.min-gt-max-selections",message:{de:`Feld '${N.key}' hat minSelections (${N.minSelections}) > maxSelections (${N.maxSelections}).`,en:`Field '${N.key}' has minSelections (${N.minSelections}) > maxSelections (${N.maxSelections}).`}}),r.push(...z8(N,z));let De=N.enumRef;De!==void 0&&r.push({severity:"error",path:`${z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${N.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 '${N.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(N.enumOptions??[]).forEach((Ee,mn)=>{let Qe=cq(Ee);Qe!==null&&r.push({severity:"error",path:`${z}.enumOptions[${mn}]`,code:"config.enum-option-value",message:{de:Qe==="empty"?`Feld '${N.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 '${N.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Qe==="empty"?`Field '${N.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 '${N.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(N.attachments??[]).forEach((Ee,mn)=>{if("storageId"in Ee){r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${N.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 '${N.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 Qe=Ee.fileKey!==void 0&&Ee.fileKey!=="",Sn=Ee.url!==void 0&&Ee.url!=="";Qe===Sn&&r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${N.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Qe&&Sn?"beide":"keines"}).`,en:`Field '${N.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Qe&&Sn?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${z}.attachments[${mn}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${N.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${N.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");I.fields.forEach((N,z)=>j(N,`${O}.fields[${z}]`)),I.groups?.forEach((N,z)=>{N.fields.forEach((le,ce)=>j(le,`${O}.groups[${z}].fields[${ce}]`))}),I.repeated?.forEach((N,z)=>{N.itemTemplate.forEach((le,ce)=>{let De=`${O}.repeated[${z}].itemTemplate[${ce}]`;j(le,De),le.type==="consent"&&r.push({severity:"error",path:De,code:"config.consent-in-repeated",message:{de:`Feld '${le.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${le.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),I.subsections?.forEach((N,z)=>T(N,`${O}.subsections[${z}]`))}s(T,"visitFieldConfig"),e.sections.forEach((I,O)=>T(I,`sections[${O}]`)),e.effects.forEach((I,O)=>{if(I.kind==="person"){r.push(...hq(I,e.effects,`effects[${O}]`,j=>l.has(j)));return}I.kind==="organization"&&I.nameFrom?.forEach((j,N)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nameFrom[${N}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${I.id}': nameFrom verweist auf das unbekannte Feld '${j}'.`,en:`Effect '${I.id}' nameFrom references unknown field '${j}'.`}})})});let R=s((I,O)=>{if(I.kind!=="person"&&I.kind!=="organization")return;let j=I.display;if(!j){r.push({severity:"error",path:`${O}.display`,code:"display.missing",message:{de:`Effekt '${I.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${I.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}lq(j.icon)||r.push({severity:"error",path:`${O}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${I.id}': display.icon '${j.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${I.id}' display.icon '${j.icon}' is not a known bucket icon.`}}),dq(j.color)||r.push({severity:"error",path:`${O}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${I.id}': display.color '${j.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${I.id}' display.color '${j.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((I,O)=>R(I,`effects[${O}]`));let D=new Set,L=s(I=>{I.kind==="person"?D.add(I.bucket):I.kind==="organization"&&D.add(I.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(L);let _=new Set,v=s(I=>{for(let O of I)O.repeated?.forEach(j=>j.effects?.forEach(N=>L(N))),v(O.subsections??[])},"collectRepeatedBuckets");v(e.sections);let P=s((I,O)=>{D.size!==0&&I.forEach((j,N)=>{j.bucket===void 0||D.has(j.bucket)||r.push({severity:"error",path:`${O}[${N}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${j.key}' geh\xF6rt zum Bucket '${j.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${j.key}' belongs to bucket '${j.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),A=s((I,O)=>{if(_.has(I))return;_.add(I);let j=`sections[${O.join(".")}]`;P(I.fields,`${j}.fields`),I.groups?.forEach((N,z)=>P(N.fields,`${j}.groups[${z}].fields`)),I.repeated?.forEach((N,z)=>P(N.itemTemplate,`${j}.repeated[${z}].itemTemplate`)),I.subsections?.forEach((N,z)=>A(N,[...O,z]))},"visitBucketSection");e.sections.forEach((I,O)=>A(I,[O]));let M=e.effects.flatMap((I,O)=>I.kind==="person"&&I.subject===!0?[{e:I,i:O}]:[]);M.length>1&&M.slice(1).forEach(({e:I,i:O})=>{r.push({severity:"error",path:`effects[${O}].subject`,code:"subject.duplicate",message:{de:`Effekt '${I.id}' deklariert subject:true, aber '${M[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${I.id}' declares subject:true, but '${M[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((I,O)=>{if(!(I.kind!=="person"||I.nationalityFrom===void 0)){if(I.subject!==!0){r.push({severity:"error",path:`effects[${O}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${I.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 '${I.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(I.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${O}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${I.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${I.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}I.nationalityFrom.forEach((j,N)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nationalityFrom[${N}]`,code:"nationality.unknown-field",message:{de:`Effekt '${I.id}': nationalityFrom verweist auf das unbekannte Feld '${j}'.`,en:`Effect '${I.id}' nationalityFrom references unknown field '${j}'.`}})})}});let U=e.effects.flatMap((I,O)=>I.kind==="person"&&I.contractParty!==void 0?[{e:I,i:O,decl:I.contractParty}]:[]);if(U.length>0){let I=new Map;U.forEach(({e:j,i:N})=>{let z=I.get(j.bucket);if(z===void 0){I.set(j.bucket,j.id);return}r.push({severity:"error",path:`effects[${N}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${j.id}' deklariert eine Vertragspartei auf Bucket '${j.bucket}', aber '${z}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${j.id}' declares a contract party on bucket '${j.bucket}', but '${z}' already does. A bucket is at most one contract party.`}})});let O=U.filter(({decl:j})=>j.role==="beneficiary");O.slice(1).forEach(({e:j,i:N})=>{r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${j.id}' deklariert contractParty.role 'beneficiary', aber '${O[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${j.id}' declares contractParty.role 'beneficiary', but '${O[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),O.forEach(({e:j,i:N})=>{j.subject!==!0&&r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${j.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 '${j.id}' setzen.`,en:`Effect '${j.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 '${j.id}'.`}})}),M.forEach(({e:j,i:N})=>{let z=j.contractParty?.role;z!==void 0&&z!=="beneficiary"&&r.push({severity:"error",path:`effects[${N}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${j.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${z}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${j.id}' is the application subject but declares contractParty.role '${z}'. The application subject is the contract beneficiary.`}})}),U.some(({decl:j})=>j.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((I,O)=>{I.kind==="fieldMap"&&I.mappings.forEach((j,N)=>{a.has(j.from)||r.push({severity:"error",path:`effects[${O}].mappings[${N}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${I.id}': fieldMap from '${j.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${I.id}' fieldMap from '${j.from}' references unknown field.`}})})});for(let[I,O]of u){if(!O.sameAs)continue;let j=`fields[${I}].sameAs`,N=u.get(O.sameAs.source);N===void 0||O.sameAs.source===I?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:O.sameAs.source===I?`Feld '${I}': sameAs.source verweist auf sich selbst.`:`Feld '${I}': sameAs.source verweist auf das unbekannte Feld '${O.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:O.sameAs.source===I?`Field '${I}' sameAs.source references itself.`:`Field '${I}' sameAs.source references unknown field '${O.sameAs.source}' (must be a top-level or group field).`}}):N.type!==O.type?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${I}' (${O.type}): sameAs.source '${O.sameAs.source}' hat einen anderen Typ (${N.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${I}' (${O.type}) sameAs.source '${O.sameAs.source}' has a different type (${N.type}) \u2014 the mirror must be shape-identical.`}}):N.sameAs&&r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${I}': sameAs.source '${O.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${I}' sameAs.source '${O.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let z=u.get(O.sameAs.toggle);(z===void 0||z.type!=="boolean")&&r.push({severity:"error",path:`${j}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:z===void 0?`Feld '${I}': sameAs.toggle verweist auf das unbekannte Feld '${O.sameAs.toggle}'.`:`Feld '${I}': sameAs.toggle '${O.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${z.type}').`,en:z===void 0?`Field '${I}' sameAs.toggle references unknown field '${O.sameAs.toggle}'.`:`Field '${I}' sameAs.toggle '${O.sameAs.toggle}' must be type 'boolean' (got '${z.type}').`}}),O.required===!0&&r.push({severity:"error",path:`fields[${I}].required`,code:"config.sameas-static-required",message:{de:`Feld '${I}' 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: "${O.sameAs.toggle} != true" verwenden.`,en:`Field '${I}' 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: "${O.sameAs.toggle} != true".`}})}{let I=new Map;e.effects.forEach(O=>I.set(O.id,O.kind)),e.effects.forEach((O,j)=>{if(O.kind!=="shareValue")return;[["from",O.from],["to",O.to]].forEach(([le,ce])=>{let De=I.get(ce.slice(1));De!==void 0&&De!=="person"&&De!=="organization"&&r.push({severity:"error",path:`effects[${j}].${le}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${O.id}': shareValue ${le} '${ce}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${De}').`,en:`Effect '${O.id}' shareValue ${le} '${ce}' must reference a person/organization effect (got '${De}').`}})});let N=O.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===N&&le.mappings.some(ce=>ce.to===O.field)||le.kind==="shareValue"&&le.id!==O.id&&le.to.slice(1)===N&&le.field===O.field)||r.push({severity:"error",path:`effects[${j}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${O.id}' teilt das Feld '${O.field}' aus '${O.from}', aber kein fieldMap mit Ziel '${O.from}' bildet auf '${O.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${O.id}' shares field '${O.field}' from '${O.from}', but no fieldMap targeting '${O.from}' maps to '${O.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((I,O)=>{I.kind==="person"&&I.bucket.includes(Qr)&&r.push({severity:"error",path:`effects[${O}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': bucket '${I.bucket}' darf '${Qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' bucket '${I.bucket}' must not contain '${Qr}' (reserved for the per-row namespace).`}}),I.kind==="organization"&&I.orgKind.includes(Qr)&&r.push({severity:"error",path:`effects[${O}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': orgKind '${I.orgKind}' darf '${Qr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' orgKind '${I.orgKind}' must not contain '${Qr}' (reserved for the per-row namespace).`}})});let oe=new Set;function Q(I,O){I.repeated?.forEach((j,N)=>{let z=j.effects??[];if(z.length>0){let le=`${O}.repeated[${N}]`,ce=new Set(z.map(se=>se.id)),De=new Set(j.itemTemplate.map(se=>se.key)),Ee=(j.uniqueBy?.length??0)>0,mn=s(se=>se.startsWith("$item.")?De.has(se.slice(6)):l.has(se),"resolvesName"),Qe=s(se=>se.startsWith("$item.")?De.has(se.slice(6)):a.has(se),"resolvesFrom"),Sn=s(se=>{let jn=se.slice(1);return ce.has(jn)||h.has(jn)},"resolvesRef");z.forEach((se,jn)=>{let hn=`${le}.effects[${jn}]`;if(h.has(se.id)||oe.has(se.id)?r.push({severity:"error",path:hn,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${se.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${se.id}' is declared more than once.`}}):oe.add(se.id),se.kind==="person"||se.kind==="organization"){R(se,hn),se.kind==="person"&&se.subject===!0&&r.push({severity:"error",path:`${hn}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${se.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 '${se.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.`}}),se.kind==="person"&&se.nationalityFrom!==void 0&&r.push({severity:"error",path:`${hn}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${se.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${se.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),se.kind==="person"&&se.contractParty!==void 0&&r.push({severity:"error",path:`${hn}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${se.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 '${se.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:le,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${j.key}' hat einen Parteien erzeugenden Effekt '${se.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${j.key}' has a party-creating effect '${se.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Fe=se.kind==="person"?se.bucket:se.orgKind;Fe.includes(Qr)&&r.push({severity:"error",path:`${hn}.${se.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${se.id}' der Wiederholung: ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' darf '${Qr}' nicht enthalten.`,en:`Repeated effect '${se.id}' ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${Qr}'.`}}),se.kind==="person"&&r.push(...hq(se,z,hn,mn)),se.kind==="organization"&&se.nameFrom?.forEach((Be,Pt)=>{mn(Be)||r.push({severity:"error",path:`${hn}.nameFrom[${Pt}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${se.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${se.id}' nameFrom references unknown field '${Be}'.`}})}),se.identity?.strategy==="keyed"&&se.identity.keyFrom.forEach((Be,Pt)=>{Qe(Be)||r.push({severity:"error",path:`${hn}.identity.keyFrom[${Pt}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${se.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Be}'.`,en:`Repeated effect '${se.id}' identity.keyFrom references unknown field '${Be}'.`}})})}else if(se.kind==="relationship"){if([["from",se.from],["to",se.to]].forEach(([Fe,Be])=>{Sn(Be)||r.push({severity:"error",path:`${hn}.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${se.id}' der Wiederholung: ${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${se.id}' ${Fe} references unknown effect '${Be}'.`}})}),se.meta)for(let[Fe,Be]of Object.entries(se.meta))typeof Be=="string"&&Be.startsWith("$")&&!Sn(Be)&&r.push({severity:"error",path:`${hn}.meta.${Fe}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${se.id}' der Wiederholung: meta.${Fe} verweist auf den unbekannten Effekt '${Be}'.`,en:`Repeated relationship '${se.id}' meta.${Fe} references unknown effect '${Be}'.`}})}else se.kind==="fieldMap"?(Sn(se.target)||r.push({severity:"error",path:`${hn}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${se.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${se.target}'.`,en:`Repeated fieldMap '${se.id}' target references unknown effect '${se.target}'.`}}),se.mappings.forEach((Fe,Be)=>{Qe(Fe.from)||r.push({severity:"error",path:`${hn}.mappings[${Be}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${se.id}' der Wiederholung: from '${Fe.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${se.id}' from '${Fe.from}' references unknown field.`}})})):se.kind==="shareValue"&&r.push({severity:"error",path:hn,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${se.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${se.id}': shareValue is not supported inside repeated row effects.`}})})}}),I.subsections?.forEach((j,N)=>Q(j,`${O}.subsections[${N}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((I,O)=>Q(I,`sections[${O}]`));let re=HM(t.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(...U8(e)),r}s(gq,"validateForm");function U8(e){let n={...e,effects:e.effects.map(yq),sections:e.sections.map(wq),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return qp(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:sk(t)}))}s(U8,"missingTranslationIssues");function yq(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(yq,"withoutSubjectFlag");function wq(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(yq)})),subsections:e.subsections?.map(wq)}}s(wq,"withoutRowSubjectFlags");function uq(e,n){let t=e.reviewRequired;return t===void 0||t===!0?[]:[{severity:"error",path:n,code:"review.shape",message:{de:`Feld '${e.key}' setzt reviewRequired auf ${JSON.stringify(t)} \u2014 erlaubt ist nur true; ein nicht pr\xFCfpflichtiges Feld l\xE4sst die Angabe weg.`,en:`Field '${e.key}' sets reviewRequired to ${JSON.stringify(t)} \u2014 only true is allowed; a field that needs no review omits it.`}}]}s(uq,"reviewRequiredShapeIssues");function fq(e,n){if(!e.export)return[];let t=[];return e.type==="docRef"&&t.push({severity:"error",path:n,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&&t.push({severity:"error",path:n,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.`}}),t}s(fq,"exportGateIssues");function Ma(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${pq(r,"de")} '${n}'`,en:`Duplicate ${pq(r,"en")}: '${n}'`}}):e.add(n)}s(Ma,"reportIfDup");function pq(e,n){let t=s((r,i)=>n==="de"?r:i,"label");switch(e){case"duplicate.section-id":return t("Abschnitts-ID","section id");case"duplicate.field-key":return t("Feldschl\xFCssel","field key");case"duplicate.effect-id":return t("Effekt-ID","effect id");case"duplicate.outcome-id":return t("Ergebnis-ID","outcome id");case"ref.unknown-required-for-outcome":return t("requiredFor-Ergebnis","requiredFor outcome");default:return e}}s(pq,"labelForCode");function Ix(e,n,t,r,i,o){e.visibleIf&&(Rr(e.visibleIf,`${n}.visibleIf`,t,r,o),qa(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(Rr(e.requiredIf,`${n}.requiredIf`,t,r,o),qa(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(Rr(e.disabledIf,`${n}.disabledIf`,t,r,o),qa(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&Rr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s(Ix,"checkFieldAsts");function Ox(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Ox,"gatingMeta");function qa(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(mq(o.left,o.right,o.op,n,t,r),mq(o.right,o.left,o.op,n,t,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(qa,"checkGatingExpr");function mq(e,n,t,r,i,o){if(e.kind!=="ident")return;let a=i.get(e.path);if(a){if(a.isConsent&&n.kind==="bool"&&n.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||n.kind!=="null"&&n.kind==="bool"&&(a.isYesNo&&t==="=="||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 '${t}' mit einem Bool-Literal. In dreiwertiger Logik ist 'undefined ${t} ${n.value}' ${t==="=="?"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 '${t}'. In three-valued logic, 'undefined ${t} ${n.value}' is ${t==="=="?"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(mq,"inspectEqualityOperand");function Rr(e,n,t,r,i){i.push(...PN(e,t.declaredContext,n)),i.push(...Dp(e,t.stageKeys,n));for(let o of _n(e))t.known.has(o)||tk(o)||r&&o.startsWith("$item.")||i.push({severity:"error",path:n,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(Rr,"checkAst");function hq(e,n,t,r){let i=[];e.nameFrom!==void 0&&i.push({severity:"error",path:`${t}.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 ${$r.firstName} / ${$r.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${$r.firstName} / ${$r.lastName}. Remove nameFrom.`}});let o=iq(e.id,n);sq(o)||i.push({severity:"error",path:t,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${$r.firstName} oder ${$r.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${$r.firstName} or ${$r.lastName} \u2014 the person would get no name.`}});for(let a of oq(o))r(a)||i.push({severity:"error",path:t,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(hq,"personNameIssues");function G8(e,n){let t=[],r=e.required===!0||e.requiredIf!==void 0;return e.type==="consent"&&(e.defaultValue!=null&&t.push({severity:"error",path:n,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&&t.push({severity:"error",path:n,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||t.push({severity:"error",path:n,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"&&t.push({severity:"warning",path:n,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'.`}}),t}s(G8,"consentConfigIssues");function z8(e,n){let t=e.exclusiveOptions;if(t===void 0)return[];let r=s((a,l)=>[{severity:"error",path:n,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(t)||t.length===0||t.some(a=>typeof a!="string"))return r(`Feld '${e.key}' setzt exclusiveOptions auf ${JSON.stringify(t)} \u2014 erwartet ist eine nicht leere Liste von Optionsschl\xFCsseln.`,`Field '${e.key}' sets exclusiveOptions to ${JSON.stringify(t)} \u2014 it must be a non-empty list of option keys.`);let i=e.enumOptions??[],o=t.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(t).size!==t.length?r(`Feld '${e.key}' nennt eine Option in exclusiveOptions doppelt.`,`Field '${e.key}' names an option twice in exclusiveOptions.`):[]}s(z8,"exclusiveOptionIssues");var W8="blocked";function kq(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=wn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(Y8(i))return r.id===W8?null:r.id}return null}s(kq,"resolveActiveOutcome");function Y8(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(Y8,"truthy");function bq(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(bq,"isScalar");function H8(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(bq(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))bq(a)&&(n[`${r}.${o}`]=a)}J8(e,n,t)}s(H8,"mergeRecord");function J8(e,n,t){let r=new Set(t);for(let i of Object.keys(e)){let o=i.indexOf("[");if(o<=0)continue;let a=i.slice(0,o);no(a).test(i)&&r.add(a)}for(let i of r){let o=Tx(e,i),a=0;for(let l=0;l<o;l++)QM(e,i,l)&&a++;n[`${i}.count`]=a}}s(J8,"mergeRepeatedCounts");function vq(e,n,t){let r={...t};return H8(e,r,n),r}s(vq,"flattenValues");function _x(e,n,t){return{code:e,fieldKey:n,text:t}}s(_x,"submitIssue");function xq(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(xq,"truthyEval");function Sq(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 n=e;if("storageId"in n)return!(typeof n.storageId=="string"&&n.storageId.trim()!=="");let t=n;return!t.street?.trim()||!t.hausnr?.trim()||!t.plz?.trim()||!t.ort?.trim()||!t.land?.trim()}return!1}s(Sq,"isEmptyValue");function Q8(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=xq(wn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(Q8,"fieldIsLiveRequired");function Z8(e,n,t){return Aq(e,n,t).evalCtx}s(Z8,"buildSubmitEvalContext");function Aq(e,n,t){let r=X8(e),i=Object.keys(n).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[w,k]of Object.entries(n))(r(w)===null||o.has(w))&&(l[w]=k);let d=Eq(e,l,t),c=new Set,u=new Set;$q(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]=n[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(Aq,"splitWithContext");function X8(e){let n=new Map,t=[];for(let r of ph(e.sections)){for(let i of r.fields)n.set(i.key,i);for(let i of r.groups??[])for(let o of i.fields)n.set(o.key,o);for(let i of r.repeated??[])t.push({key:i.key,pattern:no(i.key),items:new Map(i.itemTemplate.map(o=>[o.key,o]))})}return r=>{let i=n.get(r);if(i!==void 0)return{kind:"field",field:i};for(let o of t){let a=o.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:o.key,field:o.items.get(a[2])}}return null}}s(X8,"fieldOwnership");function Eq(e,n,t){let r=[];for(let o of ph(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=vq(n,r,t);for(let o of ph(e.sections))for(let a of o.computed??[])try{i[a.key]=wn(a.expression,{values:i})}catch{}return i}s(Eq,"rawEvalContext");function Tq(e,n,t){let{values:r,defaulted:i}=eZ(e,n,t),o=Aq(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(Tq,"splitDraftValues");function eZ(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of ph(e.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||n[d.key]!=null||r?.(d.key))continue;a??=Eq(e,n,t);let c;try{c=wn(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(eZ,"applyFieldDefaults");function ph(e){let n=[],t=s(r=>{n.push(r);for(let i of r.subsections??[])t(i)},"walk");for(let r of e)t(r);return n}s(ph,"walkSectionsDeep");function nZ(e,n,t,r=!1){if(Sq(n))return null;let i=t.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,n,{state:{values:{},computed:{}},testMode:r});return o.length>0?o[0].message:null}s(nZ,"fieldFormatIssue");function tZ(e,n){return Sq(n)||e.type==="consent"&&n!==!0}s(tZ,"isUnanswered");function fh(e,n){if(!e)return!0;try{return xq(wn(e,{values:n}))}catch{return!1}}s(fh,"isVisibleUnder");function $q(e,n,t,r){let i=s(o=>{if(fh(o.visibleIf,n)){for(let a of o.fields)fh(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(fh(a.visibleIf,n))for(let l of a.fields)fh(l.visibleIf,n)&&t(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($q,"forEachVisibleField");function Rq(e,n,t,r={}){let i=Z8(e,n,t),o=[],a=kq(e,i);a===null&&r.requireOutcome!==!1&&o.push(_x("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 $q(e,i,d=>{let c=n[d.key];if(tZ(d,c)){!l.has(d.type)&&Q8(d,i,a)&&o.push(_x("required",d.key,Rl([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=nZ(d,c,r.registry,r.testMode===!0);u!==null&&o.push(_x("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(Rq,"checkSubmittable");function Iq(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=fa(e),r=[];for(let i of n){let o=i.prefill??{};if(!$N(e,i.env))continue;let a=IN(e,i.env),{visible:l}=Tq(t,o,a),d=Rq(t,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:Rl([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(Iq,"validateScenarios");function mh(e){return e.filter(n=>(n.severity??"error")==="error")}s(mh,"blockingIssues");function hh(e,n={}){return[...gq(e,n),...Iq(e)]}s(hh,"runFormValidators");function gh(e){return mh(e)}s(gh,"blockingFormErrors");function Oq(e,n,t){return UC(e,n,t)}s(Oq,"runWorkflowValidators");function _q(e){return mh(e)}s(_q,"blockingWorkflowErrors");var rZ=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var Pq={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","reads","requiresOneOf","view"]},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"]}},yt={id:m.string(),label:Ji,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())},iZ=m.object({...yt,type:m.literal("join")}),oZ=m.object({...yt,type:m.literal("end")}),sZ=m.object({...yt,type:m.literal("eventTrigger")}),aZ=m.object({...yt,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),lZ=m.object({...yt,type:m.literal("roleAssign")}),dZ=m.object({...yt,type:m.literal("setFlag")}),cZ=m.object({...yt,type:m.literal("if"),condition:m.optional(m.any())}),uZ=m.object({...yt,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),fZ=m.object({...yt,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),pZ=m.object({...yt,type:m.literal("decision"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),reads:m.optional(m.any()),requiresOneOf:m.optional(m.any()),view:m.optional(m.any()),formView:m.optional(m.any())}),mZ=m.object({...yt,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),hZ=m.object({...yt,type:m.literal("waitlist")}),gZ=m.object({...yt,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),yZ=m.object({...yt,type:m.literal("collectPayment")}),wZ=m.object({...yt,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())}),xqe=m.union(iZ,oZ,sZ,aZ,lZ,dZ,cZ,uZ,fZ,pZ,mZ,hZ,gZ,yZ,wZ);function Nq(e){let n=[];return e.forEach((t,r)=>{if(t===null||typeof t!="object"||Array.isArray(t)){n.push(`graph.nodes[${r}]: a node must be an object`);return}let i=t,o=`graph.nodes[${r}]${typeof i.id=="string"?` (${i.id})`:""}`;(typeof i.id!="string"||i.id==="")&&n.push(`${o}: \`id\` must be a non-empty string`);let a=i.type;if(typeof a!="string"||!(a in Pq)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=Pq[a],d=new Set(["id","type","label",...rZ,...l.required,...l.optional]);for(let c of Object.keys(i))d.has(c)||n.push(`${o}: \`${c}\` is not a field of a ${a} node. Delete the line.`)}),n}s(Nq,"workflowNodeEnvelopeIssues");var Cq=s(e=>e,"asEffectId"),to=s(e=>e,"asOutcomeId"),Ka=s(e=>e,"asSectionId"),ot=s(e=>e,"asFieldKey");var Ir=["string","boolean","consent","date","enum","email","tel","address","docRef"],ec=["person","organization","relationship","fieldMap"],ro=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],ja=["fresh","keyed","manual"];function is(e,n,t,r){if(e===void 0||e===""){if(n!==void 0&&n!=="")throw new Error(`${t}: ${r}-en needs ${r} too`);return}return dn(e,n,t,r)}s(is,"optionalLocalizedText");function Hn(e,n){if(!(e===void 0||e===""))try{On(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(Hn,"assertExpression");function nc(e){return Object.keys(e.smartforms??{})}s(nc,"carriedFormSlugs");function Px(e){let t=e.workflow?.graph?.nodes??[],r=[];for(let i of t){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(Px,"boundFormSlugs");function yh(e,n){let t=nc(e);if(n){if(!t.includes(n))throw new Error(`offer form: no smartform "${n}" in this bundle (have: ${t.join(", ")||"none"})`);return n}if(t.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(t.length>1)throw new Error(`offer form: bundle carries ${t.length} smartforms \u2014 pass --form <key> (one of: ${t.join(", ")})`);return t[0]}s(yh,"resolveFormSlug");function wh(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(wh,"getForm");function Ut(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(Ut,"walkSections");function lr(e,n){return Ut(e).find(t=>t.id===n)}s(lr,"findSection");function os(e,n){for(let t of Ut(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(os,"findField");function ss(e){let n=new Set;for(let t of Ut(e))t.fields.forEach(r=>n.add(r.key)),t.groups?.forEach(r=>r.fields.forEach(i=>n.add(i.key))),t.repeated?.forEach(r=>r.itemTemplate.forEach(i=>n.add(i.key))),t.computed?.forEach(r=>n.add(r.key));return n}s(ss,"allFieldKeys");function kZ(e){let n=dn(e.label,e.labelEn,"offer form add"),t={id:Ka("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:to("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(kZ,"buildSkeletonSmartForm");function kh(e,n){let{key:t,label:r}=n;if(nc(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=kZ({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(kh,"addForm");function Dq(e,n){if(!nc(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(Px(e).includes(n))throw new Error(`offer form rm: smartform "${n}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete e.smartforms[n],e.index.smartforms&&delete e.index.smartforms[n],n}s(Dq,"removeForm");function Fq(e,n){let t=wh(e,n.slug);if(n.label===void 0&&n.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(n.label==="")throw new Error("offer form set: --label cannot be empty");bn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(Fq,"setForm");function Lq(e,n){let t=e.workflow?.graph?.nodes;if(!Array.isArray(t))throw new Error(`${n}: the bundle carries no workflow graph (workflow.json)`);return t}s(Lq,"nodesOf");function Mq(e,n,t){let r=Lq(e,t),i=r.find(o=>o.id===n);if(i===void 0)throw new Error(`${t}: no node "${n}" (nodes: ${r.map(o=>o.id).join(", ")})`);return i}s(Mq,"nodeOf");function qq(e){return e.flatMap(n=>{if(n.type!=="form"||At(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s(qq,"creatingFormNodes");function Kq(e){return gh(hh(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(Kq,"formErrors");function bh(e){let n="offer workflow restamp-exports",t=Lq(e,n),r=[];for(let{node:i,slug:o}of qq(t)){let a=e.smartforms?.[o];if(a===void 0)throw new Error(`${n}: form node "${i.id}" binds smartForm "${o}", but the bundle carries no smartforms/${o}.json`);let l=a,d=Kq(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11362
11362
  ${d.join(`
11363
11363
  `)}`);let c=Tw(l),u=Array.isArray(i.formExports)?i.formExports.map(h=>h.key):null,p=i.formExports===void 0||Pe(i.formExports)!==Pe(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 t)if(i.type==="form"&&At(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(bh,"restampFormExports");function jq(e){let n=e.workflow?.graph?.nodes??[];return qq(n).flatMap(({node:t,slug:r})=>{if(t.formExports===void 0)return[];let i=e.smartforms?.[r];if(i===void 0)return[];let o=i;return Kq(o).length>0?[]:Pe(t.formExports)===Pe(Tw(o))?[]:[{node:t.id,form:r}]})}s(jq,"staleFormExports");var Nx=["string","number","boolean","date"];function Vq(e,n){let t="offer form field export";for(let r of Ut(e)){let i=[...r.fields,...(r.groups??[]).flatMap(a=>a.fields)].find(a=>a.key===n.key);if(i!==void 0){if(n.type!==void 0)throw new Error(`${t}: --type is for a computed field; "${n.key}" is an entered ${i.type} field and exports as its own type`);if(n.on&&!cp(i.type))throw new Error(`${t}: "${n.key}" is a ${i.type} field \u2014 that type has no exported value (export.invalid-type)`);if(n.on&&i.multiple===!0)throw new Error(`${t}: "${n.key}" is a multi-select \u2014 N picked options are no single leaf (export.multiple-enum)`);let a=i.export===!0,l=i;return n.on?l.export=!0:delete l.export,{kind:"field",before:a,after:n.on}}let o=(r.computed??[]).find(a=>a.key===n.key);if(o!==void 0){let a=o.export===!0,l=o;if(!n.on){if(n.type!==void 0)throw new Error(`${t}: --type goes with an export, not with --off`);return delete l.export,delete l.exportType,{kind:"computed",before:a,after:!1}}let d=n.type??o.exportType;if(d===void 0)throw new Error(`${t}: "${n.key}" is a computed field \u2014 name its type with --type (${Nx.join("|")}); an expression has none to infer`);if(!Nx.includes(d))throw new Error(`${t}: --type "${d}" is no computed export type (${Nx.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===n.key)))throw new Error(`${t}: "${n.key}" sits in a repeated block \u2014 a row value is no per-application leaf (export.in-repeated)`)}throw new Error(`${t}: the form has no field "${n.key}"`)}s(Vq,"setFieldExport");function Bq(e,n,t){let r="offer workflow node set-generator",i=Mq(e,n,r);if(ah(i)!=="resolver")throw new Error(`${r}: "${n}" 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=t.key.trim();if(a==="")throw new Error(`${r}: the ${t.kind} key is empty`);let l=oi(i),d=l!==null&&l.key===a&&l.kind===t.kind&&l.revision===void 0,c=!d&&"generatorStamp"in i;c&&delete i.generatorStamp,i.inputs={...i.inputs??{},[Un]:{kind:"literal",value:{kind:t.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(p=>p!==Un&&p!==Lt);return{before:l,after:{key:a,kind:t.kind},droppedStamp:c,keptParameterCells:u}}s(Bq,"setGeneratorPin");function Uq(e,n,t){let r="offer workflow node set-cockpit-fields",i=Mq(e,n,r),o=ah(i);if(o!=="resolver"&&o!=="template")throw new Error(`${r}: "${n}" fills no document from a generator or a Word template (${i.type==="governedDocument"?`production ${String(i.production)}`:String(i.type)})`);if(!(o==="resolver"?oi(i)!==null:br(i)!==null))throw new Error(o==="resolver"?`${r}: "${n}" names no generator yet \u2014 name one first (offer workflow node set-generator)`:`${r}: "${n}" names no Word template yet \u2014 name one first (inputs.documentTemplate)`);let l=new Set;for(let p of t){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=t.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 t)d[p]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...t],replaced:u}}s(Uq,"setCockpitFields");var bZ=new Set(["graph","progressLayout","progressWiring"]);function Gq(e){let{label:n,...t}=e;return t}s(Gq,"definitionOf");function vZ(e){let n=[];for(let o of Object.keys(e))bZ.has(o)||n.push(`workflow.json: unknown key \`${o}\` \u2014 the file carries only graph, progressLayout, progressWiring. Delete the line.`);let t=e.graph;if(t===null||typeof t!="object"||Array.isArray(t))return n.push("workflow.json: `graph` must be an object."),n;for(let o of Object.keys(t)){if(rO.has(o))continue;let a=o==="id"||o==="label"?" (the title is the offer's, bundle.yaml `label`)":o==="dataFlow"?" (publish derives it)":"";n.push(`workflow.json: \`graph.${o}\` is no longer part of the workflow graph${a}. Delete the line.`)}let r=t;Array.isArray(r.nodes)?n.push(...Nq(r.nodes).map(o=>`workflow.json: ${o}`)):n.push("workflow.json: `graph.nodes` must be a list."),r.assignmentRules===void 0&&n.push("workflow.json: `graph.assignmentRules` is required (who becomes responsible).");let i=e.progressWiring;return i!=null&&typeof i=="object"&&"layoutId"in i&&n.push("workflow.json: `progressWiring.layoutId` is no longer part of the wiring (the layout is the workflow's own). Delete the line."),n}s(vZ,"workflowShapeIssues");function zq(e){let n=e.nodes??[],t=new Map;for(let r of n){let i=zO(r);i!==void 0&&t.set(r.id,i)}return t}s(zq,"formNodeSlugById");function xZ(e,n){let t=e.smartforms??{},r=new Map;for(let[i,o]of zq(n)){let a=t[o];if(a===void 0)return;r.set(i,Gq(a))}return qN(r)}s(xZ,"readinessContext");function SZ(e){return[...zq(e).values()]}s(SZ,"formNodeSlugs");function vh(e){let n=e.code?`[${e.code}] `:"",t=e.path?`${e.path}: `:"",r=e.reason??e.message;return`${n}${t}${r===void 0?JSON.stringify(e):r.de}`}s(vh,"describe");function Ot(e){let n=[];for(let l of Lf(e.manifest))n.push({severity:"error",area:"manifest",message:l});let t=In(e.index.label);(t==="not-localized"||t.length>0)&&n.push({severity:"error",area:"manifest",message:`[i18n/missingTranslation] bundle.yaml label fehlt in: ${t==="not-localized"?"de, en":t.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let{manifest:r,workflow:i}=e.index.slugs;i!==void 0&&i!==r&&n.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 Sf(e.index.program?.stages??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of xf(e.index.program?.runs??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of Bm(e.index.program?.runs??[],e.index.program?.stages?.map(d=>d.key)))n.push({severity:"error",area:"program",message:l});if(e.workflow!==void 0){for(let E of vZ(e.workflow))n.push({severity:"error",area:"workflow",message:E});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let E of tO(d))n.push({severity:"error",area:"workflow",message:E});let u=[];for(let{node:E,key:T,kind:R}of lh(e))E.generatorStamp?.schemaDigest===void 0&&(u.push(E.id),n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${E.id}" pinnt ${R}:${T} 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 E of l.nodes)E.type!=="governedDocument"||E.production!=="template"||E.templateStamp!==void 0||n.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${E.id}" f\xFCllt die Vorlage ${br(E)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:E,form:T}of jq(e))n.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${E}": der Stempel formExports passt nicht mehr zum Formular "${T}" \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(E=>E.key),h={...xZ(e,l),...p===void 0?{}:{stageKeys:new Set(p)}},w=s(E=>{let T=Oq(E,{layout:d,wiring:c},h),R=new Set(_q(T));return{issues:T,isError:s(D=>R.has(D)||(D.severity??"error")==="error","isError")}},"blockingOf"),{issues:k,isError:y}=w(l),b=new Set;if(u.length>0){let E=structuredClone(l);for(let L of E.nodes)u.includes(L.id)&&(L.generatorStamp={...L.generatorStamp??{},parts:[{partKey:"?"}]});let T=w(E),R=new Set(T.issues.filter(T.isError).map(vh)),D=s(L=>u.some(_=>L.includes(`$node.${_}.contract`)),"namesOutput");for(let L of k){let _=vh(L);y(L)&&!R.has(_)&&D(_)&&b.add(_)}}for(let E of k){let T=vh(E);if(b.has(T)){n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${T}`});continue}n.push({severity:y(E)?"error":"warning",area:"workflow",message:T})}}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=In(d.label);(c==="not-localized"||c.length>0)&&n.push({severity:"error",area:"smartform",message:`${l}: [i18n/missingTranslation] \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`});let u=Gq(d);for(let k of iO(u,`smartforms/${l}.json`))n.push({severity:"error",area:"smartform",message:k.de});let p=u,h=hh(p,{stageKeys:a}),w=new Set(gh(h));for(let k of h)n.push({severity:w.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${vh(k)}`});for(let k of[...YM(p),...WM(p)])n.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(SZ(l)),c=new Set(Object.keys(e.smartforms??{}));for(let u of d)c.has(u)||n.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)||n.push({severity:"warning",area:"consistency",message:`smartform "${u}" is carried but no form node binds it`})}return n}s(Ot,"validateBundle");async function Cx(e,n,t){let r=lh(t);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:n,unitKey:t.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}nO(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(Cx,"stampResolverPins");async function Dx(e,n,t){let r=(t.workflow?.graph?.nodes??[]).filter(d=>d.type==="governedDocument"&&d.production==="template"),i=[...new Set(r.flatMap(d=>{let c=br(d);return c===null?[]:[c]}))];if(i.length===0)return{rows:[],issues:[]};let o=new Map((await e.query(x.workflow.getTemplateStamps,{client:n,keys:i})).map(d=>[d.key,d])),a=[],l=[];for(let d of r){let c=br(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(K0(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(Dx,"stampTemplatePins");async function Wq(e,n,t){let r=qe(t),i=await Cx(e,n,r),o=await Dx(e,n,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");Rt(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=Ot(r).filter(p=>p.severity==="error"&&c(p.message));return{rows:a,refused:[],open:u}}s(Wq,"restampPinsOnDisk");var AZ=Y.join("contract","resolver-setup.json"),bi="resolver setup",Va=s((e,n)=>Dn(e,n,bi),"record"),io=s((e,n)=>Ge(e,n,bi),"text");function EZ(e,n){let t=Va(e,"Datei"),r=Va(t.contractTemplate,"contractTemplate"),i=Va(t.resolver,"resolver");return{dir:n,contractTemplate:{key:io(r.key,"contractTemplate.key"),name:gt(r.name,"contractTemplate.name",bi,"Vorlagennamen"),file:io(r.file,"contractTemplate.file"),role:io(r.role,"contractTemplate.role")},revenueAccounts:pm(t.revenueAccounts,bi),billingItems:mm(t.billingItems,bi),resolver:{key:io(i.key,"resolver.key"),name:gt(i.name,"resolver.name",bi,"Generatornamen"),description:i.description===void 0?null:gt(i.description,"resolver.description",bi,"Beschreibungen"),legalText:i.legalText??{},source:io(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Mt(i.feeGroups,"resolver.feeGroups",bi)).map((o,a)=>{let l=Va(o,`resolver.feeGroups[${a}]`);return{key:io(l.key,"feeGroup.key"),name:gt(l.name,"feeGroup.name",bi,"Geb\xFChrengruppen"),billingItemKeys:Fx(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:Fx(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:Fx(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:TZ(i.scenarios??[]),config:Va(i.config,"resolver.config")}}}s(EZ,"parseResolverSetup");function Fx(e,n){if(!Array.isArray(e)||e.some(t=>typeof t!="string"||t.trim()==="")||new Set(e).size!==e.length)throw new Error(`generator setup: ${n} must be a list of unique keys.`);return e}s(Fx,"stringList");function TZ(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(n=>{let t=Va(n,"scenario");if(!("input"in t)||!("expected"in t))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:io(t.key,"scenario.key"),input:t.input,expected:t.expected}})}s(TZ,"parseScenarios");function xh(e){let n=Y.resolve(e);return EZ(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(xh,"readResolverSetup");function $Z(e,n){let t=e;for(let r of n.split(".")){if(typeof t!="object"||t===null||!(r in t))throw new Error(`resolver setup: resolver.config.${n} existiert nicht.`);t=t[r]}return t}s($Z,"configValue");function Yq(e){let n=s(()=>io(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),t=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...Lx(e.resolver.config),...e.resolver.billingItemKeys])].filter(r=>!t.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"?$Z(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:n(),period:r.price.period}}})}}s(Yq,"billingSetupPayload");function Hq(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=Object.entries(e);if(n.length!==1||n[0][0]!=="$billingItem")return;let t=n[0][1];if(typeof t!="string")throw new Error(`resolver setup: $billingItem ${JSON.stringify(t)} ist kein Schl\xFCssel.`);return t}s(Hq,"billingItemRef");function Lx(e){if(Array.isArray(e))return e.flatMap(Lx);if(typeof e!="object"||e===null)return[];let n=Hq(e);return n!==void 0?[n]:Object.values(e).flatMap(Lx)}s(Lx,"billingItemRefs");function Mx(e,n,t={}){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"||t[l]===void 0)throw new Error(`generator setup: grant template ${String(l)} is not declared.`);return t[l]}let a=Hq(i);if(a!==void 0){if(!(a in n))throw new Error(`resolver setup: $billingItem "${a}" ist weder in billingItems deklariert noch ein Katalogartikel.`);return n[a]}return Object.fromEntries(Object.entries(i).map(([l,d])=>[l,r(d)]))}return i},"walk");return r(e)}s(Mx,"renderResolverConfig");function RZ(e,n){let t=Array.isArray(e.documentPlaceholderKeys)?e.documentPlaceholderKeys:[],r=new Set(n.placeholders),i=new Set(t.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(RZ,"assertPlaceholderParity");function IZ(e,n){let t=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.versionNumber-r.versionNumber)[0];if(t!==void 0)return t.coverLetter===void 0&&t.source===n.source&&t.pinnedDocumentTemplateId===n.documentTemplateId&&Pe(t.config)===Pe(n.config)&&Pe(t.legalText)===Pe(n.legalText)&&Pe([...t.billingItemDefinitionIds].sort())===Pe([...n.billingItemDefinitionIds].sort())&&Pe([...t.grantTemplateIds].sort())===Pe([...n.grantTemplateIds].sort())&&Pe(t.feeGroups)===Pe(n.feeGroups)?t:void 0}s(IZ,"matchingSealedRevision");async function tc(e,n,t){if(t.resolver.source===null)throw new Error("generator setup requires a self-contained source file.");let r=he(Y.join(t.dir,t.resolver.source),"utf8"),i=await pd(Y.join(t.dir,t.contractTemplate.file));RZ(t.resolver.config,i);let o=await e.query(x.contractSetup.planBillingSetup,{client:n,...Yq(t)}),a=await e.query(x.contractSetup.wordTemplateState,{client:n,configKey:t.contractTemplate.key}),l=a===null||a.sha256!==i.sha256,d=await e.query(x.contractConfig.model,{client:n}),c={};for(let T of t.resolver.grantTemplateKeys){let R=d.grantTemplates.find(D=>D.configKey===T);if(R===void 0)throw new Error(`Unknown grant template ${T}`);c[T]=R.id}let u=Mx(t.resolver.config,o.billingItemIds,c),h=(await e.query(x.contractGeneratorVersions.model,{client:n})).find(T=>T.definition.key===t.resolver.key),w=h?.currentRevisionId?await e.query(x.contractGeneratorVersions.detail,{client:n,id:h.currentRevisionId}):null,k=h?.revisions.find(T=>T.status==="draft"),y=k?await e.query(x.contractGeneratorVersions.detail,{client:n,id:k.id}):null,b=l||w===null?void 0:IZ([w],{source:r,config:u,legalText:t.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:t.resolver.billingItemKeys.map(T=>o.billingItemIds[T]??`not-created:${T}`),grantTemplateIds:Object.values(c),feeGroups:t.resolver.feeGroups.map(T=>({key:T.key,name:T.name,billingItemDefinitionIds:T.billingItemKeys.map(R=>o.billingItemIds[R]??`not-created:${R}`)}))}),E=o.rows.map(T=>({step:T.kind,target:T.key,action:T.action,detail:T.detail}));return E.push({step:"wordTemplate",target:t.contractTemplate.key,action:l?"create":"same",detail:Y.basename(i.file)}),E.push({step:"generatorVersion",target:t.resolver.key,action:b?"same":"create",detail:b?`Current sealed revision ${b.versionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:E,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:h,current:w,draft:y,match:b,template:{documentTemplateId:a?.id??null,upload:l}}}s(tc,"planResolverSetup");async function Jq(e,n,t){let r=await tc(e,n,t);if(r.rows.every(p=>p.action==="same"))return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}};if(!r.match&&t.resolver.scenarios.length===0)throw new Error("A new generator revision requires reviewed scenarios.");let i=await e.mutation(x.contractSetup.applyBillingSetup,{client:n,...Yq(t)});if(r.match)return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}};let o=r.template.upload?await fm(e,n,r.docx,{name:t.contractTemplate.name,role:t.contractTemplate.role,configKey:t.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:n,key:t.resolver.key,name:t.resolver.name,description:t.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:n,id:r.current._id})}let l=await e.query(x.contractGeneratorVersions.detail,{client:n,id:a}),d=await e.mutation(x.contractGeneratorVersions.save,{client:n,id:a,expectedSourceRevision:l.sourceRevision,config:Mx(t.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:t.resolver.legalText,documentTemplateId:o}),c=await e.action(x.contractGeneratorVersionActions.saveSource,{client:n,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:t.resolver.billingItemKeys.map(p=>i.billingItemIds[p]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:t.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(`
11364
11364
  `));if(d=c.sourceRevision,await e.mutation(x.contractGeneratorVersions.approveScenarios,{client:n,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:Mx({scenarios:t.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(x.contractGeneratorVersions.seal,{client:n,id:a,expectedSourceRevision:d}),(await tc(e,n,t)).match===void 0)throw new Error("The sealed revision does not match the declarative setup.");return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}}}s(Jq,"applyResolverSetup");async function qx(e,n,t){let r=Y.join(t.dir,AZ);if(!Ae(r)||t.workflow===void 0)return[];let i=xh(r);if((await tc(e,n,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(qx,"pinSetupRevisions");function OZ(e){if(e.label===void 0)return;let n=e.label;if(typeof n!="object"||n===null||typeof n.de!="string"||typeof n.en!="string")throw new Error(`node "${e.id}": label ${JSON.stringify(e.label)} is not a { de, en } text`);return{de:n.de,en:n.en}}s(OZ,"nodeText");function rc(e,n){let t=[],r=[],i=[],o={},a=n.progressEvents??[],l=OZ(e);for(let d of a){let c=`${e.id}.${d}`,u=n.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),t.push(k),r.push({match:{nodeId:e.id},event:d,bus:"process",state:c});let y=u.phase,b=_Z(y,e.id),E=i.find(T=>T.id===b);if(E)E.states=[...E.states,c];else{let T={id:b,label:p?h:y.label,tone:w,states:[c]};y.track&&(T.track=y.track),y.defaultCollapsed&&(T.defaultCollapsed=!0),y.waitlist&&(T.waitlist=!0),i.push(T)}u.terminal&&(o[c]=u.terminal)}return{states:t,mappings:r,columns:i,terminalSemantics:o}}s(rc,"deriveProgressEntriesForNode");function Sh(e){return Object.entries(e).filter(([,n])=>n.outcome==="approved").map(([n])=>n)}s(Sh,"seatedTerminalStates");function _Z(e,n){return e.scope==="global"?`col.${e.key}`:`${n}.${e.key}`}s(_Z,"columnIdFor");function Qq(e,n){let t=s(i=>(i.states??[]).some(o=>n.terminalStateIds.has(o)),"isTerminal"),r=s(i=>{let o=n.columnNodeId(i);return(o!==void 0?n.nodeOrder.get(o):void 0)??Number.POSITIVE_INFINITY},"topoOf");return e.map((i,o)=>({c:i,idx:o,term:t(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(Qq,"orderProcessColumns");var dr=s((e,n)=>({de:e,en:n}),"lt"),jx=_s("start",[]),Ah=_s("form",[jx]),Kx=_s("end",[jx,Ah]);function PZ(e){let n=[rc({id:Ah,type:"form",label:dr("Formular","Form")},rs.form),rc({id:Kx,type:"end",label:dr("Ende","End")},rs.end)],t=[],r=[],i=[],o={};for(let c of n){t.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=Sh(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:t,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:dr("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(PZ,"buildStarterProgress");function Zq(e){let{slug:n,title:t,tenant:r,unit:i,responsible:o}=e,a=n,l=`${n}-form`,d=`${n}-flow`,c=[{id:jx,type:"eventTrigger",label:dr("Start","Start"),sublabel:dr("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:Ah}}},{id:Ah,type:"form",label:t,sublabel:dr("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:dr("Standard","Standard")}],next:{standard:{to:Kx}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:Kx,type:"end",label:dr("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:gN(wN([{slot:"responsible",rules:[{when:Wi,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Pp({nodes:c})))},{layout:p,wiring:h}=PZ(d),w={id:Ka("section.applicant"),label:dr("Antragsteller","Applicant"),fields:[{key:ot("applicant.vorname"),label:dr("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:ot("applicant.nachname"),label:dr("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:to("standard"),label:dr("Standard","Standard"),when:"true",output:{fields:[{path:ot("applicant.vorname")},{path:ot("applicant.nachname")}],includeForm:!0}}],y={sections:[w],effects:[],outcomes:k},b={};return{index:{module:"admission",tenant:r,label:t,slugs:{manifest:a,workflow:a},smartforms:{[l]:{}},...i?{links:{unitKey:i}}:{}},manifest:b,smartforms:{[l]:{label:t,...y}},workflow:{graph:u,progressLayout:p,progressWiring:h}}}s(Zq,"buildSkeletonBundle");var as={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function Fn(e,n,t){let i=(await e.query(x.workflow.listManifests,{client:n})).find(o=>o.offerKey===t);if(!i)throw new We(`offer: no offer "${t}" in tenant "${n}"`);return i}s(Fn,"findOfferHandle");function st(e,n,t){return e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0})}s(st,"loadConfig");function Vx(e,n){let t=e.units.find(r=>r.key===n);if(!t)throw new We(`offer: unit "${n}" not found. Available keys: ${e.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return t.unitId}s(Vx,"resolveUnitId");function Ba(e,n){let t=Xq(e),r=e.runs.find(i=>i.key===Qt(t,n));if(!r)throw new We(`offer: run "${n}" not found. Available keys: ${e.runs.map(i=>SI(t,i.key)).join(", ")||"(none)"}`);return r.runId}s(Ba,"resolveRunId");function Ua(e,n){let t=Xq(e),r=e.stages.find(i=>i.key===Os(t,n));if(!r)throw new We(`offer: level "${n}" not found. Available keys: ${e.stages.map(i=>Kr(t,i.key)).join(", ")||"(none)"}`);return r.stageId}s(Ua,"resolveStageId");function Xq(e){if(e.programKey===null)throw new We("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(Xq,"requireProgramKey");async function Bx(e,n,t,r){await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:n,unitId:r}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:n,offerKey:t,unitId:r})}s(Bx,"linkUnit");function ls(e,n){if(n===void 0)return;let t=Number(n);if(!Number.isInteger(t)||t<0)throw new Error(`offer: --${e} must be a non-negative integer`);return t}s(ls,"parsePositiveInt");var Ga=s((e="Offer slug (required)")=>f.String("--offer",{description:e}),"offerOption"),Ux=s(()=>f.String("--slug",{hidden:!0}),"retiredSlugOption");function Gx(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new vn(`--offer "${e.offer}" and --slug "${e.retiredSlug}" name different offers \u2014 pass only --offer.`);return ln(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new vn("Missing --offer <slug>.");return e.offer}s(Gx,"requireOffer");var nn=class extends C{static{s(this,"OfferCommand")}offer=Ga();retiredSlug=Ux();#e;get offerSlug(){return this.#e??=Gx(this),this.#e}};var ic=class extends nn{static{s(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=$.Usage({category:"Offer",description:"Pull an offer's published generation (manifest + smartforms + workflow + program) into a bundle; --draft pulls the draft"});offer=Ga("Manifest slug to export (required)");out=f.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=kn();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 n=Vk(this.out,this.force),t=await this.caller(),r=this.requireTenant(t),{bundle:i,generation:o,revision:a}=await FM(t,r,this.offerSlug,this.draft?"draft":"published");return Rt({...i,dir:n}),this.print({exported:`${r}/${this.offerSlug}`,generation:o,revision:a,dir:n},l=>[{key:"exported",value:l.exported},{key:"generation",value:`${l.generation} (revision ${l.revision})`},{key:"dir",value:l.dir}]),0}},oc=class extends xe{static{s(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=$.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});offer=Ga("New offer slug (identity key) (required)");retiredSlug=Ux();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=kn();async execute(){let n=Gx(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let t=Vk(this.out??Y.join("offers",this.tenant,n),this.force),r=Zq({slug:n,title:Yn({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 Rt({...r,dir:t}),this.print({created:`${this.tenant}/${n}`,dir:t},i=>[{key:"created",value:i.created},{key:"dir",value:i.dir},{key:"next",value:`plexus offer validate --dir ${i.dir}`}]),0}},sc=class extends xe{static{s(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=$.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 n=qe(this.dir),t=Ot(n);return this.print(t,r=>r.length===0?[{severity:"ok",area:"-",message:"local validation clean"}]:r.map(i=>({severity:i.severity,area:i.area,message:i.message}))),t.some(r=>r.severity==="error")?1:0}},ac=class extends C{static{s(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=$.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 n=qe(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await eK(t,n),a=await Ax(t,n);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:as[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:as[d],target:`smartform:${l}`,detail:d})),{kind:as[a.workflow],target:"workflow",detail:a.workflow},...nK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...tK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...rK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...iK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},lc=class extends C{static{s(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=$.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=f.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=qe(this.dir),t=await this.caller(),r=await qx(t,n.index.tenant,n),i=await Ax(t,n);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:as[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:as[a],target:`smartform:${o}`,status:a})),{icon:as[i.workflow],target:"workflow",status:i.workflow},...nK(i),...tK(i),...rK(i),...iK(i)]),0}};async function eK(e,n){let t=await qx(e,n.index.tenant,n),r=await Cx(e,n.index.tenant,n),i=await Dx(e,n.index.tenant,n);return{pins:t,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Ot(n)]}}s(eK,"validateOnEnvironment");function nK(e){return e.addresses===null?[]:NM(e.addresses)}s(nK,"addressRows");function tK(e){let n={insert:"+",update:"~",archive:"-"};return e.stages.map(t=>({icon:n[t.op],target:`stage:${t.key}`,status:Ef(t)}))}s(tK,"stageRows");function rK(e){return e.capacities.map(n=>({icon:"~",target:`cap:${n.run}\xD7${n.stageKey}`,status:Um(n)}))}s(rK,"capacityRows");function iK(e){if(e.publishPending===null)return[];let n=e.externalHeadRevision===null?"none":`v${e.externalHeadRevision}`;return[{icon:e.publishPending?"!":"=",target:"publish",status:e.publishPending?`pending (draft v${e.draftRevision} ahead of live ${n})`:`up to date (live ${n})`}]}s(iK,"publishPendingRows");var dc=class extends C{static{s(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=$.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 n=qe(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await eK(t,n);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
@@ -11530,7 +11530,7 @@ At most PLEXUS_SEED_SLOTS (default 2) seeds run at once on this machine, across
11530
11530
  `)}
11531
11531
  `),0}},xT=class extends mr{static{s(this,"UsersRevokeCommand")}static paths=[["platform","users","revoke"],["users","revoke"],["users","remove"]];static usage=$.Usage({category:"Users",description:"Revoke a user's access to the active tenant (--tenant) \u2014 plan unless --confirm. Other tenants keep it; `platform users archive` archives everywhere."});email=f.String({required:!0});replaceWith=f.String("--replace-with",{description:"configKey of the staff member who takes over their active applications \u2014 required while they are responsible for any. A rule naming them refuses regardless: change it first (workflow editor: \u201EPerson ersetzen\u201C, then publish)"});confirm=f.Boolean("--confirm",!1,{description:"Revoke (without it, only the plan is printed)."});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await YX(n,this.email,t);return this.confirm?(await n.mutation(x.platformAdmin.revokeTenantAccess,{userTenantAccessId:r,...this.replaceWith!==void 0?{replaceWith:this.replaceWith}:{}}),this.report({revoked:r},`Revoked ${this.email}'s access to "${t}".`),0):(this.report({tenant:t,email:this.email,userTenantAccessId:r,revoked:!1},`DRY RUN \u2014 would revoke ${this.email}'s access to "${t}". Re-run with --confirm.`),0)}},ST=class extends mr{static{s(this,"UsersSetPlatformAdminCommand")}static paths=[["platform","users","set-platform-admin"],["users","set-platform-admin"]];static usage=$.Usage({category:"Users",description:"Grant/revoke platform-admin status (--on | --off)."});email=f.String({required:!0});on=f.Boolean("--on",!1,{description:"Grant."});off=f.Boolean("--off",!1,{description:"Revoke."});async execute(){let n=qB(this.on,this.off),t=await this.caller(),r=await MB(t,this.email);await t.mutation(x.platformAdmin.setPlatformAdmin,{userId:r,isPlatformAdmin:n});let i=n?"is now a platform admin":"is no longer a platform admin";return this.report({userId:r,isPlatformAdmin:n},`${this.email} ${i}.`),0}},AT=class extends mr{static{s(this,"UsersSetPlatformPermissionCommand")}static paths=[["platform","users","set-platform-permission"],["users","set-platform-permission"]];static usage=$.Usage({category:"Users",description:"Grant/revoke a single _platform.* permission (--on | --off)."});email=f.String({required:!0});permission=f.String("--permission",{required:!0,description:"The _platform.* permission."});on=f.Boolean("--on",!1,{description:"Grant."});off=f.Boolean("--off",!1,{description:"Revoke."});async execute(){let n=qB(this.on,this.off);if(!ig.includes(this.permission))throw new Error(`Unknown _platform.* permission "${this.permission}". One of: ${ig.join(", ")}.`);let t=await this.caller(),r=await MB(t,this.email);await t.mutation(x.platformAdmin.setPlatformPermission,{userId:r,permission:this.permission,enabled:n});let i=n?"granted":"revoked";return this.report({userId:r,permission:this.permission,enabled:n},`${i} ${this.permission} for ${this.email}.`),0}},og=class extends mr{static{s(this,"CredentialOutCommand")}out=f.String("--out",{description:"Append the `email,password` row to this CSV file (created with a header; never overwritten)."});retiredOutput=Ia();quiet=f.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (needs --out)."});#e;credentialsFile(){if(this.#e===void 0){let n=Oa(this);if(this.quiet&&n===void 0)throw new Error("--quiet without --out would lose the password \u2014 it is shown only once.");n!==void 0&&Zo(n,"password"),this.#e={file:n}}return this.#e.file}handOver(n,t,r,i){let o=this.credentialsFile();if(o!==void 0&&$m(o,n,t),this.json){this.print({...r,email:n});return}this.context.stdout.write(`${i}${o!==void 0?` \u2192 ${o}`:""}.
11532
11532
  `),this.quiet||this.context.stdout.write(` password: ${t}
11533
- `)}},sg=class extends og{static{s(this,"PasswordSettingCommand")}passwordStdin=f.Boolean("--password-stdin",!1,{description:"Read the password from stdin instead of letting the server generate one."});passwordFile=f.String("--password-file",{description:"Read the password from this file instead of letting the server generate one."});retiredPassword=f.String("--password",{hidden:!0});async chosenPassword(){if(kf(this.retiredPassword,"--password",'Pipe it in with --password-stdin (`printf %s "$PW" | plexus-cli \u2026 --password-stdin`), pass --password-file <path>, or omit both to let the server generate one.'),!(!this.passwordStdin&&this.passwordFile===void 0))return await Rs({stdin:this.passwordStdin,file:this.passwordFile},$s(this.context.stdin),{stdin:"--password-stdin",file:"--password-file"})}},ET=class extends og{static{s(this,"UsersCreateCommand")}static paths=[["platform","users","create"],["users","create"]];static usage=$.Usage({category:"Users",description:"Create a tenant-less identity WITH a login account from just an e-mail (optionally a platform admin). Idempotent: an existing user is left untouched \u2014 no password is rotated. To (re)set a ready-to-log-in account with a name, group or permission set, use `platform users provision`.",details:"The generated password is printed once (use --out/--quiet to keep it out of the terminal)."});email=f.String({required:!0});platformAdmin=f.Boolean("--platform-admin",!1,{description:"Make the new user a platform admin (full _platform.* set)."});async execute(){this.credentialsFile();let t=await(await this.caller()).mutation(x.platformAdmin.createUser,{email:this.email,platformAdmin:this.platformAdmin});return t.password===void 0?(this.report({...t,email:this.email},`${this.email} already exists (no change).`),0):(this.handOver(this.email,t.password,t,`Created ${this.email}${this.platformAdmin?" as a platform admin":""}`),0)}},Au=class extends sg{static{s(this,"UsersProvisionCommand")}static paths=[["platform","users","provision"],["users","provision"]];static usage=$.Usage({category:"Users",description:"Create \u2014 or reset \u2014 a ready-to-log-in account with a password (generated, or from --password-stdin / --password-file) and emit the email\u2192password mapping. One of three kinds: a tenant user in a permission group of the active tenant (default), a tenant-less platform admin (--platform-admin), or a tenant-less platform user with an exact _platform.* subset (--permission, repeatable). Re-running rotates the password.",examples:[["A tenant administrator, provisioned by the operator","plexus-cli --env staging --tenant <slug> platform users provision ada@example.com --name Ada --out /tmp/credentials.csv --quiet"],["A platform admin","plexus-cli --env staging platform users provision ops@example.com --name Ops --platform-admin"],["A schema-read-only platform user","plexus-cli --env prod platform users provision ada@example.com --name Ada --permission _platform.schema.read --out /tmp/credentials.csv --quiet --allow-prod"]]});email=f.String({required:!0});name=f.String("--name",{required:!0,description:"Display name for the login."});group=f.String("--group",{description:`Permission group key in the active tenant (tenant user only; default: ${Za}).`});platformAdmin=f.Boolean("--platform-admin",!1,{description:"A tenant-less platform admin holding the full _platform.* set."});permissions=f.Array("--permission",{description:"A tenant-less platform user with exactly this _platform.* permission (repeatable)."});async execute(){let n=[...new Set(this.permissions??[])];if(this.platformAdmin&&n.length>0)throw new Error("Pass --platform-admin (the full set) OR --permission (a subset), not both.");let t=this.platformAdmin||n.length>0;if(t&&this.group!==void 0)throw new Error("--group names a tenant group \u2014 a platform account has none.");if(t&&this.tenant!==void 0)throw new Error("--tenant does not apply: a platform account is tenant-less.");for(let o of n)if(!ig.includes(o))throw new Error(`Unknown _platform.* permission "${o}". One of: ${ig.join(", ")}.`);let r=await this.chosenPassword();this.credentialsFile();let i=await this.caller();if(this.platformAdmin){let o=await i.mutation(x.platformAdmin.provisionPlatformAdmin,{email:this.email,name:this.name,password:r});this.handOver(this.email,o.password,o,`Provisioned platform admin ${this.email} (${this.name})`)}else if(n.length>0){let o=await i.mutation(x.platformAdmin.provisionPlatformUser,{email:this.email,name:this.name,permissions:n,password:r});this.handOver(this.email,o.password,o,`Provisioned platform user ${this.email} (${this.name}) with ${n.join(", ")}`)}else{let o=this.requireTenant(i),a=this.group??Za,l=await i.mutation(x.platformAdmin.provisionUser,{email:this.email,name:this.name,tenantSlug:o,permissionGroupKey:a,password:r});this.handOver(this.email,l.password,l,`Provisioned ${this.email} in "${o}" (group: ${a})`)}return 0}},TT=class extends Au{static{s(this,"UsersProvisionPlatformAdminCommand")}static paths=[["users","provision-platform-admin"]];static usage=void 0;async execute(){return ln(this.context.stderr,"users provision-platform-admin","platform users provision --platform-admin"),this.platformAdmin=!0,await super.execute()}},$T=class extends Au{static{s(this,"UsersProvisionPlatformUserCommand")}static paths=[["users","provision-platform-user"]];static usage=void 0;async execute(){if(ln(this.context.stderr,"users provision-platform-user","platform users provision --permission <p>"),(this.permissions??[]).length===0)throw new Error("Pass at least one --permission.");return await super.execute()}},RT=class extends sg{static{s(this,"UsersSetPasswordCommand")}static paths=[["platform","users","set-password"],["users","set-password"]];static usage=$.Usage({category:"Users",description:"Set (rotate) an existing user's login password \u2014 tenant user or platform admin. Generated by the server unless --password-stdin / --password-file gives one. Emits the email\u2192password mapping. Creates nothing; fails loud on an unknown or orphaned identity (run `platform users relink-auth` first)."});email=f.String({required:!0});async execute(){let n=await this.chosenPassword();this.credentialsFile();let r=await(await this.caller()).mutation(x.platformAdmin.setUserPassword,{email:this.email,password:n});return this.handOver(this.email,r.password,r,`Set password for ${this.email}`),0}};function JX(e){return new Date(e).toISOString().replace("T"," ").slice(0,19)+"Z"}s(JX,"stamp");function QX(e){let n=[],t=e.account;n.push(t===null?`${e.email}: kein anmeldef\xE4higes Konto (keine Identit\xE4t oder nie ein Anmeldekonto angelegt) \u2014 dorthin geht kein Anmeldelink; jede Anfrage steht unten als \u201Eabgelehnt: unknownAddress".`:`${e.email}: Konto ${t.userId}, Adresse ${t.emailVerified?"best\xE4tigt":"NICHT best\xE4tigt"}`);let r=[...e.refusals.map(i=>({at:i.at,text:`abgelehnt: ${i.reason} \u2014 ${i.surface==="login"?"Anmeldeseite":`Portal ${i.tenantSlug??"(Schule gel\xF6scht)"}`}${i.emailSnapshot===e.email?"":` (Adresse ${i.emailSnapshot})`}`})),...e.letters.map(i=>({at:i.createdAt,text:`Brief ${i.templateId}: ${i.status}${i.errorCode?` (${i.errorCode})`:""}${i.lastSmtpResponse?` \u2014 Relay: ${i.lastSmtpResponse}`:""}`})),...e.sessions.map(i=>({at:i.createdAt,text:`Sitzung von ${i.ipAddress??"?"} \u2014 ${i.userAgent??"?"}`})),...e.passwordSetAt===null?[]:[{at:e.passwordSetAt,text:"Passwort gesetzt (zuletzt)"}]].sort((i,o)=>i.at-o.at);r.length===0&&n.push(" (nichts im Zeitraum)");for(let i of r)n.push(` ${JX(i.at)} ${i.text}`);n.push("Nicht erfasst:");for(let i of e.notRecorded)n.push(` - ${i}`);return n.join(`
11533
+ `)}},sg=class extends og{static{s(this,"PasswordSettingCommand")}passwordStdin=f.Boolean("--password-stdin",!1,{description:"Read the password from stdin instead of letting the server generate one."});passwordFile=f.String("--password-file",{description:"Read the password from this file instead of letting the server generate one."});retiredPassword=f.String("--password",{hidden:!0});async chosenPassword(){if(kf(this.retiredPassword,"--password",'Pipe it in with --password-stdin (`printf %s "$PW" | plexus-cli \u2026 --password-stdin`), pass --password-file <path>, or omit both to let the server generate one.'),!(!this.passwordStdin&&this.passwordFile===void 0))return await Rs({stdin:this.passwordStdin,file:this.passwordFile},$s(this.context.stdin),{stdin:"--password-stdin",file:"--password-file"})}},ET=class extends og{static{s(this,"UsersCreateCommand")}static paths=[["platform","users","create"],["users","create"]];static usage=$.Usage({category:"Users",description:"Create a tenant-less identity WITH a login account from just an e-mail (optionally a platform admin). Idempotent: an existing user is left untouched \u2014 no password is rotated. To (re)set a ready-to-log-in account with a name, group or permission set, use `platform users provision`.",details:"The generated password is printed once (use --out/--quiet to keep it out of the terminal)."});email=f.String({required:!0});platformAdmin=f.Boolean("--platform-admin",!1,{description:"Make the new user a platform admin (full _platform.* set)."});async execute(){this.credentialsFile();let t=await(await this.caller()).mutation(x.platformAdmin.createUser,{email:this.email,platformAdmin:this.platformAdmin});return t.password===void 0?(this.report({...t,email:this.email},`${this.email} already exists (no change).`),0):(this.handOver(this.email,t.password,t,`Created ${this.email}${this.platformAdmin?" as a platform admin":""}`),0)}},Au=class extends sg{static{s(this,"UsersProvisionCommand")}static paths=[["platform","users","provision"],["users","provision"]];static usage=$.Usage({category:"Users",description:"Create \u2014 or reset \u2014 a ready-to-log-in account with a password (generated, or from --password-stdin / --password-file) and emit the email\u2192password mapping. One of three kinds: a tenant user in a permission group of the active tenant (default), a tenant-less platform admin (--platform-admin), or a tenant-less platform user with an exact _platform.* subset (--permission, repeatable). Re-running rotates the password.",examples:[["A tenant administrator, provisioned by the operator","plexus-cli --env staging --tenant <slug> platform users provision ada@example.com --name Ada --out /tmp/credentials.csv --quiet"],["A platform admin","plexus-cli --env staging platform users provision ops@example.com --name Ops --platform-admin"],["A schema-read-only platform user","plexus-cli --env prod platform users provision ada@example.com --name Ada --permission _platform.schema.read --out /tmp/credentials.csv --quiet --allow-prod"]]});email=f.String({required:!0});name=f.String("--name",{required:!0,description:"Display name for the login."});group=f.String("--group",{description:`Permission group key in the active tenant (tenant user only; default: ${Za}).`});platformAdmin=f.Boolean("--platform-admin",!1,{description:"A tenant-less platform admin holding the full _platform.* set."});permissions=f.Array("--permission",{description:"A tenant-less platform user with exactly this _platform.* permission (repeatable)."});async execute(){let n=[...new Set(this.permissions??[])];if(this.platformAdmin&&n.length>0)throw new Error("Pass --platform-admin (the full set) OR --permission (a subset), not both.");let t=this.platformAdmin||n.length>0;if(t&&this.group!==void 0)throw new Error("--group names a tenant group \u2014 a platform account has none.");if(t&&this.tenant!==void 0)throw new Error("--tenant does not apply: a platform account is tenant-less.");for(let o of n)if(!ig.includes(o))throw new Error(`Unknown _platform.* permission "${o}". One of: ${ig.join(", ")}.`);let r=await this.chosenPassword();this.credentialsFile();let i=await this.caller();if(this.platformAdmin){let o=await i.mutation(x.platformAdmin.provisionPlatformAdmin,{email:this.email,name:this.name,password:r});this.handOver(this.email,o.password,o,`Provisioned platform admin ${this.email} (${this.name})`)}else if(n.length>0){let o=await i.mutation(x.platformAdmin.provisionPlatformUser,{email:this.email,name:this.name,permissions:n,password:r});this.handOver(this.email,o.password,o,`Provisioned platform user ${this.email} (${this.name}) with ${n.join(", ")}`)}else{let o=this.requireTenant(i),a=this.group??Za,l=await i.mutation(x.platformAdmin.provisionUser,{email:this.email,name:this.name,tenantSlug:o,permissionGroupKey:a,password:r});this.handOver(this.email,l.password,l,`Provisioned ${this.email} in "${o}" (group: ${a})`)}return 0}},TT=class extends Au{static{s(this,"UsersProvisionPlatformAdminCommand")}static paths=[["users","provision-platform-admin"]];static usage=void 0;async execute(){return ln(this.context.stderr,"users provision-platform-admin","platform users provision --platform-admin"),this.platformAdmin=!0,await super.execute()}},$T=class extends Au{static{s(this,"UsersProvisionPlatformUserCommand")}static paths=[["users","provision-platform-user"]];static usage=void 0;async execute(){if(ln(this.context.stderr,"users provision-platform-user","platform users provision --permission <p>"),(this.permissions??[]).length===0)throw new Error("Pass at least one --permission.");return await super.execute()}},RT=class extends sg{static{s(this,"UsersSetPasswordCommand")}static paths=[["platform","users","set-password"],["users","set-password"]];static usage=$.Usage({category:"Users",description:"Set (rotate) an existing user's login password \u2014 tenant user or platform admin. Generated by the server unless --password-stdin / --password-file gives one. Emits the email\u2192password mapping. Creates nothing; fails loud on an unknown or orphaned identity (run `platform users relink-auth` first)."});email=f.String({required:!0});async execute(){let n=await this.chosenPassword();this.credentialsFile();let r=await(await this.caller()).mutation(x.platformAdmin.setUserPassword,{email:this.email,password:n});return this.handOver(this.email,r.password,r,`Set password for ${this.email}`),0}};function JX(e){return new Date(e).toISOString().replace("T"," ").slice(0,19)+"Z"}s(JX,"stamp");function QX(e){let n=[],t=e.account;n.push(t===null?`${e.email}: kein anmeldef\xE4higes Konto (keine Identit\xE4t oder nie ein Anmeldekonto angelegt) \u2014 dorthin geht kein Anmeldelink; jede Anfrage steht unten als \u201Eabgelehnt: unknownAddress".`:`${e.email}: Konto ${t.userId}, Adresse ${t.emailVerified?"best\xE4tigt":"NICHT best\xE4tigt"}`);let r=[...e.refusals.map(i=>({at:i.at,text:`abgelehnt: ${i.reason} \u2014 ${i.surface==="login"?"Anmeldeseite":`Portal ${i.tenantSlug??"(Schule gel\xF6scht)"}`}${i.emailSnapshot===e.email?"":` (Adresse ${i.emailSnapshot})`}`})),...e.letters.map(i=>({at:i.createdAt,text:`Benachrichtigung ${i.templateId}: ${i.status}${i.errorCode?` (${i.errorCode})`:""}${i.lastSmtpResponse?` \u2014 Relay: ${i.lastSmtpResponse}`:""}`})),...e.sessions.map(i=>({at:i.createdAt,text:`Sitzung von ${i.ipAddress??"?"} \u2014 ${i.userAgent??"?"}`})),...e.passwordSetAt===null?[]:[{at:e.passwordSetAt,text:"Passwort gesetzt (zuletzt)"}]].sort((i,o)=>i.at-o.at);r.length===0&&n.push(" (nichts im Zeitraum)");for(let i of r)n.push(` ${JX(i.at)} ${i.text}`);n.push("Nicht erfasst:");for(let i of e.notRecorded)n.push(` - ${i}`);return n.join(`
11534
11534
  `)}s(QX,"loginTrailText");var IT=class extends C{static{s(this,"UsersLoginTrailCommand")}static paths=[["platform","users","login-trail"],["users","login-trail"]];static usage=$.Usage({category:"Users",description:"Everything the platform still knows about one address's sign-in: requests that sent no mail (login page and portal, unknown addresses included), letters with the relay's answer, sessions (when, network, browser), when a password was set (platform-admin).",examples:[["Why did she get no link today?","$0 --env prod platform users login-trail steffi@schule.example --since 24h"]]});email=f.String({required:!0});since=f.String("--since",{description:"From: 90m, 24h, 2d or an ISO date/time (default 7d)."});async execute(){let t=await(await this.caller()).query(x.loginTrail.forAddress,{email:this.email,since:Km(this.since??"7d")});return this.json?this.print(t):this.context.stdout.write(`${QX(t)}
11535
11535
  `),0}},OT=class extends mr{static{s(this,"UsersSetEmailCommand")}static paths=[["platform","users","set-email"],["users","set-email"]];static usage=$.Usage({category:"Users",description:"Change an existing user's login e-mail across all their tenants (plan unless --confirm). Fails loud when the new address is taken.",details:"The password stays. Mailbox proof is reset \u2014 except when the new address is a reserved test address (.test, .example, .invalid, .localhost, example.com/.net/.org), which has no mailbox to prove.",examples:[["Plan moving a test account off a real domain","plexus-cli --env prod platform users set-email old@example.com --to new@example.com"],["Apply it","plexus-cli --env prod platform users set-email old@example.com --to new@example.com --confirm --allow-prod"]]});email=f.String({required:!0});to=f.String("--to",{required:!0,description:"The new login e-mail address."});confirm=f.Boolean("--confirm",!1,{description:"Write the change (without it, only the plan is printed)."});async execute(){let t=await(await this.caller()).mutation(x.platformAdmin.setUserEmail,{email:this.email,newEmail:this.to,dryRun:!this.confirm});if(this.json)return this.print(t),0;let r=t.tenants.length>0?t.tenants.join(", "):"no tenant";if(!t.changed)return this.context.stdout.write(`${t.from} is already ${t.to} (no change).
11536
11536
  `),0;let i=t.applied?"Changed":"Would change";return this.context.stdout.write(`${i} ${t.from} \u2192 ${t.to} (${r}); mailbox proof ${t.proof}.
@@ -11540,6 +11540,6 @@ ${t.length} unusable ${o}:
11540
11540
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
11541
11541
  `),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>
11542
11542
  `)}else this.context.stdout.write(`No unusable identities.
11543
- `);return t.length>0?1:0}},NT=class extends mr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=$.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 t=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=t.changed?`Relinked ${this.email} to live auth account ${t.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(t,r),0}};function qB(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(qB,"requireOnOff");var KB=[gT,yT,wT,kT,bT,vT,xT,ST,AT,ET,Au,TT,$T,RT,IT,OT,_T,PT,NT];function jB(e){return e.de??e.en??Object.values(e)[0]??""}s(jB,"titleDe");function ZX(e){return{id:e._id,kind:e.kind,status:e.status,title:jB(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(ZX,"row");var XX=["id","kind","status","title","assignee","group","outcome"],FT=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.list,{client:t,...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(ZX),XX),0}},LT=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=$.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.get,{client:t,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${t}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:jB(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}},MT=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.createManual,{client:t,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}},qT=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.complete,{client:t,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}},KT=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.assign,{client:t,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}},VB=[FT,LT,MT,qT,KT];var Eu=[...bI,...eF,...dF,...uL,...cL,...LL,...UL,...BL,...LB,...KB,...FB,...vV,...$V,...MD,...NL,...AB,...wI,...QI,...SD,...WL,...zL,...JL,...QL,..._L,...yL,...VB,...pK,...tj,...kV,...rj,...aB,...hB,...RV,...LV,...KV,...UV,...zV,...wB,...IB,...jI];for(let e of Eu){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:j$(e.usage.category,n.join(" "))})}var BB="0.1.224";function UB(){return Eu.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=L$[mo(t)];return{path:t,effect:ho(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(UB,"plexusCommandCatalog");import fs from"node:path";function e7(e){let n=cn()?.workspaceRoot??process.cwd(),t=fs.resolve(n,e),r=fs.relative(n,t);if(fs.isAbsolute(e)||r===".."||r.startsWith(`..${fs.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(e7,"workspacePath");function n7(e){let{absolute:n,relative:t}=e7(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Cr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=fs.join(o,a.name);if(a.isDirectory()?i(l):r.push(fs.relative(n,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(n),{files:r.sort()}}if(!t)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(n);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:t,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:t,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 ze(n,a,"utf8"),{path:t,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 Ln(fs.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return gs(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(n7,"plexusWorkspace");function GB(e){return s(async function(t,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=$l[t];if(!o||!Object.hasOwn($l,t))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(t==="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(t==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Sy,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Sy[i.path],skillHash:bf}}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 n7(i)},"executePlexusAgentTool")}s(GB,"createPlexusAgentToolExecutor");var lg=GB({inspectCommand:WB,executeCommand:YB});function dg(){let e=new bs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:BB});e.register(cl.HelpCommand),e.register(cl.VersionCommand);for(let t of Eu)e.register(t);async function n(t,r){let i;try{i=e.process(t,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return i7(i,r.stderr??process.stderr),e.run(i,r)}return s(n,"run"),{process(t,r){return e.process(t,r)},run:n,async runExit(t,r){process.exitCode=await n(t,r)}}}s(dg,"createPlexusCli");function i7(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&hl[t]===r&&ln(n,t,r),t in hl&&ho(t)==="confirm"&&!gl(e)&&n.write(`plexus-cli: \`${hl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11543
+ `);return t.length>0?1:0}},NT=class extends mr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=$.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 t=await(await this.caller()).mutation(x.platformAdmin.relinkAuthAccount,{email:this.email}),r=t.changed?`Relinked ${this.email} to live auth account ${t.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(t,r),0}};function qB(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(qB,"requireOnOff");var KB=[gT,yT,wT,kT,bT,vT,xT,ST,AT,ET,Au,TT,$T,RT,IT,OT,_T,PT,NT];function jB(e){return e.de??e.en??Object.values(e)[0]??""}s(jB,"titleDe");function ZX(e){return{id:e._id,kind:e.kind,status:e.status,title:jB(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(ZX,"row");var XX=["id","kind","status","title","assignee","group","outcome"],FT=class extends C{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.list,{client:t,...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(ZX),XX),0}},LT=class extends C{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=$.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=f.String({required:!0,name:"workItemId"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workItems.get,{client:t,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${t}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:jB(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}},MT=class extends C{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.createManual,{client:t,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}},qT=class extends C{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.complete,{client:t,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}},KT=class extends C{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=$.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 n=await this.caller(),t=this.requireTenant(n),r=await n.mutation(x.workItems.assign,{client:t,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}},VB=[FT,LT,MT,qT,KT];var Eu=[...bI,...eF,...dF,...uL,...cL,...LL,...UL,...BL,...LB,...KB,...FB,...vV,...$V,...MD,...NL,...AB,...wI,...QI,...SD,...WL,...zL,...JL,...QL,..._L,...yL,...VB,...pK,...tj,...kV,...rj,...aB,...hB,...RV,...LV,...KV,...UV,...zV,...wB,...IB,...jI];for(let e of Eu){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:j$(e.usage.category,n.join(" "))})}var BB="0.1.226";function UB(){return Eu.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=L$[mo(t)];return{path:t,effect:ho(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(UB,"plexusCommandCatalog");import fs from"node:path";function e7(e){let n=cn()?.workspaceRoot??process.cwd(),t=fs.resolve(n,e),r=fs.relative(n,t);if(fs.isAbsolute(e)||r===".."||r.startsWith(`..${fs.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(e7,"workspacePath");function n7(e){let{absolute:n,relative:t}=e7(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Cr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=fs.join(o,a.name);if(a.isDirectory()?i(l):r.push(fs.relative(n,l)),r.length>200)throw new Error("plexus: the workspace contains too many files. List a subdirectory.")}},"visit");return i(n),{files:r.sort()}}if(!t)throw new Error("plexus: name a workspace file.");if(["read","search","edit"].includes(e.operation)){let r=he(n);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:t,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:t,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 ze(n,a,"utf8"),{path:t,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 Ln(fs.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return gs(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(n7,"plexusWorkspace");function GB(e){return s(async function(t,r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("plexus: tool input must be an object.");let i=r,o=$l[t];if(!o||!Object.hasOwn($l,t))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(t==="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(t==="plexus_skill"){if(typeof i.path!="string"||i.path.length>240||!Object.hasOwn(Sy,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:Sy[i.path],skillHash:bf}}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 n7(i)},"executePlexusAgentTool")}s(GB,"createPlexusAgentToolExecutor");var lg=GB({inspectCommand:WB,executeCommand:YB});function dg(){let e=new bs({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:BB});e.register(cl.HelpCommand),e.register(cl.VersionCommand);for(let t of Eu)e.register(t);async function n(t,r){let i;try{i=e.process(t,r)}catch(o){return(r.stderr??process.stderr).write(e.error(o,{colored:!1})),2}return i7(i,r.stderr??process.stderr),e.run(i,r)}return s(n,"run"),{process(t,r){return e.process(t,r)},run:n,async runExit(t,r){process.exitCode=await n(t,r)}}}s(dg,"createPlexusCli");function i7(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&hl[t]===r&&ln(n,t,r),t in hl&&ho(t)==="confirm"&&!gl(e)&&n.write(`plexus-cli: \`${hl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11544
11544
  `)}s(i7,"noteRetiredPath");function WB(e){let n=dg().process(nl(e),{executePlexusAgentTool:lg}),t=n.path.join(" ");if(t.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=UB().find(l=>l.path===t);if(!r){if(t===""||t==="--help"||t==="--version")return{path:t,writes:!1,host:"shared"};throw new Error(`plexus: command ${t} has no host classification.`)}let i=n,o=r.effect==="callKind"?Fm(Na(Ca),i.fn??"",i.kind):void 0,a=af(t,{confirm:gl(n),callKind:o});return{...r,writes:a}}s(WB,"inspectPlexusCommand");async function YB(e,n){if(n)return BT(n,()=>YB(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 t="",r="",i=dg();if(cn()){let l=WB(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(nl(e.argv),{executePlexusAgentTool:lg,stdin:r7.from(e.stdin===void 0?[]:[e.stdin]),stdout:new zB({write(l,d,c){t+=String(l),c()}}),stderr:new zB({write(l,d,c){r+=String(l),c()}})}),stdout:t,stderr:r}}s(YB,"executePlexusCommand");YT({source:o7.join(import.meta.dirname,"skill")});dg().runExit(nl(process.argv.slice(2)),{executePlexusAgentTool:lg});
11545
11545
  //# sourceMappingURL=cli.mjs.map