@smartkomm/plexus-cli 0.1.232 → 0.1.234

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
@@ -10207,7 +10207,7 @@ through the real primitive \u2014 see
10207
10207
  (snapshot) \u2014 the route picks the mode from the envelope's \`livemode\`; \`/stripe/webhook\`
10208
10208
  answers **503** naming the variable (not 400 \u2014 "cannot check" is not "did not
10209
10209
  check out"); payments then settle only through the 5-minute poll.
10210
- `,"references/stripe/request-and-verify-a-payment.md":'# Eine Stripe-Zahlung anfordern und nachverfolgen\n\nWof\xFCr: eine Einmalzahlung \xFCber Stripe ausl\xF6sen und ihren Weg bis `succeeded`\nverfolgen \u2014 lokal, auf Staging oder in Produktion. Voraussetzung ist eine\nverbundene Schule: [Schule mit Stripe verbinden](./connect-a-school.md).\n\nF\xFCr die Hand statt f\xFCrs Skript gibt es dasselbe unter **Administration \u2192\nIntegrationen** (`/$tenant/admin/integrations`) \u2014 gleiche Funktionen, gleiche\nRechte, nur mit Kn\xF6pfen. Dieses Playbook ist der skriptbare Weg.\n\nF\xFCr Zahlungen hat `plexus-cli stripe` (noch) keine eigenen Befehle \u2014 die Gruppe\nverbindet nur die Schule; der Zahlungsadapter wird \xFCber `plexus-cli call`\nbedient (`plexus-cli functions --grep stripe` listet die Funktionen).\n\n## 0. Verbindung pr\xFCfen\n\n```bash\nplexus-cli --env local --json call stripe:status client=<tenant>\n```\n\n`configured: false` nennt in `missing`/`invalid` genau die Variablen, an denen es\nliegt. `modes` nennt je erkl\xE4rtem Modus (`test` = Sandbox, `live`), ob er\nspricht; `realMoneyMode` sagt, worin echte Bewerbungen zahlen.\n\n## 1. Zahlung anfordern\n\n```bash\nplexus-cli --env local --json call stripe:create --kind mutation \\\n client=<tenant> \\\n mode=test \\\n amountMinor=18000 \\\n currency=eur \\\n description="Anmeldegebuehr Schuljahr 2026/27" \\\n customerEmail=eltern@beispiel.example \\\n requestKey=admissionFee:<applicationId> \\\n returnPath=/<tenant>/e/bewerbung/<applicationId>\n```\n\n- **`mode` w\xE4hlt das Konto der Schule**: `test` die Sandbox (Testkarte, kostenlos),\n `live` echtes Geld \u2014 nur wo die Deployment live spricht.\n- **`amountMinor` sind CENT**, nicht Euro. 180 \u20AC sind `18000`.\n- **`requestKey` leitet sich aus der Sache ab**, f\xFCr die gezahlt wird \u2014 nie aus\n einem Zeitstempel. Derselbe Schl\xFCssel gibt dieselbe Zeile zur\xFCck\n (`reused: true`), solange ein Versuch l\xE4uft oder die Forderung bezahlt ist.\n- **`returnPath` ist ein app-relativer Pfad.** Eine absolute URL wird abgewiesen.\n\n## 2. Zustand lesen\n\n```bash\nplexus-cli --env local --json call stripe:get client=<tenant> stripePaymentId=<id>\n```\n\n`checkoutUrl` ist die Zahlungsseite (nur solange `status: open`). `events` zeigt\ndie von Stripe zugestellten, signaturgepr\xFCften R\xFCckrufe.\n\n## 3. Wenn nichts passiert\n\nZuerst: **das ist normal, bis jemand zahlt.** Danach der Reihe nach:\n\n```bash\n# von Hand abgleichen (der Cron tut es alle 5 Minuten von selbst)\nplexus-cli --env local --json call stripe:reconcileNow --kind mutation \\\n client=<tenant> stripePaymentId=<id>\n```\n\n- `status: requires_session` l\xE4nger als ein paar Sekunden \u21D2 die Aktion ist\n gescheitert. `error` auf der Zeile nennt Stripes Grund; nach zehn Minuten\n markiert der Reaper sie als `failed`.\n- `status: processing` \u21D2 SEPA. Stripe selbst r\xE4t zu **mindestens sechs\n Werktagen** Geduld, bevor man eine Lastschrift als erfolgreich betrachtet.\n- Keine `events`, obwohl gezahlt wurde \u21D2 der Webhook kommt nicht an (das richtet\n der Plattformbetreiber ein); der Abgleich-Cron holt es trotzdem ein.\n\n## 4. Zur\xFCckziehen\n\n```bash\nplexus-cli --env local --json call stripe:cancel --kind mutation \\\n client=<tenant> stripePaymentId=<id> reason="Platz anderweitig vergeben"\n```\n\nSchlie\xDFt erst die Seite bei Stripe, dann die Zeile. Eine bereits eingegangene\nZahlung wird dabei **nie** zur\xFCckgezogen \u2014 der Aufruf gleicht sie stattdessen ab.\n',"references/test-actions/drive-a-test-application.md":`# Drive a test application through test mode
10210
+ `,"references/stripe/request-and-verify-a-payment.md":'# Eine Stripe-Zahlung anfordern und nachverfolgen\n\nWof\xFCr: eine Einmalzahlung \xFCber Stripe ausl\xF6sen und ihren Weg bis `succeeded`\nverfolgen \u2014 lokal, auf Staging oder in Produktion. Voraussetzung ist eine\nverbundene Schule: [Schule mit Stripe verbinden](./connect-a-school.md).\n\nF\xFCr die Hand statt f\xFCrs Skript gibt es dasselbe unter **Administration \u2192\nIntegrationen** (`/$tenant/admin/integrations`) \u2014 gleiche Funktionen, gleiche\nRechte, nur mit Kn\xF6pfen. Dieses Playbook ist der skriptbare Weg.\n\nF\xFCr Zahlungen hat `plexus-cli stripe` (noch) keine eigenen Befehle \u2014 die Gruppe\nverbindet nur die Schule; der Zahlungsadapter wird \xFCber `plexus-cli call`\nbedient (`plexus-cli functions --grep stripe` listet die Funktionen).\n\n## 0. Verbindung pr\xFCfen\n\n```bash\nplexus-cli --env local --json call stripe:status client=<tenant>\n```\n\n`configured: false` nennt in `missing`/`invalid` genau die Variablen, an denen es\nliegt. `modes` nennt je erkl\xE4rtem Modus (`test` = Sandbox, `live`), ob er\nspricht; `realMoneyMode` sagt, worin echte Bewerbungen zahlen.\n\n## 1. Zahlung anfordern\n\n```bash\nplexus-cli --env local --json call stripe:create --kind mutation \\\n client=<tenant> \\\n mode=test \\\n amountMinor=18000 \\\n currency=eur \\\n description="Anmeldegebuehr Schuljahr 2026/27" \\\n customerEmail=eltern@beispiel.example \\\n requestKey=admissionFee:<applicationId> \\\n returnPath=/<tenant>/e/bewerbung/<applicationId>\n```\n\n- **`mode` ist `test`**: Testen l\xE4uft immer \xFCber die Sandbox (Testkarte,\n kostenlos). `live` verweigert `stripe:create` \u2014 Live-Bereitschaft belegt der\n Zustand (`stripe platform status`, Konto `ready`, `stripe_events`), nie eine\n bezahlte Probe.\n- **`amountMinor` sind CENT**, nicht Euro. 180 \u20AC sind `18000`.\n- **`requestKey` leitet sich aus der Sache ab**, f\xFCr die gezahlt wird \u2014 nie aus\n einem Zeitstempel. Derselbe Schl\xFCssel gibt dieselbe Zeile zur\xFCck\n (`reused: true`), solange ein Versuch l\xE4uft oder die Forderung bezahlt ist.\n- **`returnPath` ist ein app-relativer Pfad.** Eine absolute URL wird abgewiesen.\n\n## 2. Zustand lesen\n\n```bash\nplexus-cli --env local --json call stripe:get client=<tenant> stripePaymentId=<id>\n```\n\n`checkoutUrl` ist die Zahlungsseite (nur solange `status: open`). `events` zeigt\ndie von Stripe zugestellten, signaturgepr\xFCften R\xFCckrufe.\n\n## 3. Wenn nichts passiert\n\nZuerst: **das ist normal, bis jemand zahlt.** Danach der Reihe nach:\n\n```bash\n# von Hand abgleichen (der Cron tut es alle 5 Minuten von selbst)\nplexus-cli --env local --json call stripe:reconcileNow --kind mutation \\\n client=<tenant> stripePaymentId=<id>\n```\n\n- `status: requires_session` l\xE4nger als ein paar Sekunden \u21D2 die Aktion ist\n gescheitert. `error` auf der Zeile nennt Stripes Grund; nach zehn Minuten\n markiert der Reaper sie als `failed`.\n- `status: processing` \u21D2 SEPA. Stripe selbst r\xE4t zu **mindestens sechs\n Werktagen** Geduld, bevor man eine Lastschrift als erfolgreich betrachtet.\n- Keine `events`, obwohl gezahlt wurde \u21D2 der Webhook kommt nicht an (das richtet\n der Plattformbetreiber ein); der Abgleich-Cron holt es trotzdem ein.\n\n## 4. Zur\xFCckziehen\n\n```bash\nplexus-cli --env local --json call stripe:cancel --kind mutation \\\n client=<tenant> stripePaymentId=<id> reason="Platz anderweitig vergeben"\n```\n\nSchlie\xDFt erst die Seite bei Stripe, dann die Zeile. Eine bereits eingegangene\nZahlung wird dabei **nie** zur\xFCckgezogen \u2014 der Aufruf gleicht sie stattdessen ab.\n',"references/test-actions/drive-a-test-application.md":`# Drive a test application through test mode
10211
10211
 
10212
10212
  **When to use:** walk a test application through an offer from the terminal \u2014 load a form
10213
10213
  scenario and submit it, fill the file fields, submit a form \u2014 exactly what the cockpit's
@@ -11096,7 +11096,7 @@ plexus-cli --env prod jobs list --status running # nothing unexpectedly in
11096
11096
  ## Related
11097
11097
  - Command reference: \`plexus-cli jobs list --help\`, \`plexus-cli platform workers reap --help\`,
11098
11098
  \`plexus-cli platform imports cleanup-orphaned --help\`.
11099
- `};var Zf="fda3f54920feb22c3e2799638c739c0c47c5c1a6ce22881a6c99331d10482c45",rw=aO;var iw=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:Zf,tools:Bl}),0}},ow=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 tw(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},lO=[iw,ow];var sw=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],Qce=new Set(sw.map(e=>e.key));var Ye=["de","en"];function Bs(e,n){return Ye.every(t=>e[t]===n[t])}s(Bs,"sameText");function Dn(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(Dn,"missingLocales");function Ui(e){let n=Dn(e);return n!=="not-localized"&&n.length===0}s(Ui,"isLocalizedText");function Ul(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(Ul,"composeTexts");function Xf(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(Xf,"slugify");var dO="tenant";function cO(e){if(e.length===0||Xf(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===dO)return`"${dO}" is reserved for the tenant-wide scope`}s(cO,"unitSlugError");var I1=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function nr(e,n){return`${e}-${n}`}s(nr,"runStorageKey");function uO(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(uO,"bareRunKey");function ep(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Dn(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"||!I1.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(ep,"runSpecIssues");var O1="-stufe-",_1=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function aw(e){return`${e}${O1}`}s(aw,"stageKeyPrefix");function Us(e,n){return`${aw(e)}${n}`}s(Us,"stageStorageKey");function pO(e,n){let t=aw(e);return n.startsWith(t)&&n.length>t.length}s(pO,"isUnderProgram");function Yr(e,n){let t=aw(e);return pO(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(Yr,"bareStageKey");function np(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Dn(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"||!_1.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(np,"stageSpecIssues");function fO(e){return{de:e.de.trim(),en:e.en.trim()}}s(fO,"trimmedText");function P1(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(P1,"describeNameChange");function tp(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:fO(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:fO(a)},u=Us(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 y={};Bs(h.name,c.name)||(y.name=[h.name,c.name]);let k=h.gradeLevel??null,w=c.gradeLevel??null;k!==w&&(y.gradeLevel=[k,w]),h.sequence!==p&&(y.sequence=[h.sequence,p]),(Object.keys(y).length>0||h.archived)&&o.push({op:"update",key:c.key,stageId:h.stageId,name:c.name,changes:y,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:pO(e,a.key)?Yr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(tp,"planStageReconcile");function rp(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(P1(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(rp,"describeStageStep");function ip(e,n){return n.startsWith(e)&&n.length>e.length?n.slice(e.length):void 0}s(ip,"bareUnder");function hO(e,n,t,r){let i=e.flatMap(y=>y.angebote).find(y=>y.offerKey===n);if(i===void 0){let y=e.flatMap(k=>k.angebote.map(w=>w.offerKey));throw new We(`applications start-test: no offer "${n}" (offers: ${y.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=Us(o,""),l=nr(o,""),d=s(y=>ip(a,y)??"(no bundle key)","stageLabel"),c=s(y=>ip(l,y)??"(no bundle key)","runLabel"),u=i.stages.find(y=>y.stageKey===Us(o,r)||y.stageId===r);if(u===void 0){let y=i.stages.map(b=>`${d(b.stageKey)} (${b.stageId})`).join(", "),k=ip(a,r),w=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}${w} \u2014 name it by its bundle key or id: ${y}`)}let p=d(u.stageKey),h=u.runs.find(y=>y.runKey===nr(o,t)||y.runId===t);if(h===void 0){let y=u.runs.map(b=>`${c(b.runKey)} (${b.runId})`).join(", "),k=ip(l,t),w=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}${w} \u2014 name it by its bundle key or id: ${y}`)}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(hO,"resolveStartTarget");function N1(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(N1,"applicantText");function gO(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:N1(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(gO,"applicationRows");var mO=sw.map(e=>e.email);function yO(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(Xy(e,n)&&(r===void 0||!mO.includes(r.trim().toLowerCase())))throw new We(`applications start-test: on prod only for the test account ${mO.join(", ")} (--applicant) \u2014 never a real family's`)}s(yO,"assertStartApplicant");function wO(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(wO,"processStoreJson");function C1(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(C1,"refText");function D1(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?C1(e.ref):JSON.stringify(e.value)}s(D1,"holds");function kO(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:D1(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(kO,"storeRows");function op(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(op,"parseKv");var bO="started",sp="submitted",ap="submitted",vO="load-scenario:";var xO="(Bewerbung)";function SO(e){return{nodeId:xO,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(SO,"sharedAsList");function AO(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(AO,"disabledText");function EO(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:AO(r)})))}s(EO,"actionRows");function TO(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: ${AO(a)}`);if(i!==xO)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(TO,"nodeOfferingAction");function $O(e,n,t){if(e.startsWith(vO)){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($O,"runParams");async function F1(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(F1,"currentNodeIds");function L1(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(L1,"refusalText");async function lp(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${L1(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,SO(r.actions)]}s(lp,"actionsOf");async function RO(e,n,t){return t!==void 0?[t]:await F1(e,n)}s(RO,"nodesOf");var lw=class extends D{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 lp(n,this.application,await RO(n,this.application,this.node));return this.print(t,EO,["node","action","label","disabled"]),0}},dw=class extends D{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=$O(this.action,this.autoSubmit,op(this.param??[]).values),t=await this.caller(),r=this.application,i=await RO(t,this.application,this.node),o=TO(await lp(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}},IO=[lw,dw];var Sr=/^[a-z][A-Za-z0-9]*$/;function cw(e){return typeof e=="string"&&Sr.test(e)}s(cw,"isNodeId");function Gs(e,n){cw(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${Sr.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(Gs,"makeNodeId");var zi="$env";function de(e){if(e.scope==="env")return`${zi}.${e.key}`;let n=`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(de,"formatAddress");var Gi=/^[a-z][a-zA-Z0-9_]*$/,M1=/^[A-Za-z_][A-Za-z0-9_]*$/;function _o(e){return typeof e=="string"&&e.split(".").every(n=>M1.test(n))}s(_o,"isPath");function ci(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&&_o(i)?{scope:"env",key:i}:null}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Gi.test(o)||(t==="node"?!Sr.test(i):!Gi.test(i))?null:q1({scope:t,owner:i,key:o},a)}default:return null}}s(ci,"tryParseAddress");function q1(e,n){if(n.length===0)return e;let t=n.join(".");return _o(t)?{...e,path:t}:null}s(q1,"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&&!_o(n.path))return!1;switch(n.scope){case"env":return _o(n.key);case"node":return typeof n.owner=="string"&&Sr.test(n.owner)&&typeof n.key=="string"&&Gi.test(n.key);case"task":return typeof n.owner=="string"&&Gi.test(n.owner)&&typeof n.key=="string"&&Gi.test(n.key);default:return!1}}s(we,"isAddress");var ui={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"}},zs=Object.keys(ui);function Ws(e){return Object.hasOwn(ui,e)}s(Ws,"isEnvKey");var K1=["self-service","staff"];function OO(e,n){return{kind:"fixed",values:e,labels:n}}s(OO,"fixedSet");var dp={of:"applicant.language",withoutValue:"de"},fi={"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:dp},"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:dp},"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:dp},"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:dp},"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:OO(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:OO(K1,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},cp={types:ui,fields:fi},up=zs.flatMap(e=>Object.keys(ui[e]).map(n=>`${e}.${n}`));function tr(e){return Object.hasOwn(fi,e)}s(tr,"isEnvLeaf");function fp(e){return`${zi}.${e}`}s(fp,"envIdentifier");function Po(e){let n=fi[e],[t,r]=e.split("."),i=ui[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(Po,"envLeaf");var _O="staffInput";var j1=["boolean"],Gl=/^[a-z][A-Za-z0-9]*$/;function pp(e){return e.staffInputs??[]}s(pp,"staffInputsOf");function mp(e){return`${_O}.${e}`}s(mp,"staffInputLeaf");function PO(e){return`${zi}.${mp(e)}`}s(PO,"staffInputIdentifier");function V1(e){let n=`${_O}.`;return e.startsWith(n)?e.slice(n.length):null}s(V1,"staffInputKeyOfLeaf");function Ys(e,n){let t=V1(n);return t===null?void 0:pp(e).find(r=>r.key===t)}s(Ys,"declaredStaffInput");function NO(e){return[...pp(e).map(n=>({leaf:mp(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...up.map(n=>{let t=Po(n);return{leaf:n,type:t.type,label:t.label,valueSet:fi[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(NO,"envLeavesFor");function CO(e){return NO(e).filter(n=>!n.cohortBound)}s(CO,"conditionEnvLeaves");function DO(e){return LO(CO(e))}s(DO,"envConditionSchemaFor");function B1(e){return NO(e).map(n=>n.leaf==="stage.key"?{...n,valueSet:{kind:"open"}}:n)}s(B1,"offerConditionEnvLeaves");function FO(e){return LO(B1(e))}s(FO,"offerConditionSchemaFor");function LO(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(LO,"schemaOfLeaves");function MO(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}"`};Gl.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),j1.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=Dn(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(MO,"staffInputIssues");var bw={required:!0,description:"Offer slug (its offerKey)"},uw=class extends D{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",bw);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=gO(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},fw=class extends D{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",bw);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}},pw=class extends D{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}},mw=class extends D{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(wO(t),()=>kO(t),["address","state","holds","producer","written"]),0}},hw=class extends D{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",bw);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();yO(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=hO(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:KO(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 lp(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}},gw=class extends D{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=U1(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 U1(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(U1,"parseDays");var yw=class extends D{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}},ww=class extends D{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}},kw=class extends D{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}]=KO([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}},qO=[uw,fw,pw,mw,hw,gw,yw,ww,kw];function KO(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!Gl.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(KO,"parseStaffInputs");var Qn="contractGenerator",No="documentTemplate";function zl(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(zl,"isGeneratorRef");function jO(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(jO,"literalOf");function pi(e){let n=jO(e,Qn);return zl(n)?n:null}s(pi,"generatorRefOfNode");function Ar(e){let n=jO(e,No);return typeof n=="string"&&n.length>0?n:null}s(Ar,"documentTemplateKeyOfNode");function VO(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(VO,"generatorRefLabel");var G1=["formExports","generatorStamp"];function BO(e,n,t){let r=e.inputs?.[Qn];(r?.kind!=="literal"||!zl(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Qn} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Qn]={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(BO,"applyGeneratorStamp");var z1=["reads"];function Hs(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 G1)delete r[i];for(let i of z1)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(Hs,"comparableWorkflowGraph");var Wl={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 hp(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=Wl[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(hp,"manifestIssues");function W1(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(W1,"validateProgressLayoutExternalCopy");function UO(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"]:W1(e)}s(UO,"progressLayoutIssues");var GO=new Set(["nodes","assignmentRules","channels","processStore","staffInputs"]);var Y1=new Set(["sections","effects","outcomes","testScenarios","env","views"]),gp={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 zO(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(Y1.has(i))continue;let o=gp[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(zO,"smartFormDefinitionShapeIssues");var Rt=["granted","rejected","waitlisted","other"];function Wi(e){return typeof e=="string"&&Rt.includes(e)}s(Wi,"isOutcomeSemantic");var rr=["arrival","manual"],WO={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function H1(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(H1,"literal");function vw(e){let n=H1(e,"waitlistOrder");return rr.includes(n)?{waitlistOrder:n}:null}s(vw,"waitlistPolicyOrNull");var wn="responsible",xw="team:";function yp(e){return`${xw}${e}`}s(yp,"teamSlot");function wp(e){return e.startsWith(xw)?e.slice(xw.length):null}s(wp,"teamKeyOfSlot");function YO(e){return e.kind==="responsible"?wn:yp(e.groupKey)}s(YO,"slotIdOf");function kp(e){if(e===wn)return{kind:"responsible"};let n=wp(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(kp,"slotOfId");var Sw="review",Aw="checkField",HO="reviewed",JO="reviewing",bp=["rejected","waitlisted"];function Ew(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ew,"isObject");var J1=new Set(["decision",Sw]),QO={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function Tw(e){return Object.hasOwn(QO,e)?QO[e]:void 0}s(Tw,"legacySemanticOfId");function Q1(e){return e===Sw?Rt.filter(n=>!bp.includes(n)):Rt}s(Q1,"allowedSemanticsFor");var Z1="other";function ZO(e){return Ew(e)&&J1.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(ZO,"outcomesOf");function XO(e){return(e?.nodes??[]).some(n=>ZO(n).some(t=>Ew(t)&&!("semantic"in t)))}s(XO,"needsOutcomeSemantics");function e_(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=ZO(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),p=Q1(u),h=!1,y=l.map(k=>{if(!Ew(k))return k;let w=String(k.id);if("semantic"in k)return Wi(k.semantic)||i.push({nodeId:c,outcomeId:w,value:String(k.semantic)}),k;let b=`${c}.${w}`,E=Object.hasOwn(n,b)?n[b]:void 0;if(E!==void 0)return p.includes(E)?(t.push({nodeId:c,outcomeId:w,semantic:E,source:"answer"}),h=!0,{...k,semantic:E}):(r.push({nodeId:c,nodeType:u,outcomeId:w,allowed:p,answer:E}),k);let T=Tw(w),R=T??Z1;return p.includes(R)?(t.push({nodeId:c,outcomeId:w,semantic:R,source:T===void 0?"formerDefault":"legacyTable"}),h=!0,{...k,semantic:R}):(r.push({nodeId:c,nodeType:u,outcomeId:w,allowed:p}),k)});return h?{...d,outcomes:y}:a});return t.length===0?{graph:e,written:t,refused:r,invalid:i}:{graph:{...e,nodes:o},written:t,refused:r,invalid:i}}s(e_,"addOutcomeSemantics");var Er="bewerbungOffen";function Co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Co,"isObject");var $w=["event","effect"];function n_(e){return Co(e)&&e.type==="eventTrigger"}s(n_,"isTrigger");function t_(e){let n=Co(e.inputs)?e.inputs:{};return"outcomes"in e||$w.some(t=>t in e||t in n)}s(t_,"oldShape");function r_(e){return(e?.nodes??[]).some(n=>n_(n)&&t_(n))}s(r_,"needsEventTriggerStartMove");function X1(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>Co(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===Er))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(Co(e.next)?e.next:{});if(!(i.length===1&&i[0]===Er))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=Co(e.inputs)?{...e.inputs}:{};for(let l of $w){let d=o[l];if(Co(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of $w)delete a[l],delete o[l];return Co(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(X1,"moveNode");function i_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!n_(i)||!t_(i))return i;let o=X1(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(i_,"moveEventTriggerStart");function Yl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Yl,"isObject");var o_={waitlistOrder:"arrival"};function s_(e){return!Yl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(Yl(e.inputs)?e.inputs:{}))}s(s_,"lacksPolicy");function e2(e){return(e?.nodes??[]).some(s_)}s(e2,"needsWaitlistPolicyMove");function Rw(e){return Yl(e)&&rr.includes(e.waitlistOrder)}s(Rw,"isWaitlistPolicy");function n2(e){if(e===void 0)return{policy:o_,stated:!1};if(!Yl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!rr.includes(n)?"malformed":{policy:{waitlistOrder:n??o_.waitlistOrder},stated:n!==void 0}}s(n2,"policyOfSelection");function a_(e,n,t={}){let r=[],i=[];if(!e2(e))return{graph:e,moved:r,refused:i};let o=n2(n),a=e.nodes.map(l=>{if(!s_(l))return l;let d=l,c=String(d.id),u=Yl(d.inputs)?{...d.inputs}:{},p=Object.hasOwn(t,c)?t[c]:void 0,h,y;if(p!==void 0)h=p,y="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;h=o.policy,y=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:h.waitlistOrder},r.push({nodeId:c,policy:h,source:y}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(a_,"moveWaitlistPolicyToInputs");function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Do,"isObject");var t2=[Qn,No],r2=["inputSchema","parties","schemaDigest","parts"];function l_(e){return Do(e)&&e.type==="governedDocument"&&("resolver"in e||Do(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(l_,"oldShape");function d_(e){return(e?.nodes??[]).some(l_)}s(d_,"needsGeneratorInputMove");function i2(e){let n=Do(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!Do(i))return{unmoved:"resolverNotObject"};if(Qn 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((Do(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>Do(d)&&t2.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Qn]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(r2.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(Do(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(No in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[No]={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(i2,"moveNode");function c_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!l_(i))return i;let o=i2(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(c_,"moveGeneratorPinsToInputs");var u_=/^\d{4}-\d{2}-\d{2}$/;function Tr(e,n){return{de:e,en:n}}s(Tr,"issue");function Fo(e){if(typeof e!="object"||e===null)return Tr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:Tr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return Tr(`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?Tr("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"||!u_.test(r)?Tr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!u_.test(i)?Tr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?Tr("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)?Tr("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))?Tr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?Tr("unbekannte Angaben","unknown details"):null:Tr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(Fo,"reductionShapeIssue");function Yi(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||Fo(n.reduction)===null&&n.reduction.kind==="amount")}s(Yi,"isPricedItemValue");var Js=["freetext","recommendation","choice","pricedItem","record","reduction"],Qs=[...Js,"appointment"];function p_(e){return typeof e=="string"&&Qs.includes(e)}s(p_,"isTaskResultKind");function Zs(e){return typeof e=="string"&&Js.includes(e)}s(Zs,"isRecordedTaskResultKind");function Xs(e){return Zs(e.kind)}s(Xs,"isRecordedTaskResult");var vp=["number","boolean","enum","text","person","assignment"];function Iw(e){return typeof e=="string"&&vp.includes(e)}s(Iw,"isRecordFieldType");function m_(e){return e==="number"||e==="boolean"||e==="enum"}s(m_,"isSuggestibleFieldType");var Ow=["form","siblingRank"],xp=500;function o2(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(o2,"recordFieldValueType");var mi={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 _w(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(_w,"isProseResult");function Sp(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&Iw(n.type)).map(n=>({key:n.writes,valueType:o2(n),field:n})):s2(e)}s(Sp,"draftResultStoreWrites");function s2(e){let n=mi[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(s2,"singleStoreWrite");var f_="team:";function ea(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(f_)){let n=e.slice(f_.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(ea,"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 a2=new Set(["if","else","in","true","false","null"]),l2=new Set(["==","!=","<=",">=","&&","||"]);function d2(e){return e>="0"&&e<="9"}s(d2,"isDigit");function c2(e){return/[a-zA-Z_$]/.test(e)}s(c2,"isIdentStart");function u2(e){return/[a-zA-Z0-9_.$]/.test(e)}s(u2,"isIdentCont");function f2(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
11099
+ `};var Zf="beb77e29d41a24e9e7d798e82609379951a54db2287712260ff3f84e5dc41964",rw=aO;var iw=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:Zf,tools:Bl}),0}},ow=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 tw(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},lO=[iw,ow];var sw=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],Qce=new Set(sw.map(e=>e.key));var Ye=["de","en"];function Bs(e,n){return Ye.every(t=>e[t]===n[t])}s(Bs,"sameText");function Dn(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(Dn,"missingLocales");function Ui(e){let n=Dn(e);return n!=="not-localized"&&n.length===0}s(Ui,"isLocalizedText");function Ul(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(Ul,"composeTexts");function Xf(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}s(Xf,"slugify");var dO="tenant";function cO(e){if(e.length===0||Xf(e)!==e)return"must be lowercase a-z/0-9 words joined by single dashes";if(e===dO)return`"${dO}" is reserved for the tenant-wide scope`}s(cO,"unitSlugError");var I1=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function nr(e,n){return`${e}-${n}`}s(nr,"runStorageKey");function uO(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(uO,"bareRunKey");function ep(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Dn(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"||!I1.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(ep,"runSpecIssues");var O1="-stufe-",_1=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function aw(e){return`${e}${O1}`}s(aw,"stageKeyPrefix");function Us(e,n){return`${aw(e)}${n}`}s(Us,"stageStorageKey");function pO(e,n){let t=aw(e);return n.startsWith(t)&&n.length>t.length}s(pO,"isUnderProgram");function Yr(e,n){let t=aw(e);return pO(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(Yr,"bareStageKey");function np(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Dn(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"||!_1.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(np,"stageSpecIssues");function fO(e){return{de:e.de.trim(),en:e.en.trim()}}s(fO,"trimmedText");function P1(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(P1,"describeNameChange");function tp(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:fO(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:fO(a)},u=Us(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 y={};Bs(h.name,c.name)||(y.name=[h.name,c.name]);let k=h.gradeLevel??null,w=c.gradeLevel??null;k!==w&&(y.gradeLevel=[k,w]),h.sequence!==p&&(y.sequence=[h.sequence,p]),(Object.keys(y).length>0||h.archived)&&o.push({op:"update",key:c.key,stageId:h.stageId,name:c.name,changes:y,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:pO(e,a.key)?Yr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(tp,"planStageReconcile");function rp(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(P1(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(rp,"describeStageStep");function ip(e,n){return n.startsWith(e)&&n.length>e.length?n.slice(e.length):void 0}s(ip,"bareUnder");function hO(e,n,t,r){let i=e.flatMap(y=>y.angebote).find(y=>y.offerKey===n);if(i===void 0){let y=e.flatMap(k=>k.angebote.map(w=>w.offerKey));throw new We(`applications start-test: no offer "${n}" (offers: ${y.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=Us(o,""),l=nr(o,""),d=s(y=>ip(a,y)??"(no bundle key)","stageLabel"),c=s(y=>ip(l,y)??"(no bundle key)","runLabel"),u=i.stages.find(y=>y.stageKey===Us(o,r)||y.stageId===r);if(u===void 0){let y=i.stages.map(b=>`${d(b.stageKey)} (${b.stageId})`).join(", "),k=ip(a,r),w=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}${w} \u2014 name it by its bundle key or id: ${y}`)}let p=d(u.stageKey),h=u.runs.find(y=>y.runKey===nr(o,t)||y.runId===t);if(h===void 0){let y=u.runs.map(b=>`${c(b.runKey)} (${b.runId})`).join(", "),k=ip(l,t),w=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}${w} \u2014 name it by its bundle key or id: ${y}`)}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(hO,"resolveStartTarget");function N1(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(N1,"applicantText");function gO(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:N1(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(gO,"applicationRows");var mO=sw.map(e=>e.email);function yO(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(Xy(e,n)&&(r===void 0||!mO.includes(r.trim().toLowerCase())))throw new We(`applications start-test: on prod only for the test account ${mO.join(", ")} (--applicant) \u2014 never a real family's`)}s(yO,"assertStartApplicant");function wO(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(wO,"processStoreJson");function C1(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(C1,"refText");function D1(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?C1(e.ref):JSON.stringify(e.value)}s(D1,"holds");function kO(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:D1(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(kO,"storeRows");function op(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(op,"parseKv");var bO="started",sp="submitted",ap="submitted",vO="load-scenario:";var xO="(Bewerbung)";function SO(e){return{nodeId:xO,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(SO,"sharedAsList");function AO(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(AO,"disabledText");function EO(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:AO(r)})))}s(EO,"actionRows");function TO(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: ${AO(a)}`);if(i!==xO)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(TO,"nodeOfferingAction");function $O(e,n,t){if(e.startsWith(vO)){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($O,"runParams");async function F1(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(F1,"currentNodeIds");function L1(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(L1,"refusalText");async function lp(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${L1(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,SO(r.actions)]}s(lp,"actionsOf");async function RO(e,n,t){return t!==void 0?[t]:await F1(e,n)}s(RO,"nodesOf");var lw=class extends D{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 lp(n,this.application,await RO(n,this.application,this.node));return this.print(t,EO,["node","action","label","disabled"]),0}},dw=class extends D{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=$O(this.action,this.autoSubmit,op(this.param??[]).values),t=await this.caller(),r=this.application,i=await RO(t,this.application,this.node),o=TO(await lp(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}},IO=[lw,dw];var Sr=/^[a-z][A-Za-z0-9]*$/;function cw(e){return typeof e=="string"&&Sr.test(e)}s(cw,"isNodeId");function Gs(e,n){cw(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${Sr.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(Gs,"makeNodeId");var zi="$env";function de(e){if(e.scope==="env")return`${zi}.${e.key}`;let n=`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(de,"formatAddress");var Gi=/^[a-z][a-zA-Z0-9_]*$/,M1=/^[A-Za-z_][A-Za-z0-9_]*$/;function _o(e){return typeof e=="string"&&e.split(".").every(n=>M1.test(n))}s(_o,"isPath");function ci(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&&_o(i)?{scope:"env",key:i}:null}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Gi.test(o)||(t==="node"?!Sr.test(i):!Gi.test(i))?null:q1({scope:t,owner:i,key:o},a)}default:return null}}s(ci,"tryParseAddress");function q1(e,n){if(n.length===0)return e;let t=n.join(".");return _o(t)?{...e,path:t}:null}s(q1,"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&&!_o(n.path))return!1;switch(n.scope){case"env":return _o(n.key);case"node":return typeof n.owner=="string"&&Sr.test(n.owner)&&typeof n.key=="string"&&Gi.test(n.key);case"task":return typeof n.owner=="string"&&Gi.test(n.owner)&&typeof n.key=="string"&&Gi.test(n.key);default:return!1}}s(we,"isAddress");var ui={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"}},zs=Object.keys(ui);function Ws(e){return Object.hasOwn(ui,e)}s(Ws,"isEnvKey");var K1=["self-service","staff"];function OO(e,n){return{kind:"fixed",values:e,labels:n}}s(OO,"fixedSet");var dp={of:"applicant.language",withoutValue:"de"},fi={"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:dp},"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:dp},"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:dp},"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:dp},"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:OO(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:OO(K1,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},cp={types:ui,fields:fi},up=zs.flatMap(e=>Object.keys(ui[e]).map(n=>`${e}.${n}`));function tr(e){return Object.hasOwn(fi,e)}s(tr,"isEnvLeaf");function fp(e){return`${zi}.${e}`}s(fp,"envIdentifier");function Po(e){let n=fi[e],[t,r]=e.split("."),i=ui[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(Po,"envLeaf");var _O="staffInput";var j1=["boolean"],Gl=/^[a-z][A-Za-z0-9]*$/;function pp(e){return e.staffInputs??[]}s(pp,"staffInputsOf");function mp(e){return`${_O}.${e}`}s(mp,"staffInputLeaf");function PO(e){return`${zi}.${mp(e)}`}s(PO,"staffInputIdentifier");function V1(e){let n=`${_O}.`;return e.startsWith(n)?e.slice(n.length):null}s(V1,"staffInputKeyOfLeaf");function Ys(e,n){let t=V1(n);return t===null?void 0:pp(e).find(r=>r.key===t)}s(Ys,"declaredStaffInput");function NO(e){return[...pp(e).map(n=>({leaf:mp(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...up.map(n=>{let t=Po(n);return{leaf:n,type:t.type,label:t.label,valueSet:fi[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(NO,"envLeavesFor");function CO(e){return NO(e).filter(n=>!n.cohortBound)}s(CO,"conditionEnvLeaves");function DO(e){return LO(CO(e))}s(DO,"envConditionSchemaFor");function B1(e){return NO(e).map(n=>n.leaf==="stage.key"?{...n,valueSet:{kind:"open"}}:n)}s(B1,"offerConditionEnvLeaves");function FO(e){return LO(B1(e))}s(FO,"offerConditionSchemaFor");function LO(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(LO,"schemaOfLeaves");function MO(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}"`};Gl.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),j1.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=Dn(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(MO,"staffInputIssues");var bw={required:!0,description:"Offer slug (its offerKey)"},uw=class extends D{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",bw);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=gO(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},fw=class extends D{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",bw);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}},pw=class extends D{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}},mw=class extends D{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(wO(t),()=>kO(t),["address","state","holds","producer","written"]),0}},hw=class extends D{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",bw);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();yO(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=hO(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:KO(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 lp(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}},gw=class extends D{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=U1(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 U1(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(U1,"parseDays");var yw=class extends D{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}},ww=class extends D{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}},kw=class extends D{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}]=KO([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}},qO=[uw,fw,pw,mw,hw,gw,yw,ww,kw];function KO(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!Gl.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(KO,"parseStaffInputs");var Qn="contractGenerator",No="documentTemplate";function zl(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(zl,"isGeneratorRef");function jO(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(jO,"literalOf");function pi(e){let n=jO(e,Qn);return zl(n)?n:null}s(pi,"generatorRefOfNode");function Ar(e){let n=jO(e,No);return typeof n=="string"&&n.length>0?n:null}s(Ar,"documentTemplateKeyOfNode");function VO(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(VO,"generatorRefLabel");var G1=["formExports","generatorStamp"];function BO(e,n,t){let r=e.inputs?.[Qn];(r?.kind!=="literal"||!zl(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Qn} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Qn]={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(BO,"applyGeneratorStamp");var z1=["reads"];function Hs(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 G1)delete r[i];for(let i of z1)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(Hs,"comparableWorkflowGraph");var Wl={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 hp(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=Wl[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(hp,"manifestIssues");function W1(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(W1,"validateProgressLayoutExternalCopy");function UO(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"]:W1(e)}s(UO,"progressLayoutIssues");var GO=new Set(["nodes","assignmentRules","channels","processStore","staffInputs"]);var Y1=new Set(["sections","effects","outcomes","testScenarios","env","views"]),gp={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 zO(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(Y1.has(i))continue;let o=gp[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(zO,"smartFormDefinitionShapeIssues");var Rt=["granted","rejected","waitlisted","other"];function Wi(e){return typeof e=="string"&&Rt.includes(e)}s(Wi,"isOutcomeSemantic");var rr=["arrival","manual"],WO={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function H1(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(H1,"literal");function vw(e){let n=H1(e,"waitlistOrder");return rr.includes(n)?{waitlistOrder:n}:null}s(vw,"waitlistPolicyOrNull");var wn="responsible",xw="team:";function yp(e){return`${xw}${e}`}s(yp,"teamSlot");function wp(e){return e.startsWith(xw)?e.slice(xw.length):null}s(wp,"teamKeyOfSlot");function YO(e){return e.kind==="responsible"?wn:yp(e.groupKey)}s(YO,"slotIdOf");function kp(e){if(e===wn)return{kind:"responsible"};let n=wp(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(kp,"slotOfId");var Sw="review",Aw="checkField",HO="reviewed",JO="reviewing",bp=["rejected","waitlisted"];function Ew(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Ew,"isObject");var J1=new Set(["decision",Sw]),QO={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function Tw(e){return Object.hasOwn(QO,e)?QO[e]:void 0}s(Tw,"legacySemanticOfId");function Q1(e){return e===Sw?Rt.filter(n=>!bp.includes(n)):Rt}s(Q1,"allowedSemanticsFor");var Z1="other";function ZO(e){return Ew(e)&&J1.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(ZO,"outcomesOf");function XO(e){return(e?.nodes??[]).some(n=>ZO(n).some(t=>Ew(t)&&!("semantic"in t)))}s(XO,"needsOutcomeSemantics");function e_(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=ZO(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),p=Q1(u),h=!1,y=l.map(k=>{if(!Ew(k))return k;let w=String(k.id);if("semantic"in k)return Wi(k.semantic)||i.push({nodeId:c,outcomeId:w,value:String(k.semantic)}),k;let b=`${c}.${w}`,E=Object.hasOwn(n,b)?n[b]:void 0;if(E!==void 0)return p.includes(E)?(t.push({nodeId:c,outcomeId:w,semantic:E,source:"answer"}),h=!0,{...k,semantic:E}):(r.push({nodeId:c,nodeType:u,outcomeId:w,allowed:p,answer:E}),k);let T=Tw(w),R=T??Z1;return p.includes(R)?(t.push({nodeId:c,outcomeId:w,semantic:R,source:T===void 0?"formerDefault":"legacyTable"}),h=!0,{...k,semantic:R}):(r.push({nodeId:c,nodeType:u,outcomeId:w,allowed:p}),k)});return h?{...d,outcomes:y}:a});return t.length===0?{graph:e,written:t,refused:r,invalid:i}:{graph:{...e,nodes:o},written:t,refused:r,invalid:i}}s(e_,"addOutcomeSemantics");var Er="bewerbungOffen";function Co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Co,"isObject");var $w=["event","effect"];function n_(e){return Co(e)&&e.type==="eventTrigger"}s(n_,"isTrigger");function t_(e){let n=Co(e.inputs)?e.inputs:{};return"outcomes"in e||$w.some(t=>t in e||t in n)}s(t_,"oldShape");function r_(e){return(e?.nodes??[]).some(n=>n_(n)&&t_(n))}s(r_,"needsEventTriggerStartMove");function X1(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>Co(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===Er))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(Co(e.next)?e.next:{});if(!(i.length===1&&i[0]===Er))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=Co(e.inputs)?{...e.inputs}:{};for(let l of $w){let d=o[l];if(Co(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of $w)delete a[l],delete o[l];return Co(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(X1,"moveNode");function i_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!n_(i)||!t_(i))return i;let o=X1(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(i_,"moveEventTriggerStart");function Yl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Yl,"isObject");var o_={waitlistOrder:"arrival"};function s_(e){return!Yl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(Yl(e.inputs)?e.inputs:{}))}s(s_,"lacksPolicy");function e2(e){return(e?.nodes??[]).some(s_)}s(e2,"needsWaitlistPolicyMove");function Rw(e){return Yl(e)&&rr.includes(e.waitlistOrder)}s(Rw,"isWaitlistPolicy");function n2(e){if(e===void 0)return{policy:o_,stated:!1};if(!Yl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!rr.includes(n)?"malformed":{policy:{waitlistOrder:n??o_.waitlistOrder},stated:n!==void 0}}s(n2,"policyOfSelection");function a_(e,n,t={}){let r=[],i=[];if(!e2(e))return{graph:e,moved:r,refused:i};let o=n2(n),a=e.nodes.map(l=>{if(!s_(l))return l;let d=l,c=String(d.id),u=Yl(d.inputs)?{...d.inputs}:{},p=Object.hasOwn(t,c)?t[c]:void 0,h,y;if(p!==void 0)h=p,y="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;h=o.policy,y=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:h.waitlistOrder},r.push({nodeId:c,policy:h,source:y}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(a_,"moveWaitlistPolicyToInputs");function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Do,"isObject");var t2=[Qn,No],r2=["inputSchema","parties","schemaDigest","parts"];function l_(e){return Do(e)&&e.type==="governedDocument"&&("resolver"in e||Do(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(l_,"oldShape");function d_(e){return(e?.nodes??[]).some(l_)}s(d_,"needsGeneratorInputMove");function i2(e){let n=Do(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!Do(i))return{unmoved:"resolverNotObject"};if(Qn 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((Do(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>Do(d)&&t2.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Qn]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(r2.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(Do(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(No in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[No]={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(i2,"moveNode");function c_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!l_(i))return i;let o=i2(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(c_,"moveGeneratorPinsToInputs");var u_=/^\d{4}-\d{2}-\d{2}$/;function Tr(e,n){return{de:e,en:n}}s(Tr,"issue");function Fo(e){if(typeof e!="object"||e===null)return Tr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:Tr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return Tr(`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?Tr("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"||!u_.test(r)?Tr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!u_.test(i)?Tr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?Tr("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)?Tr("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))?Tr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?Tr("unbekannte Angaben","unknown details"):null:Tr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(Fo,"reductionShapeIssue");function Yi(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||Fo(n.reduction)===null&&n.reduction.kind==="amount")}s(Yi,"isPricedItemValue");var Js=["freetext","recommendation","choice","pricedItem","record","reduction"],Qs=[...Js,"appointment"];function p_(e){return typeof e=="string"&&Qs.includes(e)}s(p_,"isTaskResultKind");function Zs(e){return typeof e=="string"&&Js.includes(e)}s(Zs,"isRecordedTaskResultKind");function Xs(e){return Zs(e.kind)}s(Xs,"isRecordedTaskResult");var vp=["number","boolean","enum","text","person","assignment"];function Iw(e){return typeof e=="string"&&vp.includes(e)}s(Iw,"isRecordFieldType");function m_(e){return e==="number"||e==="boolean"||e==="enum"}s(m_,"isSuggestibleFieldType");var Ow=["form","siblingRank"],xp=500;function o2(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(o2,"recordFieldValueType");var mi={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 _w(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(_w,"isProseResult");function Sp(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&Iw(n.type)).map(n=>({key:n.writes,valueType:o2(n),field:n})):s2(e)}s(Sp,"draftResultStoreWrites");function s2(e){let n=mi[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(s2,"singleStoreWrite");var f_="team:";function ea(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(f_)){let n=e.slice(f_.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(ea,"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 a2=new Set(["if","else","in","true","false","null"]),l2=new Set(["==","!=","<=",">=","&&","||"]);function d2(e){return e>="0"&&e<="9"}s(d2,"isDigit");function c2(e){return/[a-zA-Z_$]/.test(e)}s(c2,"isIdentStart");function u2(e){return/[a-zA-Z0-9_.$]/.test(e)}s(u2,"isIdentCont");function f2(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
11100
11100
  `||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(d2(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(c2(r)){let o=t;for(;o<e.length&&u2(e.charAt(o));)o++;let a=e.slice(t,o);a2.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(l2.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(f2,"tokenise");var h_=1e4,g_=128;function na(e){e.depth++,e.depth>g_&&F(`Expression nesting too deep (> ${g_})`)}s(na,"enterDepth");function x_(e){return e.pos<e.tokens.length?e.tokens[e.pos]:null}s(x_,"peek");function Zn(e){let n=e.tokens[e.pos];return n||F(`Unexpected end at ${e.pos}`),e.pos++,n}s(Zn,"take");function Xn(e,n,t){let r=x_(e);return!(!r||r.t!==n||t!==void 0&&r.v!==t)}s(Xn,"match");function Lo(e,n,t){return Xn(e,n,t)||F(`Expected ${n}${t?`:${t}`:""} at ${e.pos}`),Zn(e)}s(Lo,"expect");function gi(e){na(e);try{return Xn(e,"kw","if")?p2(e):m2(e)}finally{e.depth--}}s(gi,"parseExpr");function p2(e){Lo(e,"kw","if"),Lo(e,"punct","(");let n=gi(e);Lo(e,"punct",")");let t=gi(e);Lo(e,"kw","else");let r=gi(e);return{kind:"if",cond:n,then:t,else:r}}s(p2,"parseIf");function m2(e){let n=y_(e),t=0;try{for(;Xn(e,"op","||");){Zn(e),na(e),t++;let r=y_(e);n={kind:"binary",op:"||",left:n,right:r}}}finally{e.depth-=t}return n}s(m2,"parseLogicOr");function y_(e){let n=w_(e),t=0;try{for(;Xn(e,"op","&&");){Zn(e),na(e),t++;let r=w_(e);n={kind:"binary",op:"&&",left:n,right:r}}}finally{e.depth-=t}return n}s(y_,"parseLogicAnd");function w_(e){let n=k_(e),t=0;try{for(;Xn(e,"op","==")||Xn(e,"op","!=");){let r=Zn(e).v;na(e),t++;let i=k_(e);n={kind:"binary",op:r,left:n,right:i}}}finally{e.depth-=t}return n}s(w_,"parseEquality");function k_(e){let n=Nw(e),t=0;try{for(;Xn(e,"op","<")||Xn(e,"op","<=")||Xn(e,"op",">")||Xn(e,"op",">=")||Xn(e,"kw","in");){let r=Zn(e),i=r.t==="kw"?"in":r.v;na(e),t++;let o=Nw(e);n={kind:"binary",op:i,left:n,right:o}}}finally{e.depth-=t}return n}s(k_,"parseCompare");function Nw(e){if(Xn(e,"op","!")){Zn(e),na(e);try{return{kind:"unary",op:"!",operand:Nw(e)}}finally{e.depth--}}return h2(e)}s(Nw,"parseUnary");function h2(e){let n=x_(e);if(n||F("Unexpected end"),n.t==="num")return Zn(e),{kind:"num",value:n.v};if(n.t==="str")return Zn(e),{kind:"str",value:n.v};if(n.t==="kw"&&n.v==="true")return Zn(e),{kind:"bool",value:!0};if(n.t==="kw"&&n.v==="false")return Zn(e),{kind:"bool",value:!1};if(n.t==="kw"&&n.v==="null")return Zn(e),{kind:"null"};if(n.t==="punct"&&n.v==="("){Zn(e);let t=gi(e);return Lo(e,"punct",")"),t}if(n.t==="punct"&&n.v==="["){Zn(e);let t=[];if(!Xn(e,"punct","]"))for(t.push(gi(e));Xn(e,"punct",",");)Zn(e),t.push(gi(e));return Lo(e,"punct","]"),{kind:"arr",items:t}}if(n.t==="ident"){let t=n.v;if(Zn(e),Xn(e,"punct","(")){Zn(e);let r=[];if(!Xn(e,"punct",")"))for(r.push(gi(e));Xn(e,"punct",",");)Zn(e),r.push(gi(e));return Lo(e,"punct",")"),{kind:"call",name:t,args:r}}return{kind:"ident",path:t}}F(`Unexpected token at ${e.pos}`)}s(h2,"parsePrimary");function Fn(e){e.length>h_&&F(`Expression too long (${e.length} > ${h_})`);let n={tokens:f2(e),pos:0,depth:0},t=gi(n);return n.pos<n.tokens.length&&F(`Unexpected trailing token at ${n.pos}`),t}s(Fn,"parseExpression");var g2=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 kn(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=>kn(t,n));case"unary":{let t=kn(e.operand,n);return!Mo(t)}case"call":{let t=n.functions!==void 0&&Object.hasOwn(n.functions,e.name)?n.functions[e.name]:g2.get(e.name);t||F(`Unknown function '${e.name}'`);let r=e.args.map(i=>kn(i,n));return t(...r)}case"binary":return y2(e.op,e.left,e.right,n);case"if":return Mo(kn(e.cond,n))?kn(e.then,n):kn(e.else,n)}}s(kn,"evaluate");function y2(e,n,t,r){if(e==="&&"){let a=kn(n,r);return Mo(a)?Mo(kn(t,r)):!1}if(e==="||"){let a=kn(n,r);return Mo(a)?!0:Mo(kn(t,r))}let i=kn(n,r),o=kn(t,r);switch(e){case"==":return Pw(i,o);case"!=":return!Pw(i,o);case"<":{let[a,l]=Ap(i,o);return a!==null&&l!==null&&a<l}case"<=":{let[a,l]=Ap(i,o);return a!==null&&l!==null&&a<=l}case">":{let[a,l]=Ap(i,o);return a!==null&&l!==null&&a>l}case">=":{let[a,l]=Ap(i,o);return a!==null&&l!==null&&a>=l}case"in":return Array.isArray(o)?o.some(a=>Pw(a,i)):!1}}s(y2,"evalBinary");function Ap(e,n){return[b_(e),b_(n)]}s(Ap,"orderedOperands");function b_(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(b_,"numericOperand");function Pw(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(Pw,"looseEq");function Mo(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(Mo,"truthy");function Ln(e){let n=new Set;return hi(e,n),[...n]}s(Ln,"dependencies");function hi(e,n){switch(e.kind){case"ident":n.add(e.path);return;case"call":e.args.forEach(t=>hi(t,n));return;case"arr":e.items.forEach(t=>hi(t,n));return;case"unary":hi(e.operand,n);return;case"binary":hi(e.left,n),hi(e.right,n);return;case"if":hi(e.cond,n),hi(e.then,n),hi(e.else,n);return;default:return}}s(hi,"walk");var v_=new Map;function yi(e){let n=v_.get(e);return n||(n=Fn(e),v_.set(e,n)),n}s(yi,"parseCached");function w2(e,n){return kn(yi(e),n)}s(w2,"evalExpression");function S_(e,n){return Mo(w2(e,n))}s(S_,"evalBoolean");function A_(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(A_,"assertNoCustomNodeExports");var Cw=null;function E_(e){for(let[n,t]of Object.entries(e))A_(n,t);Cw=e}s(E_,"setSpecs");function T_(){return Cw||F("[workflow/registry] Specs not initialised. Import convex/model/admission/specs before calling specFor()."),Cw}s(T_,"requireSpecs");function Je(e){let n=T_(),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 $_(){return Object.keys(T_()).sort()}s($_,"registeredNodeTypes");var R_=up.filter(e=>fi[e].cohortBound!==!0);function Dw(e){return tr(e)&&fi[e].cohortBound!==!0}s(Dw,"isEnvAddressLeaf");function Fw(e){return Po(e).type}s(Fw,"envType");function Lw(e){return Po(e).label}s(Lw,"envLabel");function Mw(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(Mw,"addressBase");function $r(e){return e.scope==="node"&&e.key===Un&&e.path===void 0}s($r,"isInstanceAddress");function un(e){return we(e)&&e.scope==="node"&&e.key===Un&&e.path!==void 0}s(un,"isFormFieldAddress");function I_(e){return un(e)?{owner:e.owner,path:e.path}:null}s(I_,"formFieldOf");function k2(e){return Ln(yi(e)).map(n=>{if(!n.startsWith("$"))return{identifier:n,address:null,reason:"bareIdentifier"};let t=ci(n);return t===null?{identifier:n,address:null,reason:"shape"}:{identifier:n,address:t}})}s(k2,"expressionAddresses");var Un="admission",qw="document",Tp="contract",$p="contracts",O_="payment",Kw=new Set(["adoptForm","setFlagTarget","form","familyRequestFrom"]);var gt={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"},xpe={join:{...gt},end:{...gt},eventTrigger:{...gt},form:{...gt,adoptForm:"address",formExports:"stamp"},roleAssign:{...gt},setFlag:{...gt},if:{...gt,condition:"address"},countersign:{...gt,contract:"address",titles:"display",signing:"config"},engagePush:{...gt,engage:"tenantRef",form:"address",contract:"address",payment:"address"},decision:{...gt,commentRequired:"config",decisionAsTask:"config",reads:"address",view:"config",requiresOneOf:"config"},review:{...gt,form:"address",commentRequired:"config",decisionAsTask:"config"},waitlist:{...gt},completenessCheck:{...gt,requires:"address",deadline:"config"},collectPayment:{...gt},governedDocument:{...gt,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 Hr(e){return Array.isArray(e)?e:[]}s(Hr,"listOf");function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(yt,"record");function __(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(__,"dataSourceFieldsOf");function P_(e){return e.type==="review"?[]:e.type==="engagePush"?["form"]:__(e)}s(P_,"requiredDataSourceFields");var b2={setFlag:{target:"setFlagTarget"}};function Hl(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=b2[e.type]??{};for(let[d,c]of Object.entries(yt(r.inputs)??{})){let u=yt(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 y=a.get(d);o("binding",`${i}.inputs.${d}`,p,y!==void 0?{expectedType:y}:{})}for(let[d,c]of Hr(r.reads).entries())o("nodeReads",`${i}.reads.${d}`,c,{judgedTogether:`${i}.reads`});for(let[d,c]of Hr(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 __(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(yt(r.assign)??{}))for(let[u,p]of Hr(c).entries()){let h=yt(p)?.when;h!=null&&o("teamWhen",v2(e.id,d,u),h,{expectedType:"boolean"})}for(let[d,c]of Hr(r.tasks).entries())t.push(...N_(e.id,c,d));for(let[d,c]of Hr(r.optionalActions).entries()){let u=yt(c);u?.when!==void 0&&o("optionalActionWhen",x2(e.id,typeof u.key=="string"?u.key:String(d)),u.when)}return t}s(Hl,"nodeAddressFields");function v2(e,n,t){return`nodes.${e}.assign.${n}.${t}.when`}s(v2,"teamWhenPath");function x2(e,n){return`nodes.${e}.optionalActions.${n}.when`}s(x2,"optionalActionWhenPath");function N_(e,n,t){let r=yt(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,y,k={})=>{i.push({kind:p,at:h,nodeId:e,taskKey:o,value:y,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 Hr(r.reads).entries())l("taskReads",`${a}.reads.${p}`,h,{judgedTogether:d});for(let[p,h]of Hr(r.inputs).entries())l("taskInput",`${a}.inputs.${p}`,h);for(let[p,h]of Hr(r.documents).entries()){let y=yt(h);y===null||y.kind!=="field"||l("taskDocument",`${a}.documents.${p}`,y.address)}let c=yt(r.familyRequest);if(c!==null){for(let[p,h]of Hr(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=yt(r.result);if(u?.kind==="record")for(let[p,h]of Hr(u.fields).entries()){let y=yt(yt(h)?.suggest);if(y?.kind!=="form")continue;let k=yt(h)?.type;l("suggest",`${a}.result.fields.${p}.suggest`,"address"in y?y.address:y.key,typeof k=="string"?{expectedType:k}:{})}return i}s(N_,"taskAddressFields");function ta(e){return jw(e)?(Vw(e.value)??[]).flatMap(n=>n.address===null?[]:[n.address]):we(e.value)?[e.value]:[]}s(ta,"addressesInField");function jw(e){return e.kind==="condition"||e.kind==="optionalActionWhen"}s(jw,"isExpressionField");function Vw(e){if(typeof e!="string"||e.trim().length===0)return null;try{yi(e)}catch{return null}return k2(e)}s(Vw,"conditionAddresses");function It(e){return e.type==="form"&&e.adoptForm!==void 0&&e.adoptForm!==!1}s(It,"adoptsForm");function C_(e){if(e.type!=="form"||It({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(C_,"createdSmartFormSlug");function S2(e,n){return e.type!=="governedDocument"||e.production!=="resolver"||n!==qw?n:e.generatorStamp?.parts!==void 0?$p:Tp}s(S2,"addressKeyOfPort");function D_(e){let n=e.result;return n===void 0||!Xs(n)?[]:Sp(n).map(t=>t.key)}s(D_,"storeWritesOf");function Bw(e,n){return(Array.isArray(e.processStore)?e.processStore:[]).find(t=>t.key===n)}s(Bw,"declaredKey");function Jr(e,n){let t=[];if(!It(n))for(let r of Je(n).outputs?.(n)??[])t.push({address:{scope:"node",owner:n.id,key:S2(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 D_(r)){let o=Bw(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(Jr,"producedAddresses");function F_(e,n,t){for(let r of e.nodes)for(let i of Array.isArray(r.tasks)?r.tasks:[])if(i.key===n&&D_(i).includes(t))return{nodeId:r.id,template:i};return null}s(F_,"taskWriter");function wi(e,n,t){return F_(e,n,t)?.nodeId??null}s(wi,"taskOwnerNode");function A2(e){return Hl(e,{slotTypes:!1}).flatMap(n=>ta(n).map(t=>({address:t,field:n})))}s(A2,"writtenAddressesOf");function qo(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=F_(e,a.owner,a.key);if(d!==null){for(let c of N_(d.nodeId,d.template))if(!(c.kind!=="taskWhen"&&c.kind!=="taskReads"))for(let u of ta(c))i(u,"evidence",l,a)}},"carried");for(let{address:a,field:l}of A2(n))i(a,"written",l),o(a,l);return t}s(qo,"addressReadsOf");function Jl(e,n){switch(n.scope){case"env":return tr(n.key)?Fw(n.key):Ys(e,n.key)?.type;case"task":return n.path!==void 0||wi(e,n.owner,n.key)===null?void 0:Bw(e,n.key)?.type;case"node":{let t=e.nodes.find(i=>i.id===n.owner);if(t===void 0)return;let r=Jr(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(Jl,"addressType");function Ep(e,n){let t=yt(e)?.[n];return typeof t=="string"&&t.length>0?t:void 0}s(Ep,"labelText");function _e(e,n,t){let r=e.nodes.find(i=>i.id===n);return Ep(r?.label,t)??n}s(_e,"nodeDisplayName");function Ko(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 Ep(i.title,t)??n}return n}s(Ko,"taskDisplayName");function je(e,n,t){let r=[];switch(n.scope){case"env":r.push(tr(n.key)?Lw(n.key)[t]:Ys(e,n.key)?.label[t]??n.key);break;case"task":r.push(Ko(e,n.owner,t),Ep(Bw(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:Jr(e,i).find(a=>a.address.scope==="node"&&a.address.key===n.key);r.push(Ep(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 Ql=["beneficiary","signers"];function Zl(e){let n=[];for(let[t,r]of Object.entries(yt(e.inputs)??{})){let i=yt(r);i?.kind==="binding"&&we(i.address)&&n.push({slot:t,address:i.address})}return n}s(Zl,"bindingAddresses");function L_(e,n){return Zl(e).find(t=>t.slot===n)?.address??null}s(L_,"bindingAddressAt");function M_(e,n){let t=s(i=>i.scope==="node"&&i.owner===n||i.scope==="task"&&wi(e,i.owner,i.key)===n,"names");return e.nodes.filter(i=>i.id!==n).flatMap(i=>Hl(i,{slotTypes:!1})).flatMap(i=>ta(i).filter(t).map(o=>({at:i.at,nodeId:i.nodeId,address:o})))}s(M_,"addressesNaming");var Mn={target:"target",flagKey:"flagKey",value:"value"};function E2(e){return L_(e,Mn.target)}s(E2,"setFlagTarget");function q_(e){let n=E2(e);return n!==null&&$r(n)?n.owner:null}s(q_,"setFlagTargetOwner");function Rp(e){let n=e.inputs?.[Mn.flagKey];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(Rp,"setFlagKey");function K_(e){let n=e.inputs?.[Mn.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)}": \`${Mn.value}\` is no yes/no literal \u2014 publish refuses that`)}s(K_,"setFlagValue");function j_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(j_,"isObject");var V_=["target","flagKey","value"];function B_(e){return j_(e)&&e.type==="setFlag"&&V_.some(n=>n in e)}s(B_,"oldShape");function U_(e){return(e?.nodes??[]).some(B_)}s(U_,"needsSetFlagInputMove");function T2(e){let n=j_(e.inputs)?{...e.inputs}:{};if(V_.some(a=>a in e&&Mn[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[Mn.target]={kind:"binding",address:t}),typeof r=="string"&&r.length>0&&(n[Mn.flagKey]={kind:"literal",value:r}),i!==void 0&&(n[Mn.value]={kind:"literal",value:i}),{node:{...o,inputs:n}}}s(T2,"moveNode");function G_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!B_(i))return i;let o=T2(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(G_,"moveSetFlagConfigToInputs");function z_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(z_,"isObject");var Uw={countersign:{dueInDays:"number"},decision:{allowSkipInTest:"boolean"},completenessCheck:{guestRole:"string"},governedDocument:{responseDueInDays:"number"}},Gw={review:["allowSkipInTest"]};function W_(e){return Uw[String(e)]??{}}s(W_,"movesOf");function Y_(e){return Gw[String(e)]??[]}s(Y_,"deadOf");function H_(e){return z_(e)&&[...Object.keys(W_(e.type)),...Y_(e.type)].some(n=>n in e)}s(H_,"oldShape");function J_(e){return(e?.nodes??[]).some(H_)}s(J_,"needsScalarInputMove");function $2(e,n){return n==="number"?typeof e=="number"&&Number.isInteger(e)&&e>=1:typeof e===n}s($2,"wellTyped");function R2(e){let n=z_(e.inputs)?{...e.inputs}:{},t={...e};for(let[r,i]of Object.entries(W_(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==="")&&!$2(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 Y_(e.type))delete t[r];return t.inputs=n,{node:t}}s(R2,"moveNode");function Q_(e){let n=[],t=[],r=e.nodes.map(i=>{if(!H_(i))return i;let o=R2(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(Q_,"moveScalarConfigToInputs");var ra={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 Ip(e){return typeof e=="string"&&Object.hasOwn(ra,e)}s(Ip,"isResourceType");var Lpe=Object.keys(ra).filter(e=>ra[e].existence.check==="generic");function Z_(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||Fo(n.reduction)===null&&n.reduction.kind==="amount")&&Object.keys(n).every(t=>t==="groupKey"||t==="grantKeys"||t==="reduction")}s(Z_,"isPricedGroupValue");var zw=["street","hausnr","plz","ort","land"];function X_(e){return zw.includes(e)}s(X_,"isAddressPart");var I2=["municipality","municipalityKey","district","districtKey"],Ww=[...zw,...I2],Yw={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"},ia=Object.keys(Yw);function Hi(e){return typeof e=="string"&&e in Yw}s(Hi,"isValueType");function dt(e){return e===void 0?void 0:Yw[e]}s(dt,"dataTypeOf");function Op(e,n){let t=dt(e),r=dt(n);return t!==void 0&&t===r}s(Op,"valueTypesCompatible");function jo(e){return e===null?"null is not a text in both languages":Xl(e,{type:"localizedText"})}s(jo,"completeLocalizedTextIssue");function Xl(e,n){if(Ip(n.type)&&!Hi(n.type))return typeof e=="string"&&e.length>0?null:`${JSON.stringify(e)} is not a ${n.type} key`;let t=dt(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 Z_(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 zl(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=Fo(e);return o===null?null:`${r} is not a reduction \u2014 ${o.en}`}}}s(Xl,"literalTypeIssue");function eP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(eP,"isObject");var O2={collectPayment:{reason:"reason"}},_2={governedDocument:["mockAutoProduce"]},nP={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 O2[String(e)]??{}}s(Hw,"movesOf");function tP(e){return _2[String(e)]??[]}s(tP,"deadOf");function rP(e){return eP(e)&&[...Object.keys(Hw(e.type)),...tP(e.type)].some(n=>n in e)}s(rP,"oldShape");function iP(e){return(e?.nodes??[]).some(rP)}s(iP,"needsNodeConfigInputMove");function P2(e){return jo(e)===null}s(P2,"isCompleteText");function N2(e){let n=eP(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(!P2(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 tP(e.type))delete t[r];return Object.keys(Hw(e.type)).some(r=>r in e)&&(t.inputs=n),{node:t}}s(N2,"moveNode");function oP(e){let n=[],t=[],r=e.nodes.map(i=>{if(!rP(i))return i;let o=N2(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(oP,"moveNodeConfigToInputs");var ed="collectPayment",oa=["online","manual"];function _p(e){return oa.includes(e)}s(_p,"isCollectPaymentMode");var Vo="paid",Jw="skipPayment",Qw="confirmPayment",Ji="article",ct="mode",Qi="reason",ir="payee",Zw=["one_time"];function Pp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Pp,"isObject");function sP(e){if(!Pp(e)||e.type!==ed)return!1;let n=Pp(e.inputs)?e.inputs:{},t=n[ct];return!Pp(t)||t.kind!=="literal"||t.value!=="online"?!1:!(ir in n)}s(sP,"isOnlinePaymentWithoutPayee");function aP(e){return(e?.nodes??[]).some(sP)}s(aP,"needsPayee");function lP(e,n={}){let t=[],r=[],i=e.nodes.map(o=>{if(!sP(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=Pp(o.inputs)?o.inputs:{};return{...o,inputs:{...d,[ir]:{kind:"literal",value:l}}}});return t.length===0?{graph:e,set:t,refused:r}:{graph:{...e,nodes:i},set:t,refused:r}}s(lP,"setPayeeOnOnlinePayments");var dP="settlement",C2={online:"online",separate:"manual"};function Xw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Xw,"isObject");function cP(e){return Xw(e)&&e.type===ed&&Xw(e.inputs)&&dP in e.inputs}s(cP,"carriesSettlement");function uP(e){return(e?.nodes??[]).some(cP)}s(uP,"needsPaymentModeRename");function fP(e){let n=[],t=[],r=e.nodes.map(i=>{if(!cP(i))return i;let o=String(i.id),{[dP]:a,...l}=i.inputs;if(ct in l)return t.push({nodeId:o,reason:"bothCells"}),i;let d=Xw(a)&&a.kind==="literal"&&typeof a.value=="string"?C2[a.value]:void 0;return d===void 0?(t.push({nodeId:o,reason:"unknownValue"}),i):(n.push(o),{...i,inputs:{...l,[ct]:{...a,value:d}}})});return n.length===0?{graph:e,moved:n,refused:t}:{graph:{...e,nodes:r},moved:n,refused:t}}s(fP,"renameSettlementToMode");var mP="formView";function Np(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Np,"isObject");function ek(e){return Array.isArray(e.tasks)?e.tasks:[]}s(ek,"tasksOf");function nd(e){return Np(e)&&mP in e}s(nd,"carriesFormView");function hP(e){return(e?.nodes??[]).some(n=>nd(n)||Np(n)&&ek(n).some(nd))}s(hP,"needsFormViewMove");function pP(e){let{[mP]: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(pP,"moved");function gP(e){let n=[],t=[],r=e.nodes.map(i=>{if(!Np(i))return i;let o=String(i.id),a=i;if(nd(a)){let l=pP(a);typeof l=="string"?t.push({nodeId:o,reason:l}):(a=l,n.push(o))}return ek(a).some(nd)&&(a={...a,tasks:ek(a).map(l=>{if(!nd(l))return l;let d=String(l.key),c=pP(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(gP,"moveFormViewToView");function Dp(e){if(!Array.isArray(e))return[{code:"shape",index:null,detail:`expected a list of rows, got ${Cp(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=F2(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:D2(t,r)}),n}s(Dp,"teamRulesShapeIssues");function D2(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(D2,"defaultLastDetail");function nk(e,n){let t=Dp(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(nk,"readTeamRules");function Fp(e){return Dp(e).length===0?e:null}s(Fp,"tryReadTeamRules");function Kt(e){return Lp([],e)}s(Kt,"fixedTeam");function Lp(e,n){return nk([...e.map(({when:t,team:r})=>({when:t,team:r})),{when:null,team:n}],"a constructed team position")}s(Lp,"teamRulesOf");function tk(e,n){return e===void 0?Kt(n):Lp(e.slice(0,-1),n)}s(tk,"withDefaultTeam");function yP(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(yP,"defaultTeamOf");function wP(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(wP,"shadowedRows");function F2(e){if(typeof e!="object"||e===null||Array.isArray(e))return`expected { when, team }, got ${Cp(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 ${Cp(n.team)}`:"when"in n?n.when!==null&&!we(n.when)?`"when" must be an address or null, got ${Cp(n.when)}`:null:'"when" is missing \u2014 the default row says `when: null`'}s(F2,"rowShapeProblem");function Cp(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(Cp,"describe");function kP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(kP,"isObject");function bP(e){return kP(e)&&kP(e.assign)?e.assign:null}s(bP,"assignOf");function vP(e){return(e?.nodes??[]).some(n=>Object.values(bP(n)??{}).some(t=>typeof t=="string"))}s(vP,"needsNodeAssignFold");function xP(e){let n=[],t=[],r=e.nodes.map(i=>{let o=bP(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]=Kt(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(xP,"foldNodeAssignToTeamRules");function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Qr,"isObject");function rk(e){return Array.isArray(e.tasks)?e.tasks:[]}s(rk,"tasksOf");function td(e){return Qr(e)&&Array.isArray(e.documents)?e.documents:[]}s(td,"documentsOf");function rd(e){return Qr(e)&&e.kind==="document"}s(rd,"isDocumentRef");function SP(e){return(e?.nodes??[]).some(n=>Qr(n)&&rk(n).some(t=>td(t).some(rd)))}s(SP,"needsDocumentRefMove");function L2(e,n){let t=n.address;if(!Qr(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=>Qr(a)&&a.id===t.owner),i=Qr(r)&&Array.isArray(r.artifacts)?r.artifacts:[];if(i.length!==1)return null;let o=Qr(i[0])?i[0].key:void 0;return typeof o=="string"&&o.length>0?o:null}s(L2,"slotOf");function AP(e){let n=[],t=[],r=e.nodes.map(i=>{if(!Qr(i)||!rk(i).some(a=>td(a).some(rd)))return i;let o=String(i.id);return{...i,tasks:rk(i).map(a=>{if(!Qr(a)||!td(a).some(rd))return a;let l=String(a.key),d=td(a).map(p=>rd(p)?L2(e.nodes,p):void 0);if(d.includes(null))return t.push({nodeId:o,taskKey:l,reason:"noSlot"}),a;let c=new Set,u=td(a).flatMap((p,h)=>{let y=rd(p)?{kind:"artifact",key:d[h]}:p;if(!Qr(y)||y.kind!=="artifact")return[y];let k=String(y.key);return c.has(k)?[]:(c.add(k),[y])});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(AP,"moveDocumentRefsToArtifact");function Mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Mp,"isObject");function ik(e){return Mp(e)&&Mp(e.assign)&&"userId"in e.assign}s(ik,"namesUser");function qp(e){return(e?.nodes??[]).flatMap(n=>Mp(n)&&Array.isArray(n.tasks)?n.tasks.filter(ik).map(t=>({nodeId:String(n.id),taskKey:String(t.key),hasTeam:typeof t.assign.group=="string"&&t.assign.group.length>0})):[])}s(qp,"taskUserAssignments");function EP(e){let n=qp(e);if(n.length===0)return{graph:e,dropped:n};let t=e.nodes.map(r=>{if(!Mp(r)||!Array.isArray(r.tasks)||!r.tasks.some(ik))return r;let i=r.tasks.map(o=>{if(!ik(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(EP,"dropTaskAssignUserIds");function $P(e,n,t){let r=Dp(e);return r.length>0?r.map(i=>{let o=i.index===null?n:`${n}.${i.index}`;return i.code==="defaultLast"?TP(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}.`}):TP(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}.`})}):wP(e).map(({index:i,first:o})=>RP(`${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($P,"teamRulesIssues");function RP(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:e,reason:t,severity:n}}s(RP,"issue");function TP(e,n){return RP(e,"error",n)}s(TP,"error");var sa={"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"}}},ok=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,"record");function Kp(e,n){if(typeof n!="string"||n.length===0)return null;if(e==="key")return n;let t=ea(n);return t?.kind==="team"?t.groupKey:null}s(Kp,"decodeKey");var IP={"assign{}":"assign","actionTeams{}":"actionTeams"},M2=s(e=>e in IP,"isMapLeaf");function q2(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(q2,"locate");function jp(e){let n=[],t=e;for(let[r,i]of Object.entries(IP))for(let[o,a]of Object.entries(ok(t[i])??{})){if(r==="assign{}"){let l=Fp(a);if(l===null){n.push({path:`${i}.${o}`,leaf:r,owner:o,key:Kp("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:Kp("key",a),missing:typeof a!="string"||a.length===0})}for(let r of Object.keys(sa)){if(M2(r))continue;let i=sa[r],{list:o,field:a,key:l}=q2(r);for(let d of Array.isArray(t[o])?t[o]:[]){let c=ok(d);if(c===null||typeof c.key!="string")continue;let p=(a===null?c:ok(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((w,b)=>{n.push({path:`${h}.${b}`,leaf:r,owner:k,index:b,key:Kp(i.codec,w),missing:typeof w!="string"||w.length===0})});continue}let y=typeof p!="string"||p.length===0;n.push({path:`${o}.${c.key}${a===null?"":`.${a}`}.${l}`,leaf:r,owner:c.key,key:Kp(i.codec,p),missing:y})}}return n}s(jp,"nodeResourceReferences");var OP=s(e=>(e??[]).map(n=>`\u201E${n}\u201C`).join(", "),"list"),_P=s(e=>(e??[]).map(n=>`"${n}"`).join(", "),"listEn"),K2={"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 (${OP(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 (${_P(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 (${OP(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 (${_P(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 aa(e,n,t){let{problem:r,remedy:i}=K2[e][t](n);return`[${e}] ${r} ${i}`}s(aa,"addressMessage");var PP={type:"enum",dataType:"option"};function NP(e,n){return e.enumOptionLabels?.[n]??{de:n,en:n}}s(NP,"inlineEnumOptionLabel");var DP={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function Vp(e){return DP[e]!==void 0}s(Vp,"isExportableFieldType");function j2(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(j2,"leafForComputed");function CP(e){let n=DP[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:NP(e,t)}))}:{}}}s(CP,"leafFor");function sk(e){let n=[],t=s(r=>{for(let i of r.fields)i.export===!0&&n.push(CP(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&n.push(CP(o));for(let i of r.computed??[])i.export===!0&&n.push(j2(i));for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(sk,"exportedFormLeaves");function or(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(or,"derivedEdges");function ak(e){let n=new Map;for(let t of or(e.nodes)){let r=n.get(t.source)??[];r.push(t.target),n.set(t.source,r)}return n}s(ak,"successorsOf");function la(e,n,t){if(n===t)return!0;let r=ak(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(la,"dominates");function FP(e,n,t){if(n===t)return!0;let r=ak(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(FP,"reaches");function LP(e,n,t,r){let i=new Map(e.nodes.map(d=>[d.id,d])),o=ak(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(LP,"reachedAvoiding");function lk(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(la(e,i.id,n))for(let o of Jr(e,i))t.push(r(o));for(let i of R_)t.push({address:{scope:"env",key:i},type:Fw(i),label:Lw(i),nodeId:null});for(let i of pp(e))t.push({address:{scope:"env",key:mp(i.key)},type:i.type,label:i.label,nodeId:null});return t}s(lk,"visibleAddressesAt");function Zr(e,n){let t=e?.readinessFormFieldsByFormNode?.get(n.owner);if(t!==void 0)return t.get(n.path)??null}s(Zr,"formFieldEntryOf");var MP={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"}},V2=new Set(["nodeReads","requires","taskReads","taskDocument","familyRequestFields"]);function B2(e,n,t){let r=[];n.taskKey!==void 0&&r.push(`${t==="de"?"Aufgabe":"task"} \u201E${Ko(e,n.taskKey,t)}\u201C`);let i=n.kind==="binding"?` \u201E${n.at.split(".").pop()}\u201C`:"";return r.push(`${MP[n.kind][t]}${i}`),r.join(" \u203A ")}s(B2,"addressFieldWhere");function id(e,n,t){let r=B2(e,n,t);return`\u201E${_e(e,n.nodeId,t)}\u201C \u203A ${r}`}s(id,"whereOf");function qP(e,n,t){if(n.scope==="node")return _e(e,n.owner,t);if(n.scope==="task")return Ko(e,n.owner,t)}s(qP,"producerName");function KP(e,n){let t=[],r=new Set,i=s((l,d,c)=>{let u={de:aa(l,c("de"),"de"),en:aa(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=>Hl(l))];for(let l of a){let d=s(c=>id(e,l,c),"where");for(let c of U2(e,l,i))z2(e,l,c,i)&&(Y2(e,l,c,n,i),Kw.has(l.kind)&&!Q2(o,c)&&i("address/notFormInstance",l.at,u=>({where:d(u),address:je(e,c,u)})))}return Z2(e,i),X2(e,a,i),rY(e,i),oY(e,i),t}s(KP,"checkAddresses");function U2(e,n,t){let r=s(i=>id(e,n,i),"where");if(jw(n)){let i=Vw(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 ta(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(U2,"checkFieldShape");function jP(e,n,t,r){let i=qP(e,t,r);return{where:id(e,n,r),address:je(e,t,r),...i!==void 0?{producer:i}:{}}}s(jP,"addressParams");function G2(e,n,t){return Dw(n)||t==="optionalActionWhen"&&(Ys(e,n)!==void 0||tr(n))?null:Ys(e,n)!==void 0?t==="condition"||t==="binding"?null:"address/staffInputConditionOnly":tr(n)?"address/envCohortBound":"address/unknownKey"}s(G2,"envAddressRefusal");function z2(e,n,t,r){let i=s(o=>jP(e,n,t,o),"params");switch(t.scope){case"env":{let o=G2(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)?wi(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):Jr(e,o).some(a=>a.address.scope==="node"&&a.address.key===t.key)?!0:(r(Kw.has(n.kind)&&It(o)?"address/notFormInstance":"address/unknownKey",n.at,i),!1)}}}s(z2,"resolves");function W2(e,n){return e===void 0||n===void 0||dt(n)===void 0?!0:dt(e)!==void 0&&Op(e,n)}s(W2,"addressTypeFits");function Y2(e,n,t,r,i){let o=s(l=>jP(e,n,t,l),"params");if(t.scope!=="env"&&t.path!==void 0&&!J2(e,n,t,r)){i(H2(t,r)?"address/notExported":"address/pathNotInTarget",n.at,o);return}if(n.expectedType===void 0)return;let a=Jl(e,t);W2(a,n.expectedType)||i("address/typeMismatch",n.at,l=>({...o(l),expected:n.expectedType,actual:a}))}s(Y2,"checkPathAndType");function H2(e,n){if(e.scope!=="node"||e.key!==Un||e.path===void 0)return!1;let t=Zr(n,{scope:"node",owner:e.owner,key:Un,path:e.path});return t==null?!1:t.kind==="computed"||!t.repeated&&Vp(t.type)}s(H2,"formFieldUnexported");function J2(e,n,t,r){if(t.scope!=="node")return!1;if(Jl(e,t)!==void 0)return!0;if(t.key!==Un)return!1;if(!V2.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(J2,"pathExists");function Q2(e,n){if(!$r(n))return!1;let t=e.get(n.owner);return t!==void 0&&t.type==="form"&&!It(t)}s(Q2,"isCreatingFormInstance");function Z2(e,n){for(let t of e.nodes){let r=new Set(Hl(t).map(i=>i.kind));for(let i of P_(t))r.has(i)||n("address/missing",`nodes.${t.id}.${i}`,o=>({where:`\u201E${_e(e,t.id,o)}\u201C \u203A ${MP[i][o]}`}))}}s(Z2,"checkRequiredFields");function X2(e,n,t){let r=new Map;for(let i of n)if(i.judgedTogether!==null)for(let o of ta(i)){if(o.scope!=="node"||o.key!==Un)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:id(e,o[0].field,l),names:a.map(d=>_e(e,d,l))}))}}s(X2,"checkMixedForms");function eY(e,n){return e.type==="engagePush"&&n.kind==="payment"}s(eY,"readSkipsAbsentProducer");function nY(e,n,t){return n!==t&&FP(e,n,t)}s(nY,"precedesOnSomePath");function tY(e,n,t,r){let i=Mw(t.address);return r.has(de(i))||!iY(e,i)?!0:t.origin==="written"&&i.scope==="node"&&eY(n,t.field)&&nY(e,i.owner,n.id)}s(tY,"readPassesVisibility");function rY(e,n){for(let t of e.nodes){let r=qo(e,t);if(r.length===0)continue;let i=new Set(lk(e,t.id).map(o=>de(o.address)));for(let o of r){let a=Mw(o.address);if(tY(e,t,o,i))continue;let l=a.scope==="task"?wi(e,a.owner,a.key):a.scope==="node"?a.owner:null;n("address/notVisible",o.field.at,d=>({where:id(e,o.field,d),address:je(e,o.address,d),producer:qP(e,a,d)??je(e,a,d),...l!==null?{producerNode:_e(e,l,d)}:{},reader:_e(e,t.id,d)}))}}}s(rY,"checkVisibility");function iY(e,n){if(n.scope==="env")return Dw(n.key);let t=de(n);return e.nodes.some(r=>Jr(e,r).some(i=>de(i.address)===t))}s(iY,"producedSomewhere");function oY(e,n){let t=new Map;for(let r of e.nodes){let i=new Set(Jr(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"||!Gi.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${Ko(e,r,a)}\u201C`,names:i.map(l=>_e(e,l.nodeId,a))}))}s(oY,"checkTaskKeys");function Bp(e,n){return e.label[n]??""}s(Bp,"wordingIn");function Zi(e,n){let t=VP(e,n),r=Bp(e.qualifier,n);return t===""||r===""&&Bp(e.qualifier,"de")!==""?"":r===""?t:`${r} \xB7 ${t}`}s(Zi,"fieldLabelIn");function VP(e,n){return Bp(e,n)}s(VP,"fieldOwnLabelIn");function da(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:Zi(e,"de"),en:Zi(e,"en")}}}s(da,"catalogField");function ca(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(ca,"catalogFieldRefusal");function Up(e,n){let t=e.buses.find(r=>r.key===n);return t||F(`[progress] layout '${e.id}' has no bus '${n}'`),t}s(Up,"progressBus");function od(e,n){return e.states.some(t=>t.id===n)}s(od,"isBusState");function BP(e,n){let t=e.terminalSemantics?.[n];return t||F(`[progress] no terminal semantics for state '${n}' on bus '${e.key}'`),t}s(BP,"terminalSemantics");function Gp(e,n){return!!e.terminalSemantics&&Object.prototype.hasOwnProperty.call(e.terminalSemantics,n)}s(Gp,"hasTerminalSemantics");function sY(e,n){return(e.boards??[]).find(t=>t.audience===n||t.audience==="both")??null}s(sY,"boardForAudience");function UP(e){return sY(Up(e,"process"),"internal")}s(UP,"internalProcessBoard");function ua(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(ua,"resolveProgressEvent");var fa={approved:"enrolled",rejected:"declined",withdrawn:"declined",expired:"declined"},ki=Object.keys(fa);function Bo(e){return Object.hasOwn(fa,e)}s(Bo,"isEndNodeOutcome");var dk={approved:{de:"Angenommen",en:"Admitted"},rejected:{de:"Abgelehnt",en:"Rejected"},withdrawn:{de:"Zur\xFCckgezogen",en:"Withdrawn"},expired:{de:"Abgelaufen",en:"Expired"}};var Xi=["commit","discard"],lhe=m.union(...Xi.map(e=>m.literal(e)));function zp(e){return typeof e=="string"&&Xi.includes(e)}s(zp,"isApplicationDataDecision");function Gn(e){return Object.keys(e)}s(Gn,"progressEventsOf");var te=s((e,n)=>({de:e,en:n}),"lt"),nn=s((e,n,t,r,i=null,o=null)=>({chipLabel:e,tone:n,nextAction:i,affordance:o,title:t,body:r}),"ex"),GP={key:"eingeschrieben",label:te("Eingeschrieben","Enrolled"),scope:"global",defaultCollapsed:!0},Wp={key:"abgesagt",label:te("Abgesagt","Declined"),scope:"global",track:"exit",defaultCollapsed:!0},zP={key:"abgelehnt",label:te("Abgelehnt","Rejected"),scope:"global",track:"exit",defaultCollapsed:!0};var WP={enrolled:{label:te("Eingeschrieben","Enrolled"),tone:"green",terminal:{lifecycleStatus:"completed",outcome:"approved"},phase:GP,external:nn(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:Wp,external:nn(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."))}},YP={role:"effect",effect:"pure",progressDefaults:WP,progressEvents:Gn(WP),inputs:s(()=>[{id:"applicationOutcome",label:{de:"Ergebnis",en:"Outcome"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:ki.map(e=>({value:e,label:dk[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=>[...aY(e),...lY(e),...dY(e)],"validate")},pa=s((e,n,t,r)=>({layer:"GRAPH",kind:"nodeRule",path:`node.${e.id}.inputs.${n}`,reason:{de:t,en:r},severity:"error"}),"nodeIssue");function Uo(e){let n=e.inputs?.applicationOutcome;return n?.kind==="literal"&&n.value!=null?String(n.value):null}s(Uo,"literalOutcome");function aY(e){if(e.type!=="end")return[];let n=e.inputs?.applicationOutcome;if(n===void 0||n.kind==="unset")return[];let t=Uo(e);return t===null?[pa(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`)]:Bo(t)?[]:[pa(e,"applicationOutcome",`[end/applicationOutcome] ${e.label.de}: '${t}' ist kein Ausgang eines Endknotens (${ki.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 (${ki.join("|")}) \u2014 the waitlist ends through the closed outcome of its waitlist node`)]}s(aY,"checkEndApplicationOutcome");function lY(e){if(e.type!=="end")return[];let n=e.inputs?.dataDecision;return!n||n.kind!=="literal"||n.value==null?[pa(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)`)]:zp(n.value)?[]:[pa(e,"dataDecision",`[end/dataDecision] ${e.label.de}: dataDecision '${String(n.value)}' ist ung\xFCltig (${Xi.join("|")})`,`[end/dataDecision] ${e.label.en}: dataDecision '${String(n.value)}' is invalid (${Xi.join("|")})`)]}s(lY,"checkEndDataDecision");function dY(e){if(e.type!=="end")return[];let n=Uo(e);if(n===null||!Bo(n)||n==="approved")return[];let t=e.inputs?.dataDecision;if(t?.kind!=="literal"||t.value!=="commit")return[];let r=dk[n];return[{...pa(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(dY,"checkEndCommitWithoutApproval");function HP(e,n){if(!n?.layout||!n.wiring)return[];let t=[];for(let r of e.nodes){if(r.type!=="end")continue;let i=Uo(r);if(i===null||!Bo(i))continue;let o=fa[i],a=ua(n.wiring,r,o);if(a===null)continue;let l=n.layout.buses.find(c=>c.key===a.bus);if(l===void 0||!Gp(l,a.state))continue;let d=BP(l,a.state).outcome;d!==i&&t.push(pa(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(HP,"checkEndOutcomeMatchesTerminal");function ma(e){let n=Je(e);return typeof n.inputs=="function"?n.inputs(e):[]}s(ma,"inputSlots");function cY(e,n){return ma(e).find(t=>t.id===n)}s(cY,"findInputSlot");function uY(e,n){let t=cY(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(uY,"resolveInput");function JP(e){return ma(e).filter(n=>uY(e,n.id).source==="missing")}s(JP,"missingRequiredInputs");var fY=["personRef","formRef","documentRef","docRef"];function pY(e){let n=Je(e);return typeof n.inputs!="function"?[]:n.inputs(e).map(t=>({id:t.id,type:t.type}))}s(pY,"listInputs");function QP(e){let n=[];for(let t of e.nodes)for(let r of pY(t))!fY.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(QP,"findParamValueRefSlotErrors");function ZP(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(ZP,"findInspectorKindErrors");function XP(e){let n=[];for(let t of e.nodes)for(let r of JP(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(XP,"findMissingRequiredInputs");function Yp(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(Yp,"processStoreKeys");function eN(e){let n=[];for(let t of e.tasks??[]){let r=t.result;if(!(r===void 0||!Xs(r)))for(let i of Sp(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(eN,"storeWritersOn");function nN(e){let n=new Map;for(let t of e.nodes)for(let r of eN(t)){let i=n.get(r.key)??[];i.push(r),n.set(r.key,i)}return n}s(nN,"processStoreWriters");function mY(e,n,t){for(let r of e.nodes){let i=eN(r).find(o=>o.taskKey===n&&o.key===t);if(i!==void 0)return i}return null}s(mY,"writerAt");function hY(e,n,t){(n.scope!=="task"||n.path!==void 0)&&F(`[process] ${t}: ${de(n)} is no task value`);let r=mY(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(hY,"sourceOfAddress");function tN(e,n){(n.scope!=="task"||n.path!==void 0)&&F(`[process] ${de(n)} is no store address`);let t=Yp(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:hY(e,n,de(n))}}s(tN,"processLeafOf");var ck=new Set(["enum","pricedItem","number","boolean","reduction","string","staffUser","staffUserList","taskAssignment"]),wt={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 kt(e,n,t,r){return{layer:"GRAPH",kind:"contractGap",path:e,reason:{de:`${n} ${t}`,en:`${n} ${r}`},severity:"error"}}s(kt,"err");function iN(e){let n=[],t=Yp(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(kt(c,wt.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(kt(c,wt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}" ist doppelt deklariert.`,`Process key "${d.key}" is declared twice.`)),i.add(d.key),ck.has(d.type)||n.push(kt(c,wt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}" hat den Typ "${d.type}" \u2014 der Vorgang speichert nur Ergebnisse mit Wert: ${[...ck].join(", ")}.`,`Process key "${d.key}" has the type "${d.type}" \u2014 the process only stores results with a value: ${[...ck].join(", ")}.`)),(!d.label?.de?.trim()||!d.label?.en?.trim())&&n.push(kt(c,wt.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(kt(c,wt.invalidKey,`Vorgangs-Schl\xFCssel "${d.key}": audience muss 'internal' oder 'printable' sein.`,`Process key "${d.key}": audience must be 'internal' or 'printable'.`))}let o=nN(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(kt(`node.${l.id}.tasks.${d.key}.result.writes`,wt.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(kt(p,wt.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}"`,y=u.fieldKey===void 0?`Task "${u.taskKey}"`:`Field "${u.fieldKey}" of task "${u.taskKey}"`;n.push(kt(p,wt.writerTypeMismatch,`${h} liefert ${u.valueType}, der Vorgangs-Schl\xFCssel "${l}" ist aber als ${c.type} deklariert.`,`${y} 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(kt(`processStore.${l}`,wt.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(kt(`processStore.${l.key}`,wt.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=gY(e,p.address);if(h===null)continue;let y=`node.${l.id}.input.${u.id}`,k=de(p.address),w=a.get(h.source.key)??new Set;w.add(l.id),a.set(h.source.key,w),h.audience==="internal"&&n.push(kt(y,wt.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=yY(o,h.source.key,h.source.taskKey);if(b.template.when!==void 0&&u.required===!0&&u.defaultValue===void 0&&n.push(kt(y,wt.absentWithoutDefault,`${l.label.de}: "${u.id}" ist Pflicht und an ${k} gebunden, aber die schreibende Aufgabe entsteht nur unter einer Bedingung (when: ${rN(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: ${rN(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;(!Yi(E)||E.itemKey!==b.result.item||E.grantKeys.length>0)&&n.push(kt(y,wt.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(w=>w.id===p);return k!==void 0&&Je(k).processHoldTemplate?.(k)===u.templateKey})(),y=`node.${c.nodeId}.tasks.${c.taskKey}.blocks`;if(!h){let k=[...d][0],w=e.nodes.find(E=>E.id===k),b=Je(w).processHoldTemplate?.(w)??"?";n.push(kt(y,wt.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||la(e,p,k)||n.push(kt(y,wt.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(iN,"processBindingIssues");function gY(e,n){return!we(n)||n.scope!=="task"||n.path!==void 0||!Yp(e).some(t=>t.key===n.key)||wi(e,n.owner,n.key)===null?null:tN(e,n)}s(gY,"draftLeafOf");function yY(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(yY,"writerOf");function rN(e){return we(e)?de(e):JSON.stringify(e)}s(rN,"shown");var wY="Europe/Berlin";function sN(){return wY}s(sN,"tenantTimeZone");var oN=new Map;function kY(e){let n=oN.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 oN.set(e,t),t}s(kY,"formatterFor");function bY(e,n){let t=new Map(kY(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(bY,"zoneOffsetAt");function uk(e,n){let t=e+bY(n,e);return{wallClock:new Date(t).toISOString().slice(0,19),timeZone:n}}s(uk,"instantToLocalDateTime");function fk(e){let n={};for(let t of Ye)n[t]=e(t);return n}s(fk,"localized");var Go=5,zo=480;function bi(e){return typeof e=="string"&&e.trim().length>0}s(bi,"isNonEmptyString");function lN(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(lN,"unknownFieldIssues");var Hp="primaryHostTeams";function xY(e){let n=[],t=e.title;(t===void 0||typeof t!="object"||t===null||!bi(t.de)||!bi(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<Go||r>zo)&&n.push({field:"result.durationMinutes",code:Ue.appointmentInvalidDuration,message:{de:`'durationMinutes' muss eine ganze Zahl von ${Go} bis ${zo} sein, erhalten ${JSON.stringify(r)}.`,en:`'durationMinutes' must be a whole number from ${Go} to ${zo}, got ${JSON.stringify(r)}.`}});let{[Hp]:i,...o}=e;return n.push(...lN(o,["kind","title","durationMinutes","primaryParticipantTeams","participants"],{de:"Termin-Ergebnis",en:"appointment result"})),n}s(xY,"appointmentIssues");function aN(e){if(typeof e!="object"||e===null)return!1;let n=e;return bi(n.de)&&bi(n.en)}s(aN,"isBilingual");var pk=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom","multiple","tasks","maxLength"];function SY(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(Iw(d.type)||r.push(t(`${l}.type`,{de:`Feld ${u}: Typ ${JSON.stringify(d.type)} \u2014 erlaubt: ${vp.join(", ")}.`,en:`Field ${p}: type ${JSON.stringify(d.type)} \u2014 allowed: ${vp.join(", ")}.`})),aN(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 }).`})),bi(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 y=Array.isArray(d.options)?d.options:[],k=y.map(w=>w.key);(y.length<2||k.some(w=>typeof w!="string"||w.length===0)||new Set(k).size!==k.length||y.some(w=>!aN(w.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 y=typeof d.min=="number"?d.min:0;(d.type!=="number"||d.evidence!==!0||typeof d.evidenceFrom!="number"||!Number.isInteger(d.evidenceFrom)||d.evidenceFrom<=y)&&r.push(t(`${l}.evidenceFrom`,{de:`Feld ${u}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${y}) \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 (${y}) \u2014 otherwise the proof would always apply.`}))}if(r.push(...AY(d,l,u,p,n)),d.suggest!==void 0){let y=d.suggest,k=typeof y=="object"&&y!==null?y.kind:void 0,w=k==="form"&&"address"in y&&Object.keys(y).length===2&&(!we(y.address)||un(y.address))||k==="siblingRank"&&Object.keys(y).length===1&&d.type==="number";m_(d.type)?w||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: ${Ow.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: ${Ow.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(y=>!pk.includes(y));h.length>0&&r.push(t(l,{de:`Feld ${u}: unbekannte Angabe ${h.map(y=>`'${y}'`).join(", ")}; erlaubt: ${pk.join(", ")}.`,en:`Field ${p}: unknown entry ${h.map(y=>`'${y}'`).join(", ")}; allowed: ${pk.join(", ")}.`}))}return r}s(SY,"recordFieldIssues");function AY(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>xp)&&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 ${xp}.`,en:`Field ${r}: 'maxLength' exists only for type 'text', as a whole number from 1 to ${xp}.`}}),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(AY,"typedFieldIssues");function EY(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(!bi(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||!bi(a.de)||!bi(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(...SY(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"&&(bi(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"?ea(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(...lN(n,["kind","options","textRequired","chat","item","label","writes","fields","prices"],{de:"Aufgaben-Ergebnis",en:"task result"})),r}s(EY,"recordedIssues");function dN(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: ${Qs.join(", ")}.`,en:`'result' must be an object with 'kind'; known kinds: ${Qs.join(", ")}.`}}];let r=n;return p_(r.kind)?r.kind==="appointment"?xY(r):EY(r.kind,r,t):[{field:"result.kind",code:Ue.unknownKind,message:{de:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${Qs.join(", ")}.`,en:`Unknown result kind ${JSON.stringify(r.kind)}; known kinds: ${Qs.join(", ")}.`}}]}s(dN,"taskResultIssues");function mk(e){let n=Je(e);return e.outcomes&&e.outcomes.length>0?[...e.outcomes]:n.outcomes&&n.outcomes.length>0?[...n.outcomes]:null}s(mk,"nodeOutcomes");var TY=["documentChangeRequested","documentReturned","coverLetterConfirmed","coverLetterRevisionRequested"];function cN(e){return TY.includes(e)}s(cN,"isNonAdvancingExternalEvent");var ha=["offer","contract"];function Jp(e){return typeof e=="string"&&ha.includes(e)}s(Jp,"isArtifactSlotType");var uN="open",ga="done";var fN=[{key:"tenantSlug",type:"string"}];var $Y=/^(\d{4})-(\d{2})-(\d{2})$/;function RY(e){return e>=1900&&e<=2100}s(RY,"isSupportedYear");function IY(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(IY,"isRealDate");function hk(e){if(typeof e!="string")return null;let n=$Y.exec(e);if(n===null)return null;let[,t,r,i]=n;return t===void 0||r===void 0||i===void 0||!RY(Number(t))||!IY(Number(t),Number(r),Number(i))?null:{year:t,month:r,day:i}}s(hk,"isoDateParts");var gk=3;function pN(e){return uk(e,sN()).wallClock.slice(0,10)}s(pN,"localIsoDate");var Qp=["login","security","admission","tasks","deadlines","schoolMessages","staffAssigned","staffTeamQueue","staffFeedback","staffAppointments","staffDeadlines","staffWaitlist","staffUnassigned","familyMessages","mentions"],mN=m.union(...Qp.map(e=>m.literal(e)));var _ge=m.union(m.literal("admission"),m.literal("tasks"),m.literal("staff"),m.literal("chat")),yk=["loginOnly","all"],Pge=m.union(m.literal("loginOnly"),m.literal("all"));function hN(e){return typeof e=="string"&&yk.includes(e)}s(hN,"isMailLevel");function gN(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=30}s(gN,"isUnassignedTaskNoticeDays");function yN(e){return e*864e5}s(yN,"unassignedTaskNoticeMs");var Dge=yN(3),Fge=yN(1);var sd="subject";function wN(e){return e.category==="login"}s(wN,"isSignInLetter");var fn={key:"schoolName",label:"Name der Schule"},xN={de:"Zu Ihren Bewerbungen",en:"View your applications"},An={key:"portalLink",label:"Link zum Bewerberportal",required:!0,link:!0,actionLabel:xN},wk={key:An.key,label:An.label,link:!0,actionLabel:xN},SN={key:"authorName",label:"Name der schreibenden Person"},Wo={key:"applicationLink",label:"Link zur Bewerbung",required:!0,link:!0,actionLabel:{de:"Bewerbung \xF6ffnen",en:"Open application"}},ad={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"}},OY={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"}},AN={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"}},ld={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"15 Minuten",en:"15 minutes"}},EN={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"24 Stunden",en:"24 hours"}},_Y={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"60 Minuten",en:"60 minutes"}};function $e(e){return{key:sd,label:"Betreff",default:e}}s($e,"subjectSlot");var eo=m.object({de:m.string(),en:m.string()}),On={tenantSlug:m.string(),applicationId:m.id("applications")},PY=m.object({tenantSlug:m.string()}),NY={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:PY,channels:["email"],portalVisible:!0,placeholders:[fn,An],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:
11101
11101
 
11102
11102
  {{portalLink}}`,en:`Thank you for registering with {{schoolName}}. You can view and continue your applications at any time using the link below:
@@ -11185,7 +11185,7 @@ You can check the current status at any time here:
11185
11185
 
11186
11186
  Der Link gilt 30 Tage und antwortet in Ihrem Namen. Bitte leiten Sie diese E-Mail nicht weiter.`,en:`{{feedbackLink}}
11187
11187
 
11188
- The link is valid for 30 days and answers in your name. Please do not forward this email.`}}]},uH=m.object({tenantSlug:m.string(),recipientUserId:m.id("users"),workItemId:m.id("work_items"),taskTitle:m.string(),actionLabel:m.string()}),fH={key:"actionLabel",label:"Was pausiert hat",subjectSafe:!0},pH={id:"staff.taskResumed",category:"staffAssigned",label:"Aufgabe kann weitergef\xFChrt werden",occasion:{de:"Sobald eine Aufgabe, die eine optionale Aktion (z. B. Taster Day) oder die Nachbearbeitung durch die Familie pausiert hat, weitergef\xFChrt werden kann \u2014 an die Person, die sie hat (nicht an die, die die Pause beendet hat)",en:"When a task paused by an optional action (e.g. Taster Day) or by the family's rework can be continued \u2014 to the person who has it (not to whoever ended the pause)"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:uH,channels:["email"],portalVisible:!1,placeholders:[cd,fH,Xp],slots:[$e({de:"Kann weitergef\xFChrt werden: {{taskTitle}}",en:"Can be continued: {{taskTitle}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"\u201E{{actionLabel}}\u201C ist beendet. Diese Aufgabe kann weitergef\xFChrt werden:",en:"\u201C{{actionLabel}}\u201D has ended. This task can be continued:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Direkt zur Aufgabe:
11188
+ The link is valid for 30 days and answers in your name. Please do not forward this email.`}}]},uH=m.object({tenantSlug:m.string(),recipientUserId:m.id("users"),workItemId:m.id("work_items"),taskTitle:m.string(),actionLabel:m.string()}),fH={key:"actionLabel",label:"Worauf die Aufgabe gewartet hat",subjectSafe:!0},pH={id:"staff.taskResumed",category:"staffAssigned",label:"Aufgabe kann weitergef\xFChrt werden",occasion:{de:"Sobald eine Aufgabe, die auf eine optionale Aktion (z. B. Taster Day) oder die Nachbearbeitung durch die Familie gewartet hat, weitergef\xFChrt werden kann \u2014 an die Person, die sie hat (nicht an die, die das Warten beendet hat)",en:"When a task that waited for an optional action (e.g. Taster Day) or for the family's rework can be continued \u2014 to the person who has it (not to whoever ended the wait)"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:uH,channels:["email"],portalVisible:!1,placeholders:[cd,fH,Xp],slots:[$e({de:"Kann weitergef\xFChrt werden: {{taskTitle}}",en:"Can be continued: {{taskTitle}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"\u201E{{actionLabel}}\u201C ist beendet. Diese Aufgabe kann weitergef\xFChrt werden:",en:"\u201C{{actionLabel}}\u201D has ended. This task can be continued:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Direkt zur Aufgabe:
11189
11189
 
11190
11190
  {{taskLink}}`,en:`Go straight to the task:
11191
11191
 
@@ -11434,7 +11434,7 @@ ${i.map(d=>` ${lc(d)}
11434
11434
  `),0}},C0=[zv,Wv,Yv];var Hv=class extends D{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}},D0=[Hv];function ix(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(ix,"ts");function L0(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s(L0,"ago");var F0=["queued","running","succeeded","failed","canceled"];function JQ(e){let n=F0.find(t=>t===e);if(n===void 0)throw new Error(`jobs list: --status must be one of ${F0.join(" | ")}, got "${e}".`);return n}s(JQ,"jobStatus");var Jv=class extends D{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:Uf(this.limit,100),r=await this.paginate(n,x.jobs.listPage,this.status?{status:JQ(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:L0(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},Qv=class extends D{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}},Zv=class extends D{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:ix(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Xv=class extends D{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}},ex=class extends D{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:ix(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},nx=class extends D{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:ix(t.ranAt)}),0)}},tx=class extends D{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}},rx=class extends D{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:L0(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},M0=[Jv,Qv,Zv,Xv,ex,nx,tx,rx];var QQ=/^(\d+)([mhd])$/,ZQ={m:6e4,h:36e5,d:864e5};function wh(e,n=Date.now()){let t=e.trim(),r=QQ.exec(t);if(r!==null)return n-Number(r[1])*ZQ[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(wh,"parseSince");function kh(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(kh,"ts");function gx(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(!Zm(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${Ye.join("|")})`);return e}s(gx,"parseLocale");function XQ(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(XQ,"parseSlots");var ox=class extends D{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:Uf(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:wh(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:kh(o.createdAt),settled:kh(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function e8(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(e8,"showView");var sx=class extends D{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(e8(t)),0}},ax=class extends D{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}},lx=class extends D{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:kh(t.ranAt),lastDeadAt:kh(t.lastDeadAt)}),0)}},dx=class extends D{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}},cx=class extends D{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}},ux=class extends D{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:gx(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}
11435
11435
  Platzhalter: ${i||"\u2014"}
11436
11436
 
11437
- `)}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}},fx=class extends D{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=XQ(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:gx(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}},px=class extends D{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:gx(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}},uc=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function bh(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":uc(n[r],""),...t===null?{}:{platform:uc(t[r],"")}}))}s(bh,"chromeTextRows");var mx=class extends D{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=>[...bh("greeting",r.greeting,r.defaults.greeting),...bh("closing",r.closing,r.defaults.closing),{field:"senderName",school:uc(r.senderName,"\u2014 (platform)"),platform:uc(r.defaults.senderName,"")}],["field","school","platform"]),0}},hx=class extends D{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=>[...bh("greeting",l.greeting,null),...bh("closing",l.closing,null),{field:"senderName",school:uc(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},q0=[ox,sx,ax,lx,dx,cx,ux,fx,px,mx,hx];var n8={capacity:null,isOpen:!1},t8={capacity:null,isOpen:!0};function r8(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(r8,"isCapacity");function vh(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)||!r8(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(vh,"capacitySpecIssues");function j0(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(Yr(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===nr(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 y=i.get(p);if(y===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},w=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,b=w!==void 0?{capacity:w.capacity,isOpen:w.isOpen}:u===void 0?n8:t8;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:b,to:k})}}return d}s(j0,"planRunCapacities");function K0(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(K0,"describeCell");function xh(e){return`~cap ${e.run}\xD7${e.stageKey} ${K0(e.from)} \u2192 ${K0(e.to)}`}s(xh,"describeCapacityStep");function V0(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(V0,"assertBackendHasStageKeys");async function yx(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}));V0(i);let a=tp(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(yx,"planStages");async function Sh(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});V0(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Yr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return j0(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===nr(d,c)))})}s(Sh,"planCapacities");async function i8(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===nr(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(i8,"assertNoArchivedRunKey");var wx={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...np(o??[]),...ep(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(w=>w.message.de).join("; ")}`);let l=vh(t.program?.runs??[],o?.map(w=>w.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await i8(e,i,n,t);let d=await Sh(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=o8(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(w=>w.key===u);if(!p)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(w=>w.key===null?[]:[w.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 w=await yx(e,i,n,o);h.push(...w.map(rp))}else{let w=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(...w.steps,...w.warnings.map(b=>`warning ${b}`))}let y=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let w of t.program?.runs??[]){let b=y.programKey===null?void 0:y.runs.find(E=>E.key===nr(y.programKey,w.key));if(b!==void 0){Bs(b.name,w.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:w.name}),h.push(`~run ${w.key} ("${Ce(b.name)}" \u2192 "${Ce(w.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,key:w.key,name:w.name,isOpen:w.capacities!==void 0?!1:w.isOpen??!0,...w.startDate?{startDate:w.startDate}:{},...w.endDate?{endDate:w.endDate}:{}}),h.push(`+run ${w.key} (${Ce(w.name)})`)}let k=r.dryRun?d:await Sh(e,i,n,t);if(!r.dryRun&&k.length>0){let w=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=w.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let E of k){let T=w.runs.find(P=>P.key===nr(b,E.run))?.runId,R=w.stages.find(P=>Yr(b,P.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(xh)),h.join(", ")}};function o8(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(o8,"bundleUnitKey");var B0={role:"control",effect:"pure",cardinality:"N-to-1"};var Ah=["add","remove","replace"];function U0(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(U0,"roleAssignLiteral");var G0={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=U0(e,"roleKey")?.trim()??"",o=U0(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"}),Ah.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 ${Ah.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Ah.join(" | ")}.`},severity:"error"}),r},"validate")};var s8=["event","effect","outcomes"],kx=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),z0={outcomes:[{id:Er,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of s8)i in r&&t.push(kx(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${Er}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${Er}" itself.`));return or(n.nodes).some(i=>i.target===e.id)&&t.push(kx(`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?.[Er]===void 0&&t.push(kx(`nodes.${e.id}.next.${Er}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${Er}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${Er}" nowhere.`)),t},"validate")};var a8="submit",W0=[{id:a8,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function Y0(e){return e==="draft"}s(Y0,"isWritableSmartFormState");var bx=["draft","committed"],_Pe=bx.filter(e=>Y0(e));async function H0(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(H0,"getSmartFormInstance");var J0="form:fill",vx="request:collectPayment",xx="request:collectPaymentSeparate",$i="confirmPayment";var l8={key:J0,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},Q0={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},Z0={[bO]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:Q0,external:nn(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")},[sp]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:Q0,external:nn(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."))}},X0={role:"user-action",effect:"side-effect",progressDefaults:Z0,progressEvents:Gn(Z0),actions:s(()=>W0,"actions"),workItemTemplates:s(()=>[l8],"workItemTemplates"),states:bx,currentState:s(async(e,n)=>{let t=await H0(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=>It(e)?[]:[{id:ap,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 eM={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Mn.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Mn.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Mn.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:K_(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[Mn.flagKey]?.kind==="literal"&&Rp(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Mn.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?.[Mn.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Mn.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 d8="true",c8="false",Sx=[{id:d8,label:{de:"Ja",en:"Yes"}},{id:c8,label:{de:"Nein",en:"No"}}];var nM={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Sx,validate:s((e,n,t)=>u8(e,n,t),"validate")};function u8(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=Sx.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,...mm(e.condition,DO(n),t).map(r)]}s(u8,"ifNodeIssues");var Ha="decision",f8=new Set(["decision","review"]),nNe=new Set([...f8,"governedDocument"]);var rM=[{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"}],tM={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:nn(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."))}},ps={role:"user-action",effect:"side-effect",outcomes:rM,progressDefaults:tM,progressEvents:Gn(tM),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,...Wi(n.semantic)?{semantic:n.semantic}:{}})),...NC(e)],"actions"),optionalActionKinds:["spawnTasks","skipRule"],workItemTemplates:s(e=>[{key:Ha,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===Ha&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),taskView:s((e,n)=>n===Ha?e.view:void 0,"taskView"),validate:Ax};function Ax(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 ${Rt.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${Rt.join(", ")}.`},severity:"error"}):Wi(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: ${Rt.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${Rt.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(Ax,"validateDecisionNode");var Ex=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],iM=[{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 Tx="promoted";var oM="promote",sM="Nachr\xFCcken",Ja="promoteLabel";var p8={de:sM,en:"Promote from waitlist"};function m8(e){let n=e.inputs?.[Ja];if(n===void 0||n.kind==="unset")return p8;let t=n.kind==="literal"?n.value:void 0;return jo(t)!==null&&F(`waitlist node ${e.id}: inputs.${Ja} ${JSON.stringify(n)} is not a { de, en } literal`),t}s(m8,"promoteLabelOf");var $x={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},aM={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:$x,external:nn(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:$x,external:nn(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:$x,external:nn(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."))}},lM={outcomes:Ex,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:rr.map(e=>({value:e,label:WO[e]}))},{id:Ja,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?.[Ja];if(t?.kind==="literal"){let a=jo(t.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ja}`,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=vw(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=vw(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:aM,progressEvents:Gn(aM),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:Ex).some(t=>t.id===Tx)?[{id:oM,kind:"advance",outcome:Tx,semantic:"other",label:m8(e),surface:sr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var Rx="complete",fc="acceptedIncomplete",Eh="rejected",h8="absage",dM="closeWithoutDocuments",cM="rejectAtCompleteness",uM="Ohne Nachreichung abschlie\xDFen",fM="Ablehnen",pM="awaitingDocuments",Ix="documentsComplete",Ox="closedWithoutDocuments",_x="rejected",Px="withdrawn",mM="requested",ANe={[Rx]:{event:Ix,status:"complete",endsRole:!0},[fc]:{event:Ox,status:"acceptedIncomplete",endsRole:!1},[Eh]:{event:_x,status:"rejected",endsRole:!0},[h8]:{event:Px,status:"withdrawn",endsRole:!0}};var pc=s(()=>Ql[0],"beneficiary"),Nx=366;function g8(e){let n=e.reads,t=Zl(e).flatMap(({address:r})=>un(r)&&!Ql.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(un):[],...t]}s(g8,"printedFields");function y8(e,n){let t=de(n);return e.nodes.filter(r=>r.type==="governedDocument"&&g8(r).some(i=>de(i)===t))}s(y8,"documentsPrinting");function w8(e,n){if(!un(n)||n.path!==pc())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!It(t)}s(w8,"isCreatedFormBeneficiary");function zn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(zn,"issue");function k8(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Rx,fc].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)&&$r(d.form)&&d.form.owner===t)){if(d.type==="end"){if(Uo(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(k8,"reachesApprovedEndUnreviewed");var Cx={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},hM={[pM]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:Cx,external:nn(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."))},[Ix]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:Cx,external:nn(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."))},[Ox]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:Cx,external:nn(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."))},[_x]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:zP,external:nn(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."))},[Px]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:Wp,external:nn(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."))}},gM={outcomes:iM,progressDefaults:hM,progressEvents:Gn(hM),notificationEvents:s(()=>[{id:mM,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(fc)&&t.push({id:dM,kind:"advance",outcome:fc,semantic:"other",label:{de:uM,en:"Close without documents"},surface:sr,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(Eh)&&t.push({id:cM,kind:"advance",outcome:Eh,semantic:"rejected",label:{de:fM,en:"Reject application"},surface:sr,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(zn(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(zn(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(zn(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 P=Zr(t,T);if(P==null)continue;let L=ca("requires",da(P));L==="computed"||L==="repeated"?r.push(zn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${P.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${P.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(zn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${Zi(P,"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)} ("${Zi(P,"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(zn(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>Nx)&&r.push(zn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(E)}" ist keine ganze Zahl von 0 bis ${Nx} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(E)}" is not a whole number from 0 to ${Nx} days.`}))}else typeof u.until!="string"||hk(u.until)===null?r.push(zn(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<pN(Date.now())&&r.push({...zn(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 y8(n,T))r.push(zn(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(P=>{let L=Zr(t,P);return L!=null&&hm(L)}),R=[...new Set(E.map(P=>P.owner))].filter(P=>k8(n,e,P));if(R.length>0){let P=E.filter(L=>R.includes(L.owner));r.push({...zn(e,"next",{de:`[review/unreviewedAfterSupply] ${P.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] ${P.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 y=e.inputs?.guestRole,k=y?.kind==="literal"?y.value:void 0,w=e.inputs?.person,b=w?.kind==="binding"?w.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(zn(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(zn(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(zn(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(zn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Un}.${pc()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${Un}.${pc()}).`}))),we(b)&&!w8(n,b)&&r.push(zn(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>.${Un}.${pc()}).`,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>.${Un}.${pc()}).`})),b!==null&&k===void 0&&r.push(zn(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(zn(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 b8=[{id:HO,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Th=s(e=>e,"asDecision"),yM={[JO]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:nn(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."))}},wM={role:"user-action",effect:"side-effect",outcomes:b8,progressDefaults:yM,progressEvents:Gn(yM),notificationEvents:s(e=>ps.notificationEvents(Th(e)),"notificationEvents"),inputs:s(()=>[{id:lr,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:rs.map(e=>({value:e,label:KD[e]}))}],"inputs"),actions:s(e=>[...ps.actions(Th(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Aw,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:ps.optionalActionKinds,workItemTemplates:s(e=>ps.workItemTemplates(Th(e)).map(n=>n.key===Ha?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Aw]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Ax(Th(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!bp.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?.[lr],a=jD(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${lr}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${rs.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${rs.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)&&$r(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(hm)&&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 kM=["awaitingAnswer","answered"];async function bM(e,n){return(await ka(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(bM,"externalRequestState");var SM=[{id:Vo,label:{de:"Bezahlt",en:"Paid"}}],lCe=new Set(SM.map(e=>e.id));var v8=Vo,vM=[{id:v8,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],x8={id:Qw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:sr,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"}}},S8={id:Jw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:sr,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"}}},A8={id:Jw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:sr,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 Dx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Dx,"literalOf");function ao(e){let n=Dx(e,ct);return _p(n)?n:null}s(ao,"modeOrNull");function E8(e){let n=Dx(e,Ji);return typeof n=="string"&&n.length>0?n:null}s(E8,"articleKeyOrNull");function T8(e){let n=Dx(e,ir);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(T8,"payeeKeyOrNull");var $8={id:Ji,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},R8={id:ct,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)"}}]},I8={id:Qi,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},O8={id:ir,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function _8(e){return[$8,R8,...ao(e)==="online"?[O8]:[],I8]}s(_8,"collectPaymentInputs");var P8=["amount","currency","settlement"],N8={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},C8={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function D8(e,n){if(ao(e)!=="online")return[];let t=T8(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${ir}`,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(D8,"payeeIssues");var xM={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:nn(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."))}},AM={outputs:s(()=>[{name:O_,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>_8(e),"inputs"),outcomes:SM,progressDefaults:xM,progressEvents:Gn(xM),notificationEvents:s(e=>ao(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=ao(e);return n==="online"?[...vM,A8]:n==="manual"?[x8,S8]:[]},"actions"),states:kM,currentState:s((e,n)=>bM(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:ao(n.node)==="manual"?xx:vx}),"currentState"),workItemTemplates:s(e=>{let n=e,t=ao(n);return t==="manual"?[{key:$i,recipient:"internal",title:N8,unlocks:[Qw],advancesNode:!0},{key:xx,recipient:"external",title:C8,unlocks:[],informational:!0,advancesNode:!1}]:t!=="online"?[]:[{key:vx,recipient:"external",title:n.label,unlocks:vM.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 P8)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(...D8(e,t)),ao(e)==="manual"&&e.assign?.[$i]===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."}),ao(e)===null&&i(`inputs.${ct}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${oa.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[ct])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${oa.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[ct])}.`});let o=e.inputs?.[Qi];if(o?.kind==="literal"){let d=jo(o.value);d!==null&&i(`inputs.${Qi}`,{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=E8(e);if(a===null)return i(`inputs.${Ji}`,{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.${Ji}`;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 ${Zw.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Zw.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 EM(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(EM,"localeFieldMissingText");var Fx=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),TM=/^[a-z][a-z0-9_]*$/;function $M(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"||!TM.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(!Hi(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 (${ia.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 (${ia.join(", ")}).`}});continue}if(Fx.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 ${[...Fx].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a document from a template only prints ${[...Fx].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!TM.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&&!Em.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Em.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Em.join(", ")}.`}})}return t.push(...F8(e,n)),t}s($M,"templateParameterIssues");function F8(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:EM(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(F8,"localeFieldIssues");function RM(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(RM,"applyTemplateStamp");var Lx=50;async function $h(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(Lx+1);return t.length>Lx&&F(`signing_returns: Vorgang ${n} has more than ${Lx} returns`),t}s($h,"returnsOf");var Mx=50;async function qx(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(Mx+1);return t.length>Mx&&F(`signing_returns: return ${n} has more than ${Mx} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(qx,"returnDocumentsOf");async function IM(e,n){let t=await qx(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(IM,"soleReturnDocumentOf");var Rh=200,RCe=Rh*20;async function L8(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(L8,"processRedacted");async function Kx(e,n){await L8(e,n)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Kx,"assertProcessReadable");function M8(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(M8,"rowOf");async function OM(e,n,t){await Kx(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(Rh+1);return r.length>Rh&&F(`[process] application ${n} has more than ${Rh} results of ${t.scope}.${t.owner}.${t.key}`),r.map(M8)}s(OM,"storeHistory");async function q8(e,n,t){if(t.key===Un){await Kx(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 OM(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(q8,"nodeResultAt");async function Ih(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return K8(await q8(e,n.applicationId,t),t,n.applicationId)}s(Ih,"readOwnResult");function K8(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(K8,"refOf");var jx={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},j8=Object.keys(jx),V8=j8.filter(e=>jx[e]==="open"),LCe=V8.filter(e=>e!=="pending");function _M(e){return jx[e]==="terminal"}s(_M,"isTerminalSigningStatus");var lo=["docusign","insign"];var mc={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var U8=_M;function NM(e){return!U8(e.status)&&e.voidRequestedAt===void 0}s(NM,"holdsContract");async function CM(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(CM,"traegerLegalEntityOfParty");async function G8(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(G8,"isOrganizationParty");async function DM(e,n){return await CM(e,n)!==null?"traeger":await G8(e,n)?"organization":"person"}s(DM,"signerKindOf");async function FM(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await z8(e,t.partyId)==="family")return"family";return"traeger"}s(FM,"signingSideOf");async function z8(e,n){return await DM(e,n)==="traeger"?"traeger":"family"}s(z8,"sideOfParty");var vDe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),MM=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var Vx=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Oh=m.object({period:Vx,anchorDate:m.string()});var TDe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),$De=m.union(m.literal("line"),m.literal("aggregate")),_h=m.record(m.string(),m.string());var W8=m.union(m.literal("active"),m.literal("ended")),Bx=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()})),Y8=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),H8={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:Bx,pricingSelections:m.optional(_h),paymentSchedule:m.optional(Oh),resolvedSnapshot:m.any(),feeGroup:m.optional(MM),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},J8={...H8,period:Y8,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:W8,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},DDe=qt(J8).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Or=m.union(m.string(),m.null()),qM=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),Q8=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()}))}),KM=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(qM)})),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:Or}),jM=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(Vx),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Or,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),Z8={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Or,pricing:Bx,paymentSchedule:m.optional(Oh),pricingSelections:m.optional(_h),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:Or,endDate:Or,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Or,programName:Or,runName:Or,groupName:Or}),m.null()),grants:m.array(jM),payerAllocations:m.array(KM)},X8=m.object({...Z8,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Or,sourceValidTo:Or})}),eZ=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(qM),declaredSigners:m.array(Q8),payerAllocations:m.array(KM),aggregateGrants:m.optional(m.array(jM)),lines:m.array(X8)}),nZ=eZ;var tZ=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),rZ=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:so})),caption:m.string(),page:m.number(),box:tZ}))});var iZ=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(rZ)}))}),oZ=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()}),sZ={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:iZ,coverLetter:m.optional(oZ),snapshot:Ve.historyOf(nZ),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()}))},UDe=qt(sZ).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 iFe=16*1024;var oFe=15*6e4;var sFe=10*6e4;var Ux={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()}))},SFe=qt({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...Ux}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var RFe=m.object(Ux);var Gx=200;async function aZ(e,n,t,r){n.length>Gx&&F(`${r} is carried by more than ${Gx} 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(aZ,"requestsOfMembers");async function VM(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(Gx+1);return await aZ(e,r,t,`revision ${n}`)}s(VM,"requestsOfSnapshot");var BM=100;async function lZ(e,n){let t=await VM(e,n);t.length>BM&&F(`requestsBySideOf: revision ${n} has more than ${BM} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await FM(e,i.signers)].push(i);return r}s(lZ,"requestsBySideOf");async function zx(e,n){return(await lZ(e,n)).family}s(zx,"familyRequestsOf");var Wx=100;async function dZ(e,n){let t=await e;return t.length>Wx&&F(`contractChain: more than ${Wx} ${n}`),t}s(dZ,"bounded");async function cZ(e,n,t){let r=await Ih(e,{applicationId:n,nodeId:t,key:Tp});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Tp} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(cZ,"nodeContractRef");async function UM(e,n){return await dZ(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",t=>t.eq("contractId",n)).take(Wx+1),`revisions on contract ${n}`)}s(UM,"snapshotsAsc");async function Yx(e,n){let t=(await zx(e,n)).filter(NM);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(Yx,"openFamilyRequest");async function uZ(e,n){for(let t of await UM(e,n))if((await zx(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(uZ,"familyRoute");async function GM(e,n){for(let t of n)if(await uZ(e,t)==="paper")return"paper";return"provider"}s(GM,"familyRouteOf");async function fZ(e,n){let t=await IM(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(fZ,"toReturn");function Ph(e){async function n(a,l){return await cZ(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 UM(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 Yx(a,c._id);if(u===null)return null;let p=(await $h(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 fZ(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(Ph,"contractNodeReads");function Nh(e){return e.addedParts??[]}s(Nh,"addedPartsOf");var Hx=50;async function pZ(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(pZ,"groupRunsOf");async function zM(e,n){let t=await pZ(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(zM,"groupRunsInOrder");function WM(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(WM,"isCompleteGroup");var Jx=200;function mZ(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(mZ,"groupPartKeys");async function hZ(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(Jx+1);return r.length>Jx&&F(`groupChain: more than ${Jx} generation runs on node ${t}`),r}s(hZ,"nodeRuns");async function gZ(e,n,t){let r=mZ(t),i=new Set;for(let a of await hZ(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 zM(e,a);if(!WM(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(gZ,"groupRevisionRows");async function Qx(e,n,t){let r=await Ih(e,{applicationId:n,nodeId:t,key:$p});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${$p} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Qx,"nodeGroupContracts");async function yZ(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await Yx(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(yZ,"openGroupRequest");async function wZ(e,n){let t=[];for(let i of await qx(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(wZ,"toGroupReturn");function YM(e){async function n(i,o,a,l){let d=(await gZ(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 yZ(i,l);if(d===null)return null;let c=(await $h(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 wZ(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await Qx(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(YM,"groupNodeReads");async function kZ(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 Kb(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(kZ,"toRevision");async function bZ(e,n){let t=await kZ(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(bZ,"toReturn");function HM(e){let n=Im(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 bZ(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(HM,"artifactNodeReads");function Ch(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(Ch,"documentChainKind");function JM(e){switch(Ch(e)){case"contract":return Ph(e).reads;case"group":return YM(e).reads;case"artifact":return HM(e).reads}}s(JM,"documentReadsFor");var vZ={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function hc(e){let n=e.responseStrategy;return typeof n=="string"&&n in Si?Si[n].producesResponseArtifact:!1}s(hc,"returnsSignedCopy");function xZ(e){return hc(e)&&e.confirmContractTerms!==!1}s(xZ,"asksContractTerms");function QM(e){return xZ(e)?{title:e.contractTermsQuestionText??vZ,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(QM,"contractTermsConfirm");function ZM(e){let n=SZ(e);return n.length>0&&n.every(t=>t.status==="blocked")}s(ZM,"producerWindowHeld");function SZ(e){return e.filter(n=>n.isOpen&&n.kind==="admission"&&n.templateKey!==void 0&&vd.has(n.templateKey))}s(SZ,"openProducerRows");async function AZ(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:$k(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==ti||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${ti} row`),a}s(AZ,"rejectedReturnOfAsk");async function XM(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await AZ(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(XM,"returnedCopyOfAsk");var Zx=new Set([...vd,Rr,Qo,io,ti,bt]),iq={id:Qn,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},oq={id:No,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function EZ(e){let n=[],t=[{slot:iq,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:oq,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=Xl(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(EZ,"referenceInputIssues");var TZ={id:xi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},$Z={id:Pa,type:"boolean",label:{de:"Coverletter best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},RZ={id:Vt,type:"legalEntity",label:aD,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function IZ(e,n){let t=`inputs.${Vt}`,r=e.inputs?.[Vt];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=_a(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 (${wm.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 (${wm.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(IZ,"traegerIssues");function Dh(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}}:(Ui(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(Dh,"generatorFields");function OZ(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(OZ,"deferredToCockpit");function _Z(e){return Hi(e.type)?e.type:void 0}s(_Z,"resolverSlotType");function PZ(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=Da(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(PZ,"issueConfirmation");function Se(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Se,"issue");function Fh(e){return Am.includes(e.production)&&ts.includes(e.approval)&&Tm.includes(e.responseStrategy)}s(Fh,"hasValidModes");async function Xx(e,n){let t=await ka(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(ZM(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&vd.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===io))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Rr);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===bt))return"signatureStalled";let o=r.find(a=>a.templateKey===Qo);if(o!==void 0){if(Ai(n.node).issuesBy==="provider"){let l=Ch(n.node)==="group"?(await Qx(e,n.applicationId,n.node.id)).map(d=>d.contractId):[await Ph(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 GM(e,l)==="provider")return"awaitingSignature"}return Ai(n.node).producesResponseArtifact?await XM(e,{chain:JM(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===ti)?"responseInCheck":"done"}s(Xx,"governedDocCurrentState");function eq(e){return e.production!=="none"&&Ch(e)!=="artifact"}s(eq,"keepsDocumentInContractDomain");function NZ(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!tr(r.key))return[];let i=Po(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(NZ,"envCoverageIssues");function sq(e,n){let t=[];for(let r of Dh(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...NZ(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"}:OZ(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(sq,"fieldSourceIssues");function CZ(e){let n=Ar(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=$M(e.templateStamp,n).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...sq(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(CZ,"templateIssues");function DZ(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(DZ,"eSignatureAnchorIssues");function FZ(e,n){return n===void 0||n.sendable?[]:Ai(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(FZ,"eSignatureProviderIssues");var nq={key:"dokument",label:te("Dokument","Document"),scope:"node"},tq={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:nq,external:nn(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:nq,external:nn(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 rq(e,n){return!Fh(e)||e.production==="none"?null:n===io||Rm(e).some(r=>r.key===n)?Im(e):null}s(rq,"governedDocRowSlot");var aq={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Jo,"processHoldTemplate"),progressDefaults:tq,progressEvents:Gn(tq),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(!Fh(e))return[];let n=Ai(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...ns(e)?["awaitingCoverLetter"]:[],...i,...n.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(t.push({id:Qk(e),kind:"internal",surface:Na,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Rr}:{},...PZ(e)??{}}),t.push({id:uD,kind:"internal",surface:Na,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:fD,kind:"internal",surface:Na,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:vm,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:ns(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),ns(e)&&(t.push({id:km,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),t.push({id:bm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),n.producesResponseArtifact&&t.push({id:xm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Sm,kind:"internal",surface:Na,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Zo,kind:"internal",surface:Na,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:pD,currentState:Xx,workItemTemplates:s(e=>{let n=e;return Fh(n)?Rm(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e,r=rq(t,n);return r===null?[]:Rm(t).find(o=>o.key===n)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,n)=>{let t=rq(e,n);if(t!==null)return n===io?{kind:"artifact",slot:t,part:"coverLetter"}:{kind:"artifact",slot:t}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[iq,RZ]:[],...e.production==="template"?[oq]:[],TZ,...e.generatorStamp?.coverLetter===!0?[$Z]:[],...Dh(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=_Z(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"&&Yi(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:qw,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Qo||n===io||n===bd||n===ti||n===bt){let t=n===Qo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===ti?{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===bt?{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: ${Jo}${e.approval==="release"?`, ${Rr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${Jo}${e.approval==="release"?`, ${Rr}`:""}.`}}return n===Rr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Rr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Rr}" 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(eq(n.node))return!1;let t=await Xx(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&Ai(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=QM(n.node);if(t===null||eq(n.node))return null;let r=await Xx(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!Fh(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Am.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${ts.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Tm.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 {${Am.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${ts.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Tm.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=Si[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 y=e.assign??{};if(e.production!=="none"&&y.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"&&(y.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)y.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",y.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"?y.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.`})):y.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(...DZ(e,t),...FZ(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.`})),hc(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",y.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??[])Zx.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 (${[...Zx].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${E.key}" on node "${e.id}" collides with an intrinsic template (${[...Zx].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...IZ(e,t)):e.inputs?.[Vt]!==void 0&&r.push(Se(e,`inputs.${Vt}`,{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(...EZ(e)),e.production==="resolver"){let E=pi(e);if(E!==null){let T=VO(E);for(let R of Dh(e)){if(!Hi(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 (${ia.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 (${ia.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(...sq(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(...CZ(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?.[Pa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${Pa}`,{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.`})),ns(e)&&(t!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${Pa}`,{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.`})),Ai(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 w=e.inputs?.[xi],b=w===void 0||w.kind==="unset"?void 0:w.kind==="literal"?w.value:w;return b!==void 0&&!Sd(b)&&r.push(Se(e,`inputs.${xi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(b)} \u2014 erlaubt ist eine ganze Zahl von ${Xo} bis ${es} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(b)} \u2014 a whole number from ${Xo} to ${es} days is allowed.`})),b===void 0&&Dh(e).some(E=>E.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${xi}`,{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 lq={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 Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Yt,"isRecord");var eS=["field","join","literal","address","payment","contract"],LZ=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),MZ=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ur(e){return typeof e=="string"&&e.trim().length>0}s(ur,"nonEmptyString");function Lh(e,n,t,r,i="value"){if(!Yt(e)||!Yt(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=eS.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${eS.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${eS.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ur(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(ur))&&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)||ur(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"&&tr(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&&!LZ.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&&!(ur(e.lookup)&&Yt(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"||Yt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Yt(d)&&MZ.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(Lh,"checkMapping");function co(e,n,t,r,i){if(!Yt(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=lq[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))Lh(l,`${n}.${a}`,r,i)}s(co,"checkBody");function dq(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(!Yt(o)||!ur(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),Lh(o.value,`${l}.value`,t,r),o.unless!==void 0&&Lh(o.unless,`${l}.unless`,t,r,"condition")})}s(dq,"checkAif");function nS(e){let n=[];if(!Yt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Yt(e.lookups)?e.lookups:{};Yt(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))(!Yt(i)||!Object.values(i).every(ur))&&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(ur(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),co(e.pupil,"engage.pupil","addPupil",t,n),co(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&co(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&co(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&co(e.medical,"engage.medical","addMedical",t,n),dq(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(!Yt(i)||!ur(i.key)||!ur(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),co(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&co(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)=>co(u,`${a}.${l}[${p}]`,d,t,n))}}dq(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&Lh(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Yt(r)||!ur(r.repeated)||!ur(r.field)||!ur(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(nS,"engagePushConfigIssues");function*tS(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(tS,"mappingsOf");function cq(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of tS(e))for(let i of qZ(t.from))n.add(KZ(i,r));return[...n]}s(cq,"configFieldKeys");function qZ(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(qZ,"formFieldsOf");function KZ(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s(KZ,"resolveFieldKey");function uq(e,n){for(let{mapping:t}of tS(e))if(n in t.from)return!0;return!1}s(uq,"configReadsSource");function fq(e){let n=new Set;for(let{mapping:t}of tS(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(fq,"configEnvLeaves");var pq="done",mq=["sandbox","production"];var Mh="engagePush",E0e=660*1e3;function uo(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(uo,"issue");function rS(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(rS,"literal");function hq(e){return nS(e.engage).length===0?e.engage:null}s(hq,"validConfig");function jZ(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(jZ,"bypassingPath");var gq={role:"system-action",effect:"side-effect",outcomes:[{id:pq,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=hq(e);return n===null?[]:fq(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=rS(e,"target");mq.includes(a)||o.push(uo(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=rS(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(uo(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?.[Mh]===void 0&&o.push(uo(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Mh}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Mh}\` names the team.`}));for(let k of nS(e.engage))o.push(uo(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"&&rS(k,"target")===a);d.length>0&&o.push(uo(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.`})),jZ(n,e.id)&&o.push(uo(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=hq(e),u=e;for(let[k,w,b,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!uq(c,k)||u[w]!==void 0||o.push(uo(e,w,{de:aa("address/missing",{where:`\u201E${r}\u201C \u203A ${b}`},"de"),en:aa("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let p=u.form,h=we(p)&&p.scope==="node"?p.owner:void 0,y=h===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&y!==void 0){let k=new Set(y.keys()),w=cq(c).filter(b=>!k.has(b)&&!/\[\d+\]\./.test(b));if(w.length>0){let b=n.nodes.find(E=>E.id===h);o.push(uo(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${b?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${w.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${b?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${w.join(", ")}.`},"warning"))}}return o},"validate")};var ms={join:B0,end:YP,roleAssign:G0,eventTrigger:z0,waitlist:lM,completenessCheck:gM,form:X0,setFlag:eM,if:nM,decision:ps,review:wM,collectPayment:AM,governedDocument:aq,countersign:$D,engagePush:gq};E_(ms);function yq(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(yq,"graphOf");function wq(e){let n=new Map;for(let t of e.nodes)for(let r of Jr(e,t))n.set(de(r.address),r.nodeId);return n}s(wq,"producedOf");function kq(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(qo(e,t).map(r=>de(r.address))));return n}s(kq,"readsOf");function bq(e,n){let t=yq(e,"bundle"),r=yq(n.graph,"live head"),i=wq(t),o=wq(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=kq(t),d=kq(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,y=[...p].filter(w=>!h.has(w)),k=[...h].filter(w=>!p.has(w));(y.length>0||k.length>0)&&c.push({nodeId:u,added:y,removed:k})}return{headRevision:n.revision,pinnedApplications:n.pinnedApplications,produced:a,reads:c}}s(bq,"planAddresses");function vq(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(vq,"addressPlanRows");function xq(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(xq,"changed");async function Sq(e,n,t){if(n.index.module!==wx.name)throw new Error(`offer: unknown module "${n.index.module}"`);return sF(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return wx.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(Sq,"applyOffer");async function Aq(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(Aq,"exportOffer");async function iS(e,n){let{index:t}=n,i=(await e.query(x.workflow.listManifests,{client:t.tenant})).find(y=>y.offerKey===t.slugs.manifest),o="create";i&&(o="same");let a={};for(let[y,k]of Object.entries(n.smartforms??{})){let w=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=w?.def?xq(k,{label:w.def.label,...w.def.definition})?"change":"same":"create"}let l="absent",d=null;if(n.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let y=await e.query(x.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),k=y?.publishedVersion??y?.draftVersion;l=xq(k&&{graph:Hs(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:Hs(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let y=await e.query(x.workflow.getOfferHeadPins,{client:t.tenant,offerKey:t.slugs.manifest});y!==null&&(d=bq(n.workflow.graph,y))}}let c=t.program?.stages,u=c===void 0?[]:i?await yx(e,t.tenant,t.slugs.manifest,c):tp(null,[],c),p=await Sh(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(iS,"diffOffer");function qh(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(qh,"contractProductionModeOf");function Eq(e){return qh(e)==="resolver"}s(Eq,"isResolverCarrierNode");function Kh(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=pi(t);return!Eq(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(Kh,"authoredPins");var Tq={type:"address",dataType:"composite"};var $q={type:"boolean",dataType:"boolean"};var Rq={type:"consent",dataType:"boolean"};var Iq={type:"date",dataType:"date"};var Oq={type:"docRef",dataType:"file"};var _q={type:"email",dataType:"text"};var Pq={type:"string",dataType:"text"};var Nq={type:"tel",dataType:"text"};var jh={address:Tq.dataType,boolean:$q.dataType,consent:Rq.dataType,date:Iq.dataType,docRef:Oq.dataType,email:_q.dataType,enum:PP.dataType,string:Pq.dataType,tel:Nq.dataType};function oS(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(oS,"shapeOf");function Cq(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,oS(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,oS(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}`,oS(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(Cq,"fieldMapScopes");function VZ(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(VZ,"computedKeysOf");function Dq(e){let n=[],t=VZ(e);for(let r of Cq(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(Dq,"validateFieldMapSources");function Fq(e){let n=[],t=new Set;for(let o of Cq(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(Fq,"validateFieldPersistence");var BZ="$";function UZ(e){return typeof e=="string"&&e.startsWith(BZ)}s(UZ,"isRef");function Vh(e){return e.slice(1)}s(Vh,"stripRef");function*GZ(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(GZ,"refSlots");function zZ(e){let n=new Set;for(let t of GZ(e))UZ(t)&&n.add(Vh(t));return[...n]}s(zZ,"collectRefs");function WZ(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 zZ(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=Vh(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Vh(l.target)===a||l.kind==="shareValue"&&Vh(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(WZ,"buildAdjacency");function Lq(e){let{refsOf:n}=WZ(e),r=um(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(Lq,"detectCycle");function Mq(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(Mq,"escapeRegExp");function fo(e){return new RegExp(`^${Mq(e)}\\[(\\d+)\\]\\.(.+)$`)}s(fo,"repeatedRowKeyPattern");function sS(e,n){let t=fo(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(sS,"countRepeatedRows");function qq(e,n,t){let r=fo(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(qq,"repeatedRowHasData");function Kq(e){return e.endsWith(".count")?e.slice(0,-6):e}s(Kq,"readKeyOf");function aS(e){return{sections:e,fields:[]}}s(aS,"hiddenSectionsOnly");function jq(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??[])jq(r,n,t)}s(jq,"collectKeys");function Vq(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;jq(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(fo)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(Vq,"restrictedSectionsOf");function Bq(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(Bq,"matchesKey");function YZ(e,n){return n.find(t=>Bq(e,t))??null}s(YZ,"hiddenSectionOfKey");function HZ(e,n){for(let t=e;;){if(Bq(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(HZ,"fieldOwnsKey");function JZ(e,n){return n.find(t=>HZ(e,t))??null}s(JZ,"restrictedFieldOfKey");function QZ(e,n){let t=YZ(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=JZ(e,n.fields);return r===null?null:{kind:"field",field:r}}s(QZ,"hiddenOwnerOfKey");function Bh(e,n){return QZ(e,n)!==null}s(Bh,"isKeyHidden");function ZZ(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(ZZ,"visibleToListIssues");function Uq(e,n,t){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...ZZ(c.id,h,`${u}.visibleTo`,p,t));let y=p||h!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(w=>w.fields),...(c.repeated??[]).flatMap(w=>w.itemTemplate)];for(let w of k)w.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${w.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${w.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,w)=>i(k,`${u}.subsections[${w}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=Vq(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=aS(p);for(let y of Ln(c)){let k=Kq(y);(Bh(y,h)||Bh(k,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${y}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${y}' 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&&Bh(c.sameAs.source,aS(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,y=o.filter(k=>k.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,w)=>l(k,`${u}.fields[${w}]`,y)),c.groups?.forEach((k,w)=>{a(k.visibleIf,`${u}.groups[${w}].visibleIf`,y),k.fields.forEach((b,E)=>l(b,`${u}.groups[${w}].fields[${E}]`,y))}),c.repeated?.forEach((k,w)=>{a(k.itemVisibleIf,`${u}.repeated[${w}].itemVisibleIf`,y),k.itemTemplate.forEach((b,E)=>l(b,`${u}.repeated[${w}].itemTemplate[${E}]`,y))}),c.computed?.forEach((k,w)=>a(k.expression,`${u}.computed[${w}]`,y)),c.subsections?.forEach((k,w)=>d(k,`${u}.subsections[${w}]`,h))},"visitCompiled");return n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(Uq,"sectionVisibilityIssues");var oi="#";var Gq=s(e=>{let n=Mb.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),_r={firstName:Gq("persons.firstName"),lastName:Gq("persons.lastName")};function zq(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(zq,"personNameKeys");function Wq(e){return[...e.firstName,...e.lastName]}s(Wq,"personNameKeyList");function Yq(e){return e.firstName.length>0||e.lastName.length>0}s(Yq,"hasPersonName");function Qa(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 Qa(i.subsections??[],a,i.id))r.push(l)}),r}s(Qa,"walkSections");function XZ(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(XZ,"findFieldInSection");function Hq(e,n){for(let t of Qa(e.sections)){let r=XZ(t.section,n);if(r)return{section:t.section,field:r}}return null}s(Hq,"findField");var e9=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],n9=["blue","rose","amber","violet","teal","emerald","slate"];function Jq(e){return e9.includes(e)}s(Jq,"isBucketIconName");function Qq(e){return n9.includes(e)}s(Qq,"isBucketColorName");var t9="__clear__";function Zq(e){return e===""?"empty":e===t9?"reserved":null}s(Zq,"selectOptionValueDefect");var lS=lL.docRef.allowedMime;function iK(e,n={}){let t=Ta(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 C=`sections[${O.join(".")}]`;I.fields.forEach((z,le)=>{Za(a,z.key,`${C}.fields[${le}]`,"duplicate.field-key",r),l.add(z.key),u.set(z.key,z),c.set(z.key,cS(z)),z.externalFlag&&(z.type!=="boolean"&&r.push({severity:"error",path:`${C}.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:`${C}.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:`${C}.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:`${C}.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(...eK(z,`${C}.fields[${le}]`)),r.push(...Xq(z,`${C}.fields[${le}]`))}),I.groups?.forEach((z,le)=>{z.fields.forEach((ce,De)=>{Za(a,ce.key,`${C}.groups[${le}].fields[${De}]`,"duplicate.field-key",r),l.add(ce.key),u.set(ce.key,ce),c.set(ce.key,cS(ce)),ce.externalFlag&&r.push({severity:"error",path:`${C}.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(...eK(ce,`${C}.groups[${le}].fields[${De}]`)),r.push(...Xq(ce,`${C}.groups[${le}].fields[${De}]`))})}),I.repeated?.forEach((z,le)=>{z.itemTemplate.forEach((ce,De)=>{Za(a,ce.key,`${C}.repeated[${le}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(ce.key,cS(ce)),ce.externalFlag&&r.push({severity:"error",path:`${C}.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:`${C}.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:`${C}.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:`${C}.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:`${C}.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:`${C}.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),Za(a,z.key,`${C}.computed[${z.key}]`,"duplicate.field-key",r),z.exportType==="consent"&&r.push({severity:"error",path:`${C}.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:`${C}.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)=>{Za(h,I.id,`effects[${O}]`,"duplicate.effect-id",r)});let y=new Set;t.outcomes.forEach((I,O)=>{Za(y,I.id,`outcomes[${O}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((I,O)=>{I.output.effectRefs?.forEach((j,C)=>{h.has(j.effect)||r.push({severity:"error",path:`outcomes[${O}].output.effectRefs[${C}]`,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,C)=>{Hq(t,j.path)||r.push({severity:"error",path:`outcomes[${O}].output.fields[${C}]`,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 Qa(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 w={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:n.stageKeys};r.push(...vC(e)),r.push(...Uq(e,t,n.visibleToKeys)),r.push(...iD(e)),r.push(...wC(e,n.stageKeys));for(let I of Qa(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.visibleIf&&(Pr(O.visibleIf,`${j}.visibleIf`,w,!1,r),Xa(O.visibleIf,`${j}.visibleIf`,c,r)),O.fields.forEach((C,z)=>dS(C,`${j}.fields[${z}]`,w,!1,c,r)),O.groups?.forEach((C,z)=>{C.visibleIf&&(Pr(C.visibleIf,`${j}.groups[${z}].visibleIf`,w,!1,r),Xa(C.visibleIf,`${j}.groups[${z}].visibleIf`,c,r)),C.fields.forEach((le,ce)=>dS(le,`${j}.groups[${z}].fields[${ce}]`,w,!1,c,r))}),O.repeated?.forEach((C,z)=>{C.itemVisibleIf&&(Pr(C.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,w,!0,r),Xa(C.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,c,r)),C.itemTemplate.forEach((le,ce)=>dS(le,`${j}.repeated[${z}].itemTemplate[${ce}]`,w,!0,c,r)),C.effects?.forEach((le,ce)=>{le.when&&Pr(le.when,`${j}.repeated[${z}].effects[${ce}].when`,w,!0,r)})}),O.computed?.forEach((C,z)=>Pr(C.expression,`${j}.computed[${z}].expression`,w,!1,r))}t.effects.forEach((I,O)=>{I.when&&Pr(I.when,`effects[${O}].when`,w,!1,r)}),t.outcomes.forEach((I,O)=>{Pr(I.when,`outcomes[${O}].when`,w,!1,r)});let b=new Set(t.outcomes.map(I=>I.id));function E(I,O){I.requiredFor&&I.requiredFor.forEach((j,C)=>{b.has(j)||r.push({severity:"error",path:`${O}.requiredFor[${C}]`,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 Qa(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.fields.forEach((C,z)=>E(C,`${j}.fields[${z}]`)),O.groups?.forEach((C,z)=>{C.fields.forEach((le,ce)=>E(le,`${j}.groups[${z}].fields[${ce}]`))}),O.repeated?.forEach((C,z)=>{C.itemTemplate.forEach((le,ce)=>E(le,`${j}.repeated[${z}].itemTemplate[${ce}]`))})}function T(I,O){let j=s((C,z)=>{let le=(C.type==="docRef"?C.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!lS.includes(Ee));le.length>0&&r.push({severity:"error",path:z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${C.key}' erlaubt ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${lS.join(", ")}).`,en:`Field '${C.key}' allows ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${lS.join(", ")}).`}});let ce=C.type==="docRef"?C.docRefConstraints?.minFiles:void 0;if(ce!==void 0){let Ee=C.docRefConstraints?.multiple===!0,hn=typeof ce=="number"&&Number.isInteger(ce)&&ce>=2;(!Ee||!hn)&&r.push({severity:"error",path:z,code:"config.docref-min-files",message:Ee?{de:`Feld '${C.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(ce)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${C.key}' sets docRefConstraints.minFiles to ${JSON.stringify(ce)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${C.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${C.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}C.multiple===!0&&C.type!=="enum"&&r.push({severity:"error",path:z,code:"config.multiple-non-enum",message:{de:`Feld '${C.key}' setzt multiple: true, hat aber den Typ '${C.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(C.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${C.key}' sets multiple: true but is type '${C.type}' \u2014 only 'enum' supports multi-select.`+(C.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),C.presentation==="yesNo"&&C.type!=="boolean"&&r.push({severity:"error",path:z,code:"config.yesno-non-boolean",message:{de:`Feld '${C.key}' setzt presentation: 'yesNo', hat aber den Typ '${C.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${C.key}' sets presentation: 'yesNo' but is type '${C.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),C.presentation==="yesNo"&&C.defaultValue!=null&&r.push({severity:"error",path:z,code:"config.yesno-default",message:{de:`Feld '${C.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 '${C.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...i9(C,z)),typeof C.minSelections=="number"&&typeof C.maxSelections=="number"&&C.minSelections>C.maxSelections&&r.push({severity:"error",path:z,code:"config.min-gt-max-selections",message:{de:`Feld '${C.key}' hat minSelections (${C.minSelections}) > maxSelections (${C.maxSelections}).`,en:`Field '${C.key}' has minSelections (${C.minSelections}) > maxSelections (${C.maxSelections}).`}}),r.push(...o9(C,z));let De=C.enumRef;De!==void 0&&r.push({severity:"error",path:`${z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${C.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 '${C.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(C.enumOptions??[]).forEach((Ee,hn)=>{let Qe=Zq(Ee);Qe!==null&&r.push({severity:"error",path:`${z}.enumOptions[${hn}]`,code:"config.enum-option-value",message:{de:Qe==="empty"?`Feld '${C.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 '${C.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Qe==="empty"?`Field '${C.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 '${C.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(C.attachments??[]).forEach((Ee,hn)=>{if("storageId"in Ee){r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.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 '${C.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!=="",En=Ee.url!==void 0&&Ee.url!=="";Qe===En&&r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Qe&&En?"beide":"keines"}).`,en:`Field '${C.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Qe&&En?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${C.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${C.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");I.fields.forEach((C,z)=>j(C,`${O}.fields[${z}]`)),I.groups?.forEach((C,z)=>{C.fields.forEach((le,ce)=>j(le,`${O}.groups[${z}].fields[${ce}]`))}),I.repeated?.forEach((C,z)=>{C.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((C,z)=>T(C,`${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(...rK(I,e.effects,`effects[${O}]`,j=>l.has(j)));return}I.kind==="organization"&&I.nameFrom?.forEach((j,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nameFrom[${C}]`,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}Jq(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.`}}),Qq(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 P=new Set,L=s(I=>{I.kind==="person"?P.add(I.bucket):I.kind==="organization"&&P.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(C=>L(C))),v(O.subsections??[])},"collectRepeatedBuckets");v(e.sections);let N=s((I,O)=>{P.size!==0&&I.forEach((j,C)=>{j.bucket===void 0||P.has(j.bucket)||r.push({severity:"error",path:`${O}[${C}].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(".")}]`;N(I.fields,`${j}.fields`),I.groups?.forEach((C,z)=>N(C.fields,`${j}.groups[${z}].fields`)),I.repeated?.forEach((C,z)=>N(C.itemTemplate,`${j}.repeated[${z}].itemTemplate`)),I.subsections?.forEach((C,z)=>A(C,[...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,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nationalityFrom[${C}]`,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:C})=>{let z=I.get(j.bucket);if(z===void 0){I.set(j.bucket,j.id);return}r.push({severity:"error",path:`effects[${C}].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:C})=>{r.push({severity:"error",path:`effects[${C}].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:C})=>{j.subject!==!0&&r.push({severity:"error",path:`effects[${C}].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:C})=>{let z=j.contractParty?.role;z!==void 0&&z!=="beneficiary"&&r.push({severity:"error",path:`effects[${C}].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,C)=>{a.has(j.from)||r.push({severity:"error",path:`effects[${O}].mappings[${C}].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`,C=u.get(O.sameAs.source);C===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).`}}):C.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 (${C.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${I}' (${O.type}) sameAs.source '${O.sameAs.source}' has a different type (${C.type}) \u2014 the mirror must be shape-identical.`}}):C.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 C=O.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===C&&le.mappings.some(ce=>ce.to===O.field)||le.kind==="shareValue"&&le.id!==O.id&&le.to.slice(1)===C&&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(oi)&&r.push({severity:"error",path:`effects[${O}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': bucket '${I.bucket}' darf '${oi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' bucket '${I.bucket}' must not contain '${oi}' (reserved for the per-row namespace).`}}),I.kind==="organization"&&I.orgKind.includes(oi)&&r.push({severity:"error",path:`effects[${O}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': orgKind '${I.orgKind}' darf '${oi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' orgKind '${I.orgKind}' must not contain '${oi}' (reserved for the per-row namespace).`}})});let oe=new Set;function Q(I,O){I.repeated?.forEach((j,C)=>{let z=j.effects??[];if(z.length>0){let le=`${O}.repeated[${C}]`,ce=new Set(z.map(se=>se.id)),De=new Set(j.itemTemplate.map(se=>se.key)),Ee=(j.uniqueBy?.length??0)>0,hn=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"),En=s(se=>{let Wn=se.slice(1);return ce.has(Wn)||h.has(Wn)},"resolvesRef");z.forEach((se,Wn)=>{let gn=`${le}.effects[${Wn}]`;if(h.has(se.id)||oe.has(se.id)?r.push({severity:"error",path:gn,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,gn),se.kind==="person"&&se.subject===!0&&r.push({severity:"error",path:`${gn}.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:`${gn}.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:`${gn}.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(oi)&&r.push({severity:"error",path:`${gn}.${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 '${oi}' nicht enthalten.`,en:`Repeated effect '${se.id}' ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${oi}'.`}}),se.kind==="person"&&r.push(...rK(se,z,gn,hn)),se.kind==="organization"&&se.nameFrom?.forEach((Be,Lt)=>{hn(Be)||r.push({severity:"error",path:`${gn}.nameFrom[${Lt}]`,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,Lt)=>{Qe(Be)||r.push({severity:"error",path:`${gn}.identity.keyFrom[${Lt}]`,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])=>{En(Be)||r.push({severity:"error",path:`${gn}.${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("$")&&!En(Be)&&r.push({severity:"error",path:`${gn}.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"?(En(se.target)||r.push({severity:"error",path:`${gn}.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:`${gn}.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:gn,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,C)=>Q(j,`${O}.subsections[${C}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((I,O)=>Q(I,`sections[${O}]`));let re=Lq(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(...r9(e)),r}s(iK,"validateForm");function r9(e){let n={...e,effects:e.effects.map(oK),sections:e.sections.map(sK),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return ym(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:Kk(t)}))}s(r9,"missingTranslationIssues");function oK(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(oK,"withoutSubjectFlag");function sK(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(oK)})),subsections:e.subsections?.map(sK)}}s(sK,"withoutRowSubjectFlags");function Xq(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(Xq,"reviewRequiredShapeIssues");function eK(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(eK,"exportGateIssues");function Za(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${nK(r,"de")} '${n}'`,en:`Duplicate ${nK(r,"en")}: '${n}'`}}):e.add(n)}s(Za,"reportIfDup");function nK(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(nK,"labelForCode");function dS(e,n,t,r,i,o){e.visibleIf&&(Pr(e.visibleIf,`${n}.visibleIf`,t,r,o),Xa(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(Pr(e.requiredIf,`${n}.requiredIf`,t,r,o),Xa(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(Pr(e.disabledIf,`${n}.disabledIf`,t,r,o),Xa(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&Pr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s(dS,"checkFieldAsts");function cS(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(cS,"gatingMeta");function Xa(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(tK(o.left,o.right,o.op,n,t,r),tK(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(Xa,"checkGatingExpr");function tK(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(tK,"inspectEqualityOperand");function Pr(e,n,t,r,i){i.push(...bC(e,t.declaredContext,n)),i.push(...pm(e,t.stageKeys,n));for(let o of Ln(e))t.known.has(o)||Fk(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(Pr,"checkAst");function rK(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=zq(e.id,n);Yq(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 Wq(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(rK,"personNameIssues");function i9(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(i9,"consentConfigIssues");function o9(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(o9,"exclusiveOptionIssues");var s9="blocked";function aK(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=kn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(a9(i))return r.id===s9?null:r.id}return null}s(aK,"resolveActiveOutcome");function a9(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(a9,"truthy");function lK(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(lK,"isScalar");function l9(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(lK(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))lK(a)&&(n[`${r}.${o}`]=a)}d9(e,n,t)}s(l9,"mergeRecord");function d9(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);fo(a).test(i)&&r.add(a)}for(let i of r){let o=sS(e,i),a=0;for(let l=0;l<o;l++)qq(e,i,l)&&a++;n[`${i}.count`]=a}}s(d9,"mergeRepeatedCounts");function dK(e,n,t){let r={...t};return l9(e,r,n),r}s(dK,"flattenValues");function uS(e,n,t){return{code:e,fieldKey:n,text:t}}s(uS,"submitIssue");function cK(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(cK,"truthyEval");function uK(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(uK,"isEmptyValue");function c9(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=cK(kn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(c9,"fieldIsLiveRequired");function u9(e,n,t){return fK(e,n,t).evalCtx}s(u9,"buildSubmitEvalContext");function fK(e,n,t){let r=f9(e),i=Object.keys(n).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,k]of Object.entries(n))(r(y)===null||o.has(y))&&(l[y]=k);let d=pK(e,l,t),c=new Set,u=new Set;hK(e,d,y=>c.add(y.key),y=>u.add(y.key));let p=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(p.size===o.size&&[...p].every(y=>o.has(y))){let y={};for(let k of i)o.has(k)||(y[k]=n[k]);return{visible:l,hidden:y,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let y=i.filter(k=>p.has(k)!==o.has(k));F(`[smartForm] visibility of ${y.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(fK,"splitWithContext");function f9(e){let n=new Map,t=[];for(let r of Gh(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:fo(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(f9,"fieldOwnership");function pK(e,n,t){let r=[];for(let o of Gh(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=dK(n,r,t);for(let o of Gh(e.sections))for(let a of o.computed??[])try{i[a.key]=kn(a.expression,{values:i})}catch{}return i}s(pK,"rawEvalContext");function mK(e,n,t){let{values:r,defaulted:i}=p9(e,n,t),o=fK(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(mK,"splitDraftValues");function p9(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of Gh(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??=pK(e,n,t);let c;try{c=kn(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(p9,"applyFieldDefaults");function Gh(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(Gh,"walkSectionsDeep");function m9(e,n,t,r=!1){if(uK(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(m9,"fieldFormatIssue");function h9(e,n){return uK(n)||e.type==="consent"&&n!==!0}s(h9,"isUnanswered");function Uh(e,n){if(!e)return!0;try{return cK(kn(e,{values:n}))}catch{return!1}}s(Uh,"isVisibleUnder");function hK(e,n,t,r){let i=s(o=>{if(Uh(o.visibleIf,n)){for(let a of o.fields)Uh(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(Uh(a.visibleIf,n))for(let l of a.fields)Uh(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(hK,"forEachVisibleField");function gK(e,n,t,r={}){let i=u9(e,n,t),o=[],a=aK(e,i);a===null&&r.requireOutcome!==!1&&o.push(uS("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 hK(e,i,d=>{let c=n[d.key];if(h9(d,c)){!l.has(d.type)&&c9(d,i,a)&&o.push(uS("required",d.key,Ul([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=m9(d,c,r.registry,r.testMode===!0);u!==null&&o.push(uS("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(gK,"checkSubmittable");function yK(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=Ta(e),r=[];for(let i of n){let o=i.prefill??{};if(!hC(e,i.env))continue;let a=yC(e,i.env),{visible:l}=mK(t,o,a),d=gK(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:Ul([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(yK,"validateScenarios");function zh(e){return e.filter(n=>(n.severity??"error")==="error")}s(zh,"blockingIssues");function Wh(e,n={}){return[...iK(e,n),...yK(e)]}s(Wh,"runFormValidators");function Yh(e){return zh(e)}s(Yh,"blockingFormErrors");function wK(e,n,t){return PD(e,n,t)}s(wK,"runWorkflowValidators");function kK(e){return zh(e)}s(kK,"blockingWorkflowErrors");var g9=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var bK={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"]}},xt={id:m.string(),label:so,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())},y9=m.object({...xt,type:m.literal("join")}),w9=m.object({...xt,type:m.literal("end")}),k9=m.object({...xt,type:m.literal("eventTrigger")}),b9=m.object({...xt,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),v9=m.object({...xt,type:m.literal("roleAssign")}),x9=m.object({...xt,type:m.literal("setFlag")}),S9=m.object({...xt,type:m.literal("if"),condition:m.optional(m.any())}),A9=m.object({...xt,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),E9=m.object({...xt,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),T9=m.object({...xt,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())}),$9=m.object({...xt,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),R9=m.object({...xt,type:m.literal("waitlist")}),I9=m.object({...xt,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),O9=m.object({...xt,type:m.literal("collectPayment")}),_9=m.object({...xt,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())}),xKe=m.union(y9,w9,k9,b9,v9,x9,S9,A9,E9,T9,$9,R9,I9,O9,_9);function vK(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 bK)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=bK[a],d=new Set(["id","type","label",...g9,...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(vK,"workflowNodeEnvelopeIssues");var xK=s(e=>e,"asEffectId"),po=s(e=>e,"asOutcomeId"),el=s(e=>e,"asSectionId"),ut=s(e=>e,"asFieldKey");var Nr=["string","boolean","consent","date","enum","email","tel","address","docRef"],gc=["person","organization","relationship","fieldMap"],mo=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],nl=["fresh","keyed","manual"];function hs(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(hs,"optionalLocalizedText");function tt(e,n){if(!(e===void 0||e===""))try{Fn(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(tt,"assertExpression");function yc(e){return Object.keys(e.smartforms??{})}s(yc,"carriedFormSlugs");function fS(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(fS,"boundFormSlugs");function Hh(e,n){let t=yc(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(Hh,"resolveFormSlug");function Jh(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(Jh,"getForm");function Ht(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(Ht,"walkSections");function fr(e,n){return Ht(e).find(t=>t.id===n)}s(fr,"findSection");function gs(e,n){for(let t of Ht(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(gs,"findField");function ys(e){let n=new Set;for(let t of Ht(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(ys,"allFieldKeys");function P9(e){let n=dn(e.label,e.labelEn,"offer form add"),t={id:el("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:po("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(P9,"buildSkeletonSmartForm");function Qh(e,n){let{key:t,label:r}=n;if(yc(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=P9({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(Qh,"addForm");function SK(e,n){if(!yc(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(fS(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(SK,"removeForm");function AK(e,n){let t=Jh(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");vn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(AK,"setForm");function EK(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(EK,"nodesOf");function TK(e,n,t){let r=EK(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(TK,"nodeOf");function $K(e){return e.flatMap(n=>{if(n.type!=="form"||It(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s($K,"creatingFormNodes");function RK(e){return Yh(Wh(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(RK,"formErrors");function Zh(e){let n="offer workflow restamp-exports",t=EK(e,n),r=[];for(let{node:i,slug:o}of $K(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=RK(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11437
+ `)}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}},fx=class extends D{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=XQ(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:gx(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}},px=class extends D{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:gx(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}},uc=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function bh(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":uc(n[r],""),...t===null?{}:{platform:uc(t[r],"")}}))}s(bh,"chromeTextRows");var mx=class extends D{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=>[...bh("greeting",r.greeting,r.defaults.greeting),...bh("closing",r.closing,r.defaults.closing),{field:"senderName",school:uc(r.senderName,"\u2014 (platform)"),platform:uc(r.defaults.senderName,"")}],["field","school","platform"]),0}},hx=class extends D{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=>[...bh("greeting",l.greeting,null),...bh("closing",l.closing,null),{field:"senderName",school:uc(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},q0=[ox,sx,ax,lx,dx,cx,ux,fx,px,mx,hx];var n8={capacity:null,isOpen:!1},t8={capacity:null,isOpen:!0};function r8(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(r8,"isCapacity");function vh(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)||!r8(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(vh,"capacitySpecIssues");function j0(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(Yr(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===nr(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 y=i.get(p);if(y===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},w=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,b=w!==void 0?{capacity:w.capacity,isOpen:w.isOpen}:u===void 0?n8:t8;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:p,from:b,to:k})}}return d}s(j0,"planRunCapacities");function K0(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(K0,"describeCell");function xh(e){return`~cap ${e.run}\xD7${e.stageKey} ${K0(e.from)} \u2192 ${K0(e.to)}`}s(xh,"describeCapacityStep");function V0(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(V0,"assertBackendHasStageKeys");async function yx(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}));V0(i);let a=tp(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(yx,"planStages");async function Sh(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});V0(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>Yr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return j0(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===nr(d,c)))})}s(Sh,"planCapacities");async function i8(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===nr(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(i8,"assertNoArchivedRunKey");var wx={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...np(o??[]),...ep(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(w=>w.message.de).join("; ")}`);let l=vh(t.program?.runs??[],o?.map(w=>w.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await i8(e,i,n,t);let d=await Sh(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=o8(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(w=>w.key===u);if(!p)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(w=>w.key===null?[]:[w.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 w=await yx(e,i,n,o);h.push(...w.map(rp))}else{let w=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(...w.steps,...w.warnings.map(b=>`warning ${b}`))}let y=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let w of t.program?.runs??[]){let b=y.programKey===null?void 0:y.runs.find(E=>E.key===nr(y.programKey,w.key));if(b!==void 0){Bs(b.name,w.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:w.name}),h.push(`~run ${w.key} ("${Ce(b.name)}" \u2192 "${Ce(w.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,key:w.key,name:w.name,isOpen:w.capacities!==void 0?!1:w.isOpen??!0,...w.startDate?{startDate:w.startDate}:{},...w.endDate?{endDate:w.endDate}:{}}),h.push(`+run ${w.key} (${Ce(w.name)})`)}let k=r.dryRun?d:await Sh(e,i,n,t);if(!r.dryRun&&k.length>0){let w=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=w.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let E of k){let T=w.runs.find(P=>P.key===nr(b,E.run))?.runId,R=w.stages.find(P=>Yr(b,P.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(xh)),h.join(", ")}};function o8(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(o8,"bundleUnitKey");var B0={role:"control",effect:"pure",cardinality:"N-to-1"};var Ah=["add","remove","replace"];function U0(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(U0,"roleAssignLiteral");var G0={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=U0(e,"roleKey")?.trim()??"",o=U0(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"}),Ah.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 ${Ah.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Ah.join(" | ")}.`},severity:"error"}),r},"validate")};var s8=["event","effect","outcomes"],kx=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),z0={outcomes:[{id:Er,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of s8)i in r&&t.push(kx(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${Er}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${Er}" itself.`));return or(n.nodes).some(i=>i.target===e.id)&&t.push(kx(`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?.[Er]===void 0&&t.push(kx(`nodes.${e.id}.next.${Er}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${Er}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${Er}" nowhere.`)),t},"validate")};var a8="submit",W0=[{id:a8,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function Y0(e){return e==="draft"}s(Y0,"isWritableSmartFormState");var bx=["draft","committed"],_Pe=bx.filter(e=>Y0(e));async function H0(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(H0,"getSmartFormInstance");var J0="form:fill",vx="request:collectPayment",xx="request:collectPaymentSeparate",$i="confirmPayment";var l8={key:J0,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},Q0={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},Z0={[bO]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:Q0,external:nn(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")},[sp]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:Q0,external:nn(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."))}},X0={role:"user-action",effect:"side-effect",progressDefaults:Z0,progressEvents:Gn(Z0),actions:s(()=>W0,"actions"),workItemTemplates:s(()=>[l8],"workItemTemplates"),states:bx,currentState:s(async(e,n)=>{let t=await H0(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=>It(e)?[]:[{id:ap,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 eM={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:Mn.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:Mn.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:Mn.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:K_(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[Mn.flagKey]?.kind==="literal"&&Rp(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Mn.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?.[Mn.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Mn.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 d8="true",c8="false",Sx=[{id:d8,label:{de:"Ja",en:"Yes"}},{id:c8,label:{de:"Nein",en:"No"}}];var nM={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Sx,validate:s((e,n,t)=>u8(e,n,t),"validate")};function u8(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=Sx.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,...mm(e.condition,DO(n),t).map(r)]}s(u8,"ifNodeIssues");var Ha="decision",f8=new Set(["decision","review"]),nNe=new Set([...f8,"governedDocument"]);var rM=[{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"}],tM={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:nn(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."))}},ps={role:"user-action",effect:"side-effect",outcomes:rM,progressDefaults:tM,progressEvents:Gn(tM),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,...Wi(n.semantic)?{semantic:n.semantic}:{}})),...NC(e)],"actions"),optionalActionKinds:["spawnTasks","skipRule"],workItemTemplates:s(e=>[{key:Ha,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===Ha&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),taskView:s((e,n)=>n===Ha?e.view:void 0,"taskView"),validate:Ax};function Ax(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 ${Rt.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${Rt.join(", ")}.`},severity:"error"}):Wi(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: ${Rt.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${Rt.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(Ax,"validateDecisionNode");var Ex=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],iM=[{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 Tx="promoted";var oM="promote",sM="Nachr\xFCcken",Ja="promoteLabel";var p8={de:sM,en:"Promote from waitlist"};function m8(e){let n=e.inputs?.[Ja];if(n===void 0||n.kind==="unset")return p8;let t=n.kind==="literal"?n.value:void 0;return jo(t)!==null&&F(`waitlist node ${e.id}: inputs.${Ja} ${JSON.stringify(n)} is not a { de, en } literal`),t}s(m8,"promoteLabelOf");var $x={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},aM={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:$x,external:nn(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:$x,external:nn(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:$x,external:nn(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."))}},lM={outcomes:Ex,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:rr.map(e=>({value:e,label:WO[e]}))},{id:Ja,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?.[Ja];if(t?.kind==="literal"){let a=jo(t.value);if(a!==null)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Ja}`,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=vw(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=vw(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:aM,progressEvents:Gn(aM),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:Ex).some(t=>t.id===Tx)?[{id:oM,kind:"advance",outcome:Tx,semantic:"other",label:m8(e),surface:sr,superUserOnly:!0,teamAssignable:!0}]:[],"actions")};var Rx="complete",fc="acceptedIncomplete",Eh="rejected",h8="absage",dM="closeWithoutDocuments",cM="rejectAtCompleteness",uM="Ohne Nachreichung abschlie\xDFen",fM="Ablehnen",pM="awaitingDocuments",Ix="documentsComplete",Ox="closedWithoutDocuments",_x="rejected",Px="withdrawn",mM="requested",ANe={[Rx]:{event:Ix,status:"complete",endsRole:!0},[fc]:{event:Ox,status:"acceptedIncomplete",endsRole:!1},[Eh]:{event:_x,status:"rejected",endsRole:!0},[h8]:{event:Px,status:"withdrawn",endsRole:!0}};var pc=s(()=>Ql[0],"beneficiary"),Nx=366;function g8(e){let n=e.reads,t=Zl(e).flatMap(({address:r})=>un(r)&&!Ql.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(un):[],...t]}s(g8,"printedFields");function y8(e,n){let t=de(n);return e.nodes.filter(r=>r.type==="governedDocument"&&g8(r).some(i=>de(i)===t))}s(y8,"documentsPrinting");function w8(e,n){if(!un(n)||n.path!==pc())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!It(t)}s(w8,"isCreatedFormBeneficiary");function zn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(zn,"issue");function k8(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Rx,fc].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)&&$r(d.form)&&d.form.owner===t)){if(d.type==="end"){if(Uo(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(k8,"reachesApprovedEndUnreviewed");var Cx={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},hM={[pM]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:Cx,external:nn(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."))},[Ix]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:Cx,external:nn(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."))},[Ox]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:Cx,external:nn(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."))},[_x]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:zP,external:nn(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."))},[Px]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:Wp,external:nn(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."))}},gM={outcomes:iM,progressDefaults:hM,progressEvents:Gn(hM),notificationEvents:s(()=>[{id:mM,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(fc)&&t.push({id:dM,kind:"advance",outcome:fc,semantic:"other",label:{de:uM,en:"Close without documents"},surface:sr,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(Eh)&&t.push({id:cM,kind:"advance",outcome:Eh,semantic:"rejected",label:{de:fM,en:"Reject application"},surface:sr,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(zn(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(zn(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(zn(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 P=Zr(t,T);if(P==null)continue;let L=ca("requires",da(P));L==="computed"||L==="repeated"?r.push(zn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a(T)} ist ${P.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l(T)} is ${P.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):L==="untranslated"&&r.push(zn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a(T)} (\u201E${Zi(P,"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)} ("${Zi(P,"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(zn(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>Nx)&&r.push(zn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(E)}" ist keine ganze Zahl von 0 bis ${Nx} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(E)}" is not a whole number from 0 to ${Nx} days.`}))}else typeof u.until!="string"||hk(u.until)===null?r.push(zn(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<pN(Date.now())&&r.push({...zn(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 y8(n,T))r.push(zn(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(P=>{let L=Zr(t,P);return L!=null&&hm(L)}),R=[...new Set(E.map(P=>P.owner))].filter(P=>k8(n,e,P));if(R.length>0){let P=E.filter(L=>R.includes(L.owner));r.push({...zn(e,"next",{de:`[review/unreviewedAfterSupply] ${P.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] ${P.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 y=e.inputs?.guestRole,k=y?.kind==="literal"?y.value:void 0,w=e.inputs?.person,b=w?.kind==="binding"?w.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(zn(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(zn(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(zn(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(zn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${Un}.${pc()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${Un}.${pc()}).`}))),we(b)&&!w8(n,b)&&r.push(zn(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>.${Un}.${pc()}).`,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>.${Un}.${pc()}).`})),b!==null&&k===void 0&&r.push(zn(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(zn(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 b8=[{id:HO,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Th=s(e=>e,"asDecision"),yM={[JO]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:nn(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."))}},wM={role:"user-action",effect:"side-effect",outcomes:b8,progressDefaults:yM,progressEvents:Gn(yM),notificationEvents:s(e=>ps.notificationEvents(Th(e)),"notificationEvents"),inputs:s(()=>[{id:lr,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:rs.map(e=>({value:e,label:KD[e]}))}],"inputs"),actions:s(e=>[...ps.actions(Th(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Aw,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:ps.optionalActionKinds,workItemTemplates:s(e=>ps.workItemTemplates(Th(e)).map(n=>n.key===Ha?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Aw]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Ax(Th(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!bp.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?.[lr],a=jD(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${lr}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${rs.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${rs.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)&&$r(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(hm)&&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 kM=["awaitingAnswer","answered"];async function bM(e,n){return(await ka(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(bM,"externalRequestState");var SM=[{id:Vo,label:{de:"Bezahlt",en:"Paid"}}],lCe=new Set(SM.map(e=>e.id));var v8=Vo,vM=[{id:v8,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],x8={id:Qw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},surface:sr,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"}}},S8={id:Jw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:sr,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"}}},A8={id:Jw,kind:"advance",outcome:Vo,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:sr,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 Dx(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Dx,"literalOf");function ao(e){let n=Dx(e,ct);return _p(n)?n:null}s(ao,"modeOrNull");function E8(e){let n=Dx(e,Ji);return typeof n=="string"&&n.length>0?n:null}s(E8,"articleKeyOrNull");function T8(e){let n=Dx(e,ir);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(T8,"payeeKeyOrNull");var $8={id:Ji,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},R8={id:ct,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)"}}]},I8={id:Qi,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},O8={id:ir,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function _8(e){return[$8,R8,...ao(e)==="online"?[O8]:[],I8]}s(_8,"collectPaymentInputs");var P8=["amount","currency","settlement"],N8={de:"Zahlungseingang best\xE4tigen",en:"Confirm payment received"},C8={de:"Bewerbungsgeb\xFChr bezahlen",en:"Pay the application fee"};function D8(e,n){if(ao(e)!=="online")return[];let t=T8(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${ir}`,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(D8,"payeeIssues");var xM={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:nn(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."))}},AM={outputs:s(()=>[{name:O_,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>_8(e),"inputs"),outcomes:SM,progressDefaults:xM,progressEvents:Gn(xM),notificationEvents:s(e=>ao(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=ao(e);return n==="online"?[...vM,A8]:n==="manual"?[x8,S8]:[]},"actions"),states:kM,currentState:s((e,n)=>bM(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:ao(n.node)==="manual"?xx:vx}),"currentState"),workItemTemplates:s(e=>{let n=e,t=ao(n);return t==="manual"?[{key:$i,recipient:"internal",title:N8,unlocks:[Qw],advancesNode:!0},{key:xx,recipient:"external",title:C8,unlocks:[],informational:!0,advancesNode:!1}]:t!=="online"?[]:[{key:vx,recipient:"external",title:n.label,unlocks:vM.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 P8)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(...D8(e,t)),ao(e)==="manual"&&e.assign?.[$i]===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."}),ao(e)===null&&i(`inputs.${ct}`,{de:`[collectPayment/invalidMode] Zahlungsweg muss einer von ${oa.join(", ")} sein (online = die Familie zahlt im Portal, manual = die Schule erh\xE4lt das Geld au\xDFerhalb von Plexus); erhalten ${JSON.stringify(e.inputs?.[ct])}.`,en:`[collectPayment/invalidMode] Payment mode must be one of ${oa.join(", ")} (online = the family pays in the portal, manual = the school receives the money outside Plexus); received ${JSON.stringify(e.inputs?.[ct])}.`});let o=e.inputs?.[Qi];if(o?.kind==="literal"){let d=jo(o.value);d!==null&&i(`inputs.${Qi}`,{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=E8(e);if(a===null)return i(`inputs.${Ji}`,{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.${Ji}`;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 ${Zw.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Zw.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 EM(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(EM,"localeFieldMissingText");var Fx=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),TM=/^[a-z][a-z0-9_]*$/;function $M(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"||!TM.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(!Hi(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 (${ia.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 (${ia.join(", ")}).`}});continue}if(Fx.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 ${[...Fx].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a document from a template only prints ${[...Fx].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!TM.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&&!Em.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${Em.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${Em.join(", ")}.`}})}return t.push(...F8(e,n)),t}s($M,"templateParameterIssues");function F8(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:EM(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(F8,"localeFieldIssues");function RM(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(RM,"applyTemplateStamp");var Lx=50;async function $h(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(Lx+1);return t.length>Lx&&F(`signing_returns: Vorgang ${n} has more than ${Lx} returns`),t}s($h,"returnsOf");var Mx=50;async function qx(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(Mx+1);return t.length>Mx&&F(`signing_returns: return ${n} has more than ${Mx} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(qx,"returnDocumentsOf");async function IM(e,n){let t=await qx(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(IM,"soleReturnDocumentOf");var Rh=200,RCe=Rh*20;async function L8(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(L8,"processRedacted");async function Kx(e,n){await L8(e,n)&&ae("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(Kx,"assertProcessReadable");function M8(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(M8,"rowOf");async function OM(e,n,t){await Kx(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(Rh+1);return r.length>Rh&&F(`[process] application ${n} has more than ${Rh} results of ${t.scope}.${t.owner}.${t.key}`),r.map(M8)}s(OM,"storeHistory");async function q8(e,n,t){if(t.key===Un){await Kx(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 OM(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(q8,"nodeResultAt");async function Ih(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return K8(await q8(e,n.applicationId,t),t,n.applicationId)}s(Ih,"readOwnResult");function K8(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(K8,"refOf");var jx={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},j8=Object.keys(jx),V8=j8.filter(e=>jx[e]==="open"),LCe=V8.filter(e=>e!=="pending");function _M(e){return jx[e]==="terminal"}s(_M,"isTerminalSigningStatus");var lo=["docusign","insign"];var mc={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var U8=_M;function NM(e){return!U8(e.status)&&e.voidRequestedAt===void 0}s(NM,"holdsContract");async function CM(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(CM,"traegerLegalEntityOfParty");async function G8(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(G8,"isOrganizationParty");async function DM(e,n){return await CM(e,n)!==null?"traeger":await G8(e,n)?"organization":"person"}s(DM,"signerKindOf");async function FM(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await z8(e,t.partyId)==="family")return"family";return"traeger"}s(FM,"signingSideOf");async function z8(e,n){return await DM(e,n)==="traeger"?"traeger":"family"}s(z8,"sideOfParty");var vDe=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()}),billingItemDefinitionIds:m.array(m.id("billing_item_definitions"))}),MM=m.object({key:m.string(),name:m.object({de:m.string(),en:m.string()})});var Vx=m.union(m.literal("month"),m.literal("year"),m.literal("once"),m.literal("unit")),Oh=m.object({period:Vx,anchorDate:m.string()});var TDe=m.union(m.object({percent:m.number()}),m.object({amountMinor:m.number()})),$De=m.union(m.literal("line"),m.literal("aggregate")),_h=m.record(m.string(),m.string());var W8=m.union(m.literal("active"),m.literal("ended")),Bx=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()})),Y8=m.union(m.object({anchor:m.literal("enrollment")}),m.object({anchor:m.literal("manual"),activeFrom:m.string(),activeTo:m.optional(m.string())})),H8={contractId:Ve.belongsTo(m.id("contracts")),billingItemDefinitionId:Ve.restrict(m.id("billing_item_definitions")),pricing:Bx,pricingSelections:m.optional(_h),paymentSchedule:m.optional(Oh),resolvedSnapshot:m.any(),feeGroup:m.optional(MM),generationRunId:m.optional(Ve.history(m.id("contract_generation_runs")))},J8={...H8,period:Y8,enrollmentPeriodBaseline:m.optional(m.string()),enrollmentReconciliations:m.optional(m.record(m.string(),m.object({basis:m.string(),evidence:m.string()}))),status:W8,enrollmentContextId:m.optional(Ve.restrict(m.id("enrollments")))},DDe=qt(J8).index("by_contractId",["contractId"]).index("by_billingItemDefinitionId",["billingItemDefinitionId"]).index("by_enrollmentContextId",["enrollmentContextId"]).index("by_contractId_and_status",["contractId","status"]);var Or=m.union(m.string(),m.null()),qM=m.object({partyId:m.id("parties"),role:m.string(),nameAtSigning:m.string()}),Q8=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()}))}),KM=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(qM)})),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:Or}),jM=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(Vx),eligibleBillingItemDefinitionIds:m.optional(m.array(m.id("billing_item_definitions"))),eligibleContractLineIds:m.optional(m.array(m.id("contract_lines"))),activeFrom:m.string(),activeTo:Or,status:m.string(),qualifyingEnrolmentId:m.union(m.id("enrollments"),m.null()),eligibilityRuleOpaque:m.any(),eligibilityEvidenceOpaque:m.any()}),Z8={sourceContractLineId:m.id("contract_lines"),status:m.string(),activeFrom:m.string(),activeTo:Or,pricing:Bx,paymentSchedule:m.optional(Oh),pricingSelections:m.optional(_h),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:Or,endDate:Or,studentPartyId:m.id("parties"),studentNameAtSigning:m.string(),unitName:Or,programName:Or,runName:Or,groupName:Or}),m.null()),grants:m.array(jM),payerAllocations:m.array(KM)},X8=m.object({...Z8,resolvedPrice:m.object({amount:m.number(),currency:m.string(),sourceBillingItemVersionId:m.union(m.id("billing_item_versions"),m.null()),sourceValidFrom:Or,sourceValidTo:Or})}),eZ=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(qM),declaredSigners:m.array(Q8),payerAllocations:m.array(KM),aggregateGrants:m.optional(m.array(jM)),lines:m.array(X8)}),nZ=eZ;var tZ=m.object({left:m.number(),top:m.number(),width:m.number(),height:m.number()}),rZ=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:so})),caption:m.string(),page:m.number(),box:tZ}))});var iZ=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(rZ)}))}),oZ=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()}),sZ={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:iZ,coverLetter:m.optional(oZ),snapshot:Ve.historyOf(nZ),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()}))},UDe=qt(sZ).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 iFe=16*1024;var oFe=15*6e4;var sFe=10*6e4;var Ux={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()}))},SFe=qt({tenantId:Ve.tenant(m.id("tenants")),signingRequestDocumentId:Ve.belongsTo(m.id("signing_request_documents")),...Ux}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var RFe=m.object(Ux);var Gx=200;async function aZ(e,n,t,r){n.length>Gx&&F(`${r} is carried by more than ${Gx} 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(aZ,"requestsOfMembers");async function VM(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(Gx+1);return await aZ(e,r,t,`revision ${n}`)}s(VM,"requestsOfSnapshot");var BM=100;async function lZ(e,n){let t=await VM(e,n);t.length>BM&&F(`requestsBySideOf: revision ${n} has more than ${BM} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await FM(e,i.signers)].push(i);return r}s(lZ,"requestsBySideOf");async function zx(e,n){return(await lZ(e,n)).family}s(zx,"familyRequestsOf");var Wx=100;async function dZ(e,n){let t=await e;return t.length>Wx&&F(`contractChain: more than ${Wx} ${n}`),t}s(dZ,"bounded");async function cZ(e,n,t){let r=await Ih(e,{applicationId:n,nodeId:t,key:Tp});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Tp} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(cZ,"nodeContractRef");async function UM(e,n){return await dZ(e.db.query("contract_snapshots").withIndex("by_contractId_and_snapshotNumber",t=>t.eq("contractId",n)).take(Wx+1),`revisions on contract ${n}`)}s(UM,"snapshotsAsc");async function Yx(e,n){let t=(await zx(e,n)).filter(NM);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(Yx,"openFamilyRequest");async function uZ(e,n){for(let t of await UM(e,n))if((await zx(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(uZ,"familyRoute");async function GM(e,n){for(let t of n)if(await uZ(e,t)==="paper")return"paper";return"provider"}s(GM,"familyRouteOf");async function fZ(e,n){let t=await IM(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(fZ,"toReturn");function Ph(e){async function n(a,l){return await cZ(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 UM(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 Yx(a,c._id);if(u===null)return null;let p=(await $h(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 fZ(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(Ph,"contractNodeReads");function Nh(e){return e.addedParts??[]}s(Nh,"addedPartsOf");var Hx=50;async function pZ(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(pZ,"groupRunsOf");async function zM(e,n){let t=await pZ(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(zM,"groupRunsInOrder");function WM(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(WM,"isCompleteGroup");var Jx=200;function mZ(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(mZ,"groupPartKeys");async function hZ(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(Jx+1);return r.length>Jx&&F(`groupChain: more than ${Jx} generation runs on node ${t}`),r}s(hZ,"nodeRuns");async function gZ(e,n,t){let r=mZ(t),i=new Set;for(let a of await hZ(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 zM(e,a);if(!WM(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(gZ,"groupRevisionRows");async function Qx(e,n,t){let r=await Ih(e,{applicationId:n,nodeId:t,key:$p});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${$p} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(Qx,"nodeGroupContracts");async function yZ(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await Yx(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(yZ,"openGroupRequest");async function wZ(e,n){let t=[];for(let i of await qx(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(wZ,"toGroupReturn");function YM(e){async function n(i,o,a,l){let d=(await gZ(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 yZ(i,l);if(d===null)return null;let c=(await $h(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 wZ(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await Qx(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(YM,"groupNodeReads");async function kZ(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 Kb(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(kZ,"toRevision");async function bZ(e,n){let t=await kZ(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(bZ,"toReturn");function HM(e){let n=Im(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 bZ(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(HM,"artifactNodeReads");function Ch(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(Ch,"documentChainKind");function JM(e){switch(Ch(e)){case"contract":return Ph(e).reads;case"group":return YM(e).reads;case"artifact":return HM(e).reads}}s(JM,"documentReadsFor");var vZ={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function hc(e){let n=e.responseStrategy;return typeof n=="string"&&n in Si?Si[n].producesResponseArtifact:!1}s(hc,"returnsSignedCopy");function xZ(e){return hc(e)&&e.confirmContractTerms!==!1}s(xZ,"asksContractTerms");function QM(e){return xZ(e)?{title:e.contractTermsQuestionText??vZ,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(QM,"contractTermsConfirm");function ZM(e){let n=SZ(e);return n.length>0&&n.every(t=>t.status==="blocked")}s(ZM,"producerWindowHeld");function SZ(e){return e.filter(n=>n.isOpen&&n.kind==="admission"&&n.templateKey!==void 0&&vd.has(n.templateKey))}s(SZ,"openProducerRows");async function AZ(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:$k(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==ti||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${ti} row`),a}s(AZ,"rejectedReturnOfAsk");async function XM(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await AZ(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(XM,"returnedCopyOfAsk");var Zx=new Set([...vd,Rr,Qo,io,ti,bt]),iq={id:Qn,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},oq={id:No,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function EZ(e){let n=[],t=[{slot:iq,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:oq,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=Xl(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(EZ,"referenceInputIssues");var TZ={id:xi,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},$Z={id:Pa,type:"boolean",label:{de:"Anschreiben best\xE4tigen lassen",en:"Have the cover letter confirmed"},inspector:"literal-only"},RZ={id:Vt,type:"legalEntity",label:aD,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function IZ(e,n){let t=`inputs.${Vt}`,r=e.inputs?.[Vt];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=_a(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 (${wm.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 (${wm.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s(IZ,"traegerIssues");function Dh(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}}:(Ui(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(Dh,"generatorFields");function OZ(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(OZ,"deferredToCockpit");function _Z(e){return Hi(e.type)?e.type:void 0}s(_Z,"resolverSlotType");function PZ(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=Da(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(PZ,"issueConfirmation");function Se(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Se,"issue");function Fh(e){return Am.includes(e.production)&&ts.includes(e.approval)&&Tm.includes(e.responseStrategy)}s(Fh,"hasValidModes");async function Xx(e,n){let t=await ka(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(ZM(r))return"producingHeld";if(r.some(a=>a.templateKey!==void 0&&vd.has(a.templateKey)))return"producing";if(r.some(a=>a.templateKey===io))return"awaitingCoverLetter";let i=r.find(a=>a.templateKey===Rr);if(i!==void 0)return i.status==="blocked"?"deferred":"awaitingApproval";if(r.some(a=>a.templateKey===bt))return"signatureStalled";let o=r.find(a=>a.templateKey===Qo);if(o!==void 0){if(Ai(n.node).issuesBy==="provider"){let l=Ch(n.node)==="group"?(await Qx(e,n.applicationId,n.node.id)).map(d=>d.contractId):[await Ph(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 GM(e,l)==="provider")return"awaitingSignature"}return Ai(n.node).producesResponseArtifact?await XM(e,{chain:JM(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===ti)?"responseInCheck":"done"}s(Xx,"governedDocCurrentState");function eq(e){return e.production!=="none"&&Ch(e)!=="artifact"}s(eq,"keepsDocumentInContractDomain");function NZ(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!tr(r.key))return[];let i=Po(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(NZ,"envCoverageIssues");function sq(e,n){let t=[];for(let r of Dh(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...NZ(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"}:OZ(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(sq,"fieldSourceIssues");function CZ(e){let n=Ar(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=$M(e.templateStamp,n).map(({path:r,reason:i})=>Se(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...sq(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(CZ,"templateIssues");function DZ(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(DZ,"eSignatureAnchorIssues");function FZ(e,n){return n===void 0||n.sendable?[]:Ai(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(FZ,"eSignatureProviderIssues");var nq={key:"dokument",label:te("Dokument","Document"),scope:"node"},tq={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:nq,external:nn(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:nq,external:nn(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 rq(e,n){return!Fh(e)||e.production==="none"?null:n===io||Rm(e).some(r=>r.key===n)?Im(e):null}s(rq,"governedDocRowSlot");var aq={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Jo,"processHoldTemplate"),progressDefaults:tq,progressEvents:Gn(tq),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:"Anschreiben 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(!Fh(e))return[];let n=Ai(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=[...ns(e)?["awaitingCoverLetter"]:[],...i,...n.checksReturn?["responseInCheck"]:[]];return e.production!=="none"&&(t.push({id:Qk(e),kind:"internal",surface:Na,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...e.approval==="release"?{handsTo:Rr}:{},...PZ(e)??{}}),t.push({id:uD,kind:"internal",surface:Na,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:fD,kind:"internal",surface:Na,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:vm,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:ns(e)?["awaitingCoverLetter",...i]:i,external:{emphasis:"decline",event:"userTaskResolved"}}),ns(e)&&(t.push({id:km,kind:"internal",label:{de:"Angebot best\xE4tigen",en:"Confirm offer"},availableIn:["awaitingCoverLetter"],external:{emphasis:"primary",event:"coverLetterConfirmed"}}),t.push({id:bm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:["awaitingCoverLetter"],external:{emphasis:"secondary",event:"coverLetterRevisionRequested"}})),n.producesResponseArtifact&&t.push({id:xm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Sm,kind:"internal",surface:Na,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Zo,kind:"internal",surface:Na,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:pD,currentState:Xx,workItemTemplates:s(e=>{let n=e;return Fh(n)?Rm(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e,r=rq(t,n);return r===null?[]:Rm(t).find(o=>o.key===n)?.recipient==="internal"?[{kind:"artifact",key:r}]:[]},"taskDocuments"),taskView:s((e,n)=>{let t=rq(e,n);if(t!==null)return n===io?{kind:"artifact",slot:t,part:"coverLetter"}:{kind:"artifact",slot:t}},"taskView"),inputs:s(e=>[...e.production==="resolver"?[iq,RZ]:[],...e.production==="template"?[oq]:[],TZ,...e.generatorStamp?.coverLetter===!0?[$Z]:[],...Dh(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=_Z(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"&&Yi(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:qw,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Qo||n===io||n===bd||n===ti||n===bt){let t=n===Qo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===ti?{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===bt?{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: ${Jo}${e.approval==="release"?`, ${Rr}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${Jo}${e.approval==="release"?`, ${Rr}`:""}.`}}return n===Rr&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Rr}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Rr}" 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(eq(n.node))return!1;let t=await Xx(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&Ai(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=QM(n.node);if(t===null||eq(n.node))return null;let r=await Xx(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!Fh(e))return r.push(Se(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${Am.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${ts.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Tm.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 {${Am.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${ts.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${Tm.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=Si[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 y=e.assign??{};if(e.production!=="none"&&y.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"&&(y.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)y.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",y.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"?y.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.`})):y.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(...DZ(e,t),...FZ(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.`})),hc(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",y.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??[])Zx.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 (${[...Zx].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${E.key}" on node "${e.id}" collides with an intrinsic template (${[...Zx].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...IZ(e,t)):e.inputs?.[Vt]!==void 0&&r.push(Se(e,`inputs.${Vt}`,{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(...EZ(e)),e.production==="resolver"){let E=pi(e);if(E!==null){let T=VO(E);for(let R of Dh(e)){if(!Hi(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 (${ia.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 (${ia.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(...sq(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(...CZ(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?.[Pa];k!==void 0&&k.kind!=="unset"&&!(k.kind==="literal"&&typeof k.value=="boolean")&&r.push(Se(e,`inputs.${Pa}`,{de:`[governedDocument/coverLetterInput] Knoten "${e.id}": Die Best\xE4tigung des Anschreibens ist ein fester Wert ja oder nein.`,en:`[governedDocument/coverLetterInput] Node "${e.id}": the cover letter's confirmation is a fixed yes or no.`})),ns(e)&&(t!==void 0&&e.generatorStamp?.coverLetter!==!0&&r.push(Se(e,`inputs.${Pa}`,{de:`[governedDocument/coverLetterNotDeclared] Knoten "${e.id}" l\xE4sst ein Anschreiben 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 Anschreiben mit Best\xE4tigung braucht die Freigabe, denn Vertrag und Anschreiben werden zusammen freigegeben.`,en:`[governedDocument/coverLetterNeedsRelease] Node "${e.id}": a cover letter with confirmation needs the release, because contract and letter are released together.`})),Ai(e).producesResponseArtifact||r.push(Se(e,"responseStrategy",{de:`[governedDocument/coverLetterNeedsSigning] Knoten "${e.id}": Ein Anschreiben 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 w=e.inputs?.[xi],b=w===void 0||w.kind==="unset"?void 0:w.kind==="literal"?w.value:w;return b!==void 0&&!Sd(b)&&r.push(Se(e,`inputs.${xi}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(b)} \u2014 erlaubt ist eine ganze Zahl von ${Xo} bis ${es} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(b)} \u2014 a whole number from ${Xo} to ${es} days is allowed.`})),b===void 0&&Dh(e).some(E=>E.processSource==="responseDueInDays")&&r.push(Se(e,`inputs.${xi}`,{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 lq={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 Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Yt,"isRecord");var eS=["field","join","literal","address","payment","contract"],LZ=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),MZ=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function ur(e){return typeof e=="string"&&e.trim().length>0}s(ur,"nonEmptyString");function Lh(e,n,t,r,i="value"){if(!Yt(e)||!Yt(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=eS.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${eS.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${eS.join(" | ")}).`}});return}let[l]=a;l==="field"&&!ur(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(ur))&&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)||ur(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"&&tr(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&&!LZ.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&&!(ur(e.lookup)&&Yt(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"||Yt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Yt(d)&&MZ.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(Lh,"checkMapping");function co(e,n,t,r,i){if(!Yt(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=lq[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))Lh(l,`${n}.${a}`,r,i)}s(co,"checkBody");function dq(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(!Yt(o)||!ur(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),Lh(o.value,`${l}.value`,t,r),o.unless!==void 0&&Lh(o.unless,`${l}.unless`,t,r,"condition")})}s(dq,"checkAif");function nS(e){let n=[];if(!Yt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Yt(e.lookups)?e.lookups:{};Yt(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))(!Yt(i)||!Object.values(i).every(ur))&&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(ur(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),co(e.pupil,"engage.pupil","addPupil",t,n),co(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&co(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&co(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&co(e.medical,"engage.medical","addMedical",t,n),dq(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(!Yt(i)||!ur(i.key)||!ur(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),co(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&co(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)=>co(u,`${a}.${l}[${p}]`,d,t,n))}}dq(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&Lh(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Yt(r)||!ur(r.repeated)||!ur(r.field)||!ur(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(nS,"engagePushConfigIssues");function*tS(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(tS,"mappingsOf");function cq(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of tS(e))for(let i of qZ(t.from))n.add(KZ(i,r));return[...n]}s(cq,"configFieldKeys");function qZ(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(qZ,"formFieldsOf");function KZ(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s(KZ,"resolveFieldKey");function uq(e,n){for(let{mapping:t}of tS(e))if(n in t.from)return!0;return!1}s(uq,"configReadsSource");function fq(e){let n=new Set;for(let{mapping:t}of tS(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(fq,"configEnvLeaves");var pq="done",mq=["sandbox","production"];var Mh="engagePush",E0e=660*1e3;function uo(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(uo,"issue");function rS(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(rS,"literal");function hq(e){return nS(e.engage).length===0?e.engage:null}s(hq,"validConfig");function jZ(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(jZ,"bypassingPath");var gq={role:"system-action",effect:"side-effect",outcomes:[{id:pq,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=hq(e);return n===null?[]:fq(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=rS(e,"target");mq.includes(a)||o.push(uo(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=rS(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(uo(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?.[Mh]===void 0&&o.push(uo(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${Mh}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${Mh}\` names the team.`}));for(let k of nS(e.engage))o.push(uo(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"&&rS(k,"target")===a);d.length>0&&o.push(uo(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.`})),jZ(n,e.id)&&o.push(uo(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=hq(e),u=e;for(let[k,w,b,E]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])c===null||!uq(c,k)||u[w]!==void 0||o.push(uo(e,w,{de:aa("address/missing",{where:`\u201E${r}\u201C \u203A ${b}`},"de"),en:aa("address/missing",{where:`"${i}" \u203A ${E}`},"en")}));let p=u.form,h=we(p)&&p.scope==="node"?p.owner:void 0,y=h===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&y!==void 0){let k=new Set(y.keys()),w=cq(c).filter(b=>!k.has(b)&&!/\[\d+\]\./.test(b));if(w.length>0){let b=n.nodes.find(E=>E.id===h);o.push(uo(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${b?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${w.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${b?.label?.en||h}" does not know these fields \u2014 they are not transferred: ${w.join(", ")}.`},"warning"))}}return o},"validate")};var ms={join:B0,end:YP,roleAssign:G0,eventTrigger:z0,waitlist:lM,completenessCheck:gM,form:X0,setFlag:eM,if:nM,decision:ps,review:wM,collectPayment:AM,governedDocument:aq,countersign:$D,engagePush:gq};E_(ms);function yq(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(yq,"graphOf");function wq(e){let n=new Map;for(let t of e.nodes)for(let r of Jr(e,t))n.set(de(r.address),r.nodeId);return n}s(wq,"producedOf");function kq(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(qo(e,t).map(r=>de(r.address))));return n}s(kq,"readsOf");function bq(e,n){let t=yq(e,"bundle"),r=yq(n.graph,"live head"),i=wq(t),o=wq(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=kq(t),d=kq(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,y=[...p].filter(w=>!h.has(w)),k=[...h].filter(w=>!p.has(w));(y.length>0||k.length>0)&&c.push({nodeId:u,added:y,removed:k})}return{headRevision:n.revision,pinnedApplications:n.pinnedApplications,produced:a,reads:c}}s(bq,"planAddresses");function vq(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(vq,"addressPlanRows");function xq(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(xq,"changed");async function Sq(e,n,t){if(n.index.module!==wx.name)throw new Error(`offer: unknown module "${n.index.module}"`);return sF(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return wx.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(Sq,"applyOffer");async function Aq(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(Aq,"exportOffer");async function iS(e,n){let{index:t}=n,i=(await e.query(x.workflow.listManifests,{client:t.tenant})).find(y=>y.offerKey===t.slugs.manifest),o="create";i&&(o="same");let a={};for(let[y,k]of Object.entries(n.smartforms??{})){let w=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=w?.def?xq(k,{label:w.def.label,...w.def.definition})?"change":"same":"create"}let l="absent",d=null;if(n.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let y=await e.query(x.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),k=y?.publishedVersion??y?.draftVersion;l=xq(k&&{graph:Hs(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:Hs(k.graph),progressLayout:k.progressLayout,progressWiring:k.progressWiring})?"change":"same"}if(i){let y=await e.query(x.workflow.getOfferHeadPins,{client:t.tenant,offerKey:t.slugs.manifest});y!==null&&(d=bq(n.workflow.graph,y))}}let c=t.program?.stages,u=c===void 0?[]:i?await yx(e,t.tenant,t.slugs.manifest,c):tp(null,[],c),p=await Sh(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(iS,"diffOffer");function qh(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(qh,"contractProductionModeOf");function Eq(e){return qh(e)==="resolver"}s(Eq,"isResolverCarrierNode");function Kh(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=pi(t);return!Eq(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(Kh,"authoredPins");var Tq={type:"address",dataType:"composite"};var $q={type:"boolean",dataType:"boolean"};var Rq={type:"consent",dataType:"boolean"};var Iq={type:"date",dataType:"date"};var Oq={type:"docRef",dataType:"file"};var _q={type:"email",dataType:"text"};var Pq={type:"string",dataType:"text"};var Nq={type:"tel",dataType:"text"};var jh={address:Tq.dataType,boolean:$q.dataType,consent:Rq.dataType,date:Iq.dataType,docRef:Oq.dataType,email:_q.dataType,enum:PP.dataType,string:Pq.dataType,tel:Nq.dataType};function oS(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(oS,"shapeOf");function Cq(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,oS(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,oS(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}`,oS(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(Cq,"fieldMapScopes");function VZ(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(VZ,"computedKeysOf");function Dq(e){let n=[],t=VZ(e);for(let r of Cq(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(Dq,"validateFieldMapSources");function Fq(e){let n=[],t=new Set;for(let o of Cq(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(Fq,"validateFieldPersistence");var BZ="$";function UZ(e){return typeof e=="string"&&e.startsWith(BZ)}s(UZ,"isRef");function Vh(e){return e.slice(1)}s(Vh,"stripRef");function*GZ(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(GZ,"refSlots");function zZ(e){let n=new Set;for(let t of GZ(e))UZ(t)&&n.add(Vh(t));return[...n]}s(zZ,"collectRefs");function WZ(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 zZ(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=Vh(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&Vh(l.target)===a||l.kind==="shareValue"&&Vh(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(WZ,"buildAdjacency");function Lq(e){let{refsOf:n}=WZ(e),r=um(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(Lq,"detectCycle");function Mq(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(Mq,"escapeRegExp");function fo(e){return new RegExp(`^${Mq(e)}\\[(\\d+)\\]\\.(.+)$`)}s(fo,"repeatedRowKeyPattern");function sS(e,n){let t=fo(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(sS,"countRepeatedRows");function qq(e,n,t){let r=fo(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(qq,"repeatedRowHasData");function Kq(e){return e.endsWith(".count")?e.slice(0,-6):e}s(Kq,"readKeyOf");function aS(e){return{sections:e,fields:[]}}s(aS,"hiddenSectionsOnly");function jq(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??[])jq(r,n,t)}s(jq,"collectKeys");function Vq(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;jq(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(fo)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(Vq,"restrictedSectionsOf");function Bq(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(Bq,"matchesKey");function YZ(e,n){return n.find(t=>Bq(e,t))??null}s(YZ,"hiddenSectionOfKey");function HZ(e,n){for(let t=e;;){if(Bq(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(HZ,"fieldOwnsKey");function JZ(e,n){return n.find(t=>HZ(e,t))??null}s(JZ,"restrictedFieldOfKey");function QZ(e,n){let t=YZ(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=JZ(e,n.fields);return r===null?null:{kind:"field",field:r}}s(QZ,"hiddenOwnerOfKey");function Bh(e,n){return QZ(e,n)!==null}s(Bh,"isKeyHidden");function ZZ(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(ZZ,"visibleToListIssues");function Uq(e,n,t){let r=[],i=s((c,u,p)=>{let h=c.visibleTo;h!==void 0&&r.push(...ZZ(c.id,h,`${u}.visibleTo`,p,t));let y=p||h!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(w=>w.fields),...(c.repeated??[]).flatMap(w=>w.itemTemplate)];for(let w of k)w.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${w.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${w.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,w)=>i(k,`${u}.subsections[${w}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=Vq(e);if(o.length===0)return r;let a=s((c,u,p)=>{if(c===void 0)return;let h=aS(p);for(let y of Ln(c)){let k=Kq(y);(Bh(y,h)||Bh(k,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:{de:`${u} liest '${y}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`,en:`${u} reads '${y}' 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&&Bh(c.sameAs.source,aS(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,y=o.filter(k=>k.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,w)=>l(k,`${u}.fields[${w}]`,y)),c.groups?.forEach((k,w)=>{a(k.visibleIf,`${u}.groups[${w}].visibleIf`,y),k.fields.forEach((b,E)=>l(b,`${u}.groups[${w}].fields[${E}]`,y))}),c.repeated?.forEach((k,w)=>{a(k.itemVisibleIf,`${u}.repeated[${w}].itemVisibleIf`,y),k.itemTemplate.forEach((b,E)=>l(b,`${u}.repeated[${w}].itemTemplate[${E}]`,y))}),c.computed?.forEach((k,w)=>a(k.expression,`${u}.computed[${w}]`,y)),c.subsections?.forEach((k,w)=>d(k,`${u}.subsections[${w}]`,h))},"visitCompiled");return n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(Uq,"sectionVisibilityIssues");var oi="#";var Gq=s(e=>{let n=Mb.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),_r={firstName:Gq("persons.firstName"),lastName:Gq("persons.lastName")};function zq(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(zq,"personNameKeys");function Wq(e){return[...e.firstName,...e.lastName]}s(Wq,"personNameKeyList");function Yq(e){return e.firstName.length>0||e.lastName.length>0}s(Yq,"hasPersonName");function Qa(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 Qa(i.subsections??[],a,i.id))r.push(l)}),r}s(Qa,"walkSections");function XZ(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(XZ,"findFieldInSection");function Hq(e,n){for(let t of Qa(e.sections)){let r=XZ(t.section,n);if(r)return{section:t.section,field:r}}return null}s(Hq,"findField");var e9=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],n9=["blue","rose","amber","violet","teal","emerald","slate"];function Jq(e){return e9.includes(e)}s(Jq,"isBucketIconName");function Qq(e){return n9.includes(e)}s(Qq,"isBucketColorName");var t9="__clear__";function Zq(e){return e===""?"empty":e===t9?"reserved":null}s(Zq,"selectOptionValueDefect");var lS=lL.docRef.allowedMime;function iK(e,n={}){let t=Ta(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 C=`sections[${O.join(".")}]`;I.fields.forEach((z,le)=>{Za(a,z.key,`${C}.fields[${le}]`,"duplicate.field-key",r),l.add(z.key),u.set(z.key,z),c.set(z.key,cS(z)),z.externalFlag&&(z.type!=="boolean"&&r.push({severity:"error",path:`${C}.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:`${C}.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:`${C}.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:`${C}.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(...eK(z,`${C}.fields[${le}]`)),r.push(...Xq(z,`${C}.fields[${le}]`))}),I.groups?.forEach((z,le)=>{z.fields.forEach((ce,De)=>{Za(a,ce.key,`${C}.groups[${le}].fields[${De}]`,"duplicate.field-key",r),l.add(ce.key),u.set(ce.key,ce),c.set(ce.key,cS(ce)),ce.externalFlag&&r.push({severity:"error",path:`${C}.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(...eK(ce,`${C}.groups[${le}].fields[${De}]`)),r.push(...Xq(ce,`${C}.groups[${le}].fields[${De}]`))})}),I.repeated?.forEach((z,le)=>{z.itemTemplate.forEach((ce,De)=>{Za(a,ce.key,`${C}.repeated[${le}].itemTemplate[${De}]`,"duplicate.field-key",r),c.set(ce.key,cS(ce)),ce.externalFlag&&r.push({severity:"error",path:`${C}.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:`${C}.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:`${C}.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:`${C}.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:`${C}.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:`${C}.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),Za(a,z.key,`${C}.computed[${z.key}]`,"duplicate.field-key",r),z.exportType==="consent"&&r.push({severity:"error",path:`${C}.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:`${C}.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)=>{Za(h,I.id,`effects[${O}]`,"duplicate.effect-id",r)});let y=new Set;t.outcomes.forEach((I,O)=>{Za(y,I.id,`outcomes[${O}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((I,O)=>{I.output.effectRefs?.forEach((j,C)=>{h.has(j.effect)||r.push({severity:"error",path:`outcomes[${O}].output.effectRefs[${C}]`,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,C)=>{Hq(t,j.path)||r.push({severity:"error",path:`outcomes[${O}].output.fields[${C}]`,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 Qa(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 w={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:n.stageKeys};r.push(...vC(e)),r.push(...Uq(e,t,n.visibleToKeys)),r.push(...iD(e)),r.push(...wC(e,n.stageKeys));for(let I of Qa(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.visibleIf&&(Pr(O.visibleIf,`${j}.visibleIf`,w,!1,r),Xa(O.visibleIf,`${j}.visibleIf`,c,r)),O.fields.forEach((C,z)=>dS(C,`${j}.fields[${z}]`,w,!1,c,r)),O.groups?.forEach((C,z)=>{C.visibleIf&&(Pr(C.visibleIf,`${j}.groups[${z}].visibleIf`,w,!1,r),Xa(C.visibleIf,`${j}.groups[${z}].visibleIf`,c,r)),C.fields.forEach((le,ce)=>dS(le,`${j}.groups[${z}].fields[${ce}]`,w,!1,c,r))}),O.repeated?.forEach((C,z)=>{C.itemVisibleIf&&(Pr(C.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,w,!0,r),Xa(C.itemVisibleIf,`${j}.repeated[${z}].itemVisibleIf`,c,r)),C.itemTemplate.forEach((le,ce)=>dS(le,`${j}.repeated[${z}].itemTemplate[${ce}]`,w,!0,c,r)),C.effects?.forEach((le,ce)=>{le.when&&Pr(le.when,`${j}.repeated[${z}].effects[${ce}].when`,w,!0,r)})}),O.computed?.forEach((C,z)=>Pr(C.expression,`${j}.computed[${z}].expression`,w,!1,r))}t.effects.forEach((I,O)=>{I.when&&Pr(I.when,`effects[${O}].when`,w,!1,r)}),t.outcomes.forEach((I,O)=>{Pr(I.when,`outcomes[${O}].when`,w,!1,r)});let b=new Set(t.outcomes.map(I=>I.id));function E(I,O){I.requiredFor&&I.requiredFor.forEach((j,C)=>{b.has(j)||r.push({severity:"error",path:`${O}.requiredFor[${C}]`,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 Qa(t.sections)){let O=I.section,j=`sections[${I.path.join(".")}]`;O.fields.forEach((C,z)=>E(C,`${j}.fields[${z}]`)),O.groups?.forEach((C,z)=>{C.fields.forEach((le,ce)=>E(le,`${j}.groups[${z}].fields[${ce}]`))}),O.repeated?.forEach((C,z)=>{C.itemTemplate.forEach((le,ce)=>E(le,`${j}.repeated[${z}].itemTemplate[${ce}]`))})}function T(I,O){let j=s((C,z)=>{let le=(C.type==="docRef"?C.docRefConstraints?.mimeType??[]:[]).filter(Ee=>!lS.includes(Ee));le.length>0&&r.push({severity:"error",path:z,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${C.key}' erlaubt ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${lS.join(", ")}).`,en:`Field '${C.key}' allows ${le.map(Ee=>`'${Ee}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${lS.join(", ")}).`}});let ce=C.type==="docRef"?C.docRefConstraints?.minFiles:void 0;if(ce!==void 0){let Ee=C.docRefConstraints?.multiple===!0,hn=typeof ce=="number"&&Number.isInteger(ce)&&ce>=2;(!Ee||!hn)&&r.push({severity:"error",path:z,code:"config.docref-min-files",message:Ee?{de:`Feld '${C.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(ce)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${C.key}' sets docRefConstraints.minFiles to ${JSON.stringify(ce)} \u2014 it must be a whole number of at least 2.`}:{de:`Feld '${C.key}' setzt docRefConstraints.minFiles ohne docRefConstraints.multiple: true \u2014 eine Mindestanzahl gibt es nur bei einem Mehrfach-Upload.`,en:`Field '${C.key}' sets docRefConstraints.minFiles without docRefConstraints.multiple: true \u2014 a minimum count exists only on a multi-file upload.`}})}C.multiple===!0&&C.type!=="enum"&&r.push({severity:"error",path:z,code:"config.multiple-non-enum",message:{de:`Feld '${C.key}' setzt multiple: true, hat aber den Typ '${C.type}' \u2014 nur 'enum' unterst\xFCtzt Mehrfachauswahl.`+(C.type==="docRef"?" F\xFCr mehrere Dateien docRefConstraints.multiple: true verwenden.":""),en:`Field '${C.key}' sets multiple: true but is type '${C.type}' \u2014 only 'enum' supports multi-select.`+(C.type==="docRef"?" For several files use docRefConstraints.multiple: true.":"")}}),C.presentation==="yesNo"&&C.type!=="boolean"&&r.push({severity:"error",path:z,code:"config.yesno-non-boolean",message:{de:`Feld '${C.key}' setzt presentation: 'yesNo', hat aber den Typ '${C.type}' \u2014 nur 'boolean'-Felder lassen sich als Ja | Nein-Antwort darstellen.`,en:`Field '${C.key}' sets presentation: 'yesNo' but is type '${C.type}' \u2014 only 'boolean' fields can be drawn as the Yes | No answer.`}}),C.presentation==="yesNo"&&C.defaultValue!=null&&r.push({severity:"error",path:z,code:"config.yesno-default",message:{de:`Feld '${C.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 '${C.key}' is a Yes | No question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}}),r.push(...i9(C,z)),typeof C.minSelections=="number"&&typeof C.maxSelections=="number"&&C.minSelections>C.maxSelections&&r.push({severity:"error",path:z,code:"config.min-gt-max-selections",message:{de:`Feld '${C.key}' hat minSelections (${C.minSelections}) > maxSelections (${C.maxSelections}).`,en:`Field '${C.key}' has minSelections (${C.minSelections}) > maxSelections (${C.maxSelections}).`}}),r.push(...o9(C,z));let De=C.enumRef;De!==void 0&&r.push({severity:"error",path:`${z}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${C.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 '${C.key}' names the removed option catalog (enumRef '${String(De)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(C.enumOptions??[]).forEach((Ee,hn)=>{let Qe=Zq(Ee);Qe!==null&&r.push({severity:"error",path:`${z}.enumOptions[${hn}]`,code:"config.enum-option-value",message:{de:Qe==="empty"?`Feld '${C.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 '${C.key}' hat den Enum-Optionswert '${Ee}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Qe==="empty"?`Field '${C.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 '${C.key}' has the enum option value '${Ee}', which the single select reserves for its clear row. Rename the option.`}})}),(C.attachments??[]).forEach((Ee,hn)=>{if("storageId"in Ee){r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.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 '${C.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!=="",En=Ee.url!==void 0&&Ee.url!=="";Qe===En&&r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Qe&&En?"beide":"keines"}).`,en:`Field '${C.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Qe&&En?"both":"neither"}).`}}),Ee.renderAs==="inlineLink"&&Ee.label===void 0&&r.push({severity:"error",path:`${z}.attachments[${hn}]`,code:"config.attachment-inline-link-label",message:{de:`inlineLink-Anhang des Felds '${C.key}' braucht ein 'label' \u2014 die verlinkte Wendung im Feldlabel.`,en:`Field '${C.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`}})})},"considerField");I.fields.forEach((C,z)=>j(C,`${O}.fields[${z}]`)),I.groups?.forEach((C,z)=>{C.fields.forEach((le,ce)=>j(le,`${O}.groups[${z}].fields[${ce}]`))}),I.repeated?.forEach((C,z)=>{C.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((C,z)=>T(C,`${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(...rK(I,e.effects,`effects[${O}]`,j=>l.has(j)));return}I.kind==="organization"&&I.nameFrom?.forEach((j,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nameFrom[${C}]`,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}Jq(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.`}}),Qq(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 P=new Set,L=s(I=>{I.kind==="person"?P.add(I.bucket):I.kind==="organization"&&P.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(C=>L(C))),v(O.subsections??[])},"collectRepeatedBuckets");v(e.sections);let N=s((I,O)=>{P.size!==0&&I.forEach((j,C)=>{j.bucket===void 0||P.has(j.bucket)||r.push({severity:"error",path:`${O}[${C}].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(".")}]`;N(I.fields,`${j}.fields`),I.groups?.forEach((C,z)=>N(C.fields,`${j}.groups[${z}].fields`)),I.repeated?.forEach((C,z)=>N(C.itemTemplate,`${j}.repeated[${z}].itemTemplate`)),I.subsections?.forEach((C,z)=>A(C,[...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,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${O}].nationalityFrom[${C}]`,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:C})=>{let z=I.get(j.bucket);if(z===void 0){I.set(j.bucket,j.id);return}r.push({severity:"error",path:`effects[${C}].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:C})=>{r.push({severity:"error",path:`effects[${C}].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:C})=>{j.subject!==!0&&r.push({severity:"error",path:`effects[${C}].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:C})=>{let z=j.contractParty?.role;z!==void 0&&z!=="beneficiary"&&r.push({severity:"error",path:`effects[${C}].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,C)=>{a.has(j.from)||r.push({severity:"error",path:`effects[${O}].mappings[${C}].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`,C=u.get(O.sameAs.source);C===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).`}}):C.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 (${C.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${I}' (${O.type}) sameAs.source '${O.sameAs.source}' has a different type (${C.type}) \u2014 the mirror must be shape-identical.`}}):C.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 C=O.from.slice(1);e.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===C&&le.mappings.some(ce=>ce.to===O.field)||le.kind==="shareValue"&&le.id!==O.id&&le.to.slice(1)===C&&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(oi)&&r.push({severity:"error",path:`effects[${O}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': bucket '${I.bucket}' darf '${oi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' bucket '${I.bucket}' must not contain '${oi}' (reserved for the per-row namespace).`}}),I.kind==="organization"&&I.orgKind.includes(oi)&&r.push({severity:"error",path:`effects[${O}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${I.id}': orgKind '${I.orgKind}' darf '${oi}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${I.id}' orgKind '${I.orgKind}' must not contain '${oi}' (reserved for the per-row namespace).`}})});let oe=new Set;function Q(I,O){I.repeated?.forEach((j,C)=>{let z=j.effects??[];if(z.length>0){let le=`${O}.repeated[${C}]`,ce=new Set(z.map(se=>se.id)),De=new Set(j.itemTemplate.map(se=>se.key)),Ee=(j.uniqueBy?.length??0)>0,hn=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"),En=s(se=>{let Wn=se.slice(1);return ce.has(Wn)||h.has(Wn)},"resolvesRef");z.forEach((se,Wn)=>{let gn=`${le}.effects[${Wn}]`;if(h.has(se.id)||oe.has(se.id)?r.push({severity:"error",path:gn,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,gn),se.kind==="person"&&se.subject===!0&&r.push({severity:"error",path:`${gn}.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:`${gn}.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:`${gn}.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(oi)&&r.push({severity:"error",path:`${gn}.${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 '${oi}' nicht enthalten.`,en:`Repeated effect '${se.id}' ${se.kind==="person"?"bucket":"orgKind"} '${Fe}' must not contain '${oi}'.`}}),se.kind==="person"&&r.push(...rK(se,z,gn,hn)),se.kind==="organization"&&se.nameFrom?.forEach((Be,Lt)=>{hn(Be)||r.push({severity:"error",path:`${gn}.nameFrom[${Lt}]`,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,Lt)=>{Qe(Be)||r.push({severity:"error",path:`${gn}.identity.keyFrom[${Lt}]`,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])=>{En(Be)||r.push({severity:"error",path:`${gn}.${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("$")&&!En(Be)&&r.push({severity:"error",path:`${gn}.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"?(En(se.target)||r.push({severity:"error",path:`${gn}.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:`${gn}.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:gn,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,C)=>Q(j,`${O}.subsections[${C}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((I,O)=>Q(I,`sections[${O}]`));let re=Lq(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(...r9(e)),r}s(iK,"validateForm");function r9(e){let n={...e,effects:e.effects.map(oK),sections:e.sections.map(sK),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return ym(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:Kk(t)}))}s(r9,"missingTranslationIssues");function oK(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(oK,"withoutSubjectFlag");function sK(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(oK)})),subsections:e.subsections?.map(sK)}}s(sK,"withoutRowSubjectFlags");function Xq(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(Xq,"reviewRequiredShapeIssues");function eK(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(eK,"exportGateIssues");function Za(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${nK(r,"de")} '${n}'`,en:`Duplicate ${nK(r,"en")}: '${n}'`}}):e.add(n)}s(Za,"reportIfDup");function nK(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(nK,"labelForCode");function dS(e,n,t,r,i,o){e.visibleIf&&(Pr(e.visibleIf,`${n}.visibleIf`,t,r,o),Xa(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(Pr(e.requiredIf,`${n}.requiredIf`,t,r,o),Xa(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(Pr(e.disabledIf,`${n}.disabledIf`,t,r,o),Xa(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&Pr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s(dS,"checkFieldAsts");function cS(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(cS,"gatingMeta");function Xa(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(tK(o.left,o.right,o.op,n,t,r),tK(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(Xa,"checkGatingExpr");function tK(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(tK,"inspectEqualityOperand");function Pr(e,n,t,r,i){i.push(...bC(e,t.declaredContext,n)),i.push(...pm(e,t.stageKeys,n));for(let o of Ln(e))t.known.has(o)||Fk(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(Pr,"checkAst");function rK(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=zq(e.id,n);Yq(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 Wq(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(rK,"personNameIssues");function i9(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(i9,"consentConfigIssues");function o9(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(o9,"exclusiveOptionIssues");var s9="blocked";function aK(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=kn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(a9(i))return r.id===s9?null:r.id}return null}s(aK,"resolveActiveOutcome");function a9(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(a9,"truthy");function lK(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(lK,"isScalar");function l9(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(lK(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))lK(a)&&(n[`${r}.${o}`]=a)}d9(e,n,t)}s(l9,"mergeRecord");function d9(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);fo(a).test(i)&&r.add(a)}for(let i of r){let o=sS(e,i),a=0;for(let l=0;l<o;l++)qq(e,i,l)&&a++;n[`${i}.count`]=a}}s(d9,"mergeRepeatedCounts");function dK(e,n,t){let r={...t};return l9(e,r,n),r}s(dK,"flattenValues");function uS(e,n,t){return{code:e,fieldKey:n,text:t}}s(uS,"submitIssue");function cK(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(cK,"truthyEval");function uK(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(uK,"isEmptyValue");function c9(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=cK(kn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(c9,"fieldIsLiveRequired");function u9(e,n,t){return fK(e,n,t).evalCtx}s(u9,"buildSubmitEvalContext");function fK(e,n,t){let r=f9(e),i=Object.keys(n).filter(l=>r(l)!==null),o=new Set(i),a=new Set;for(;;){let l={};for(let[y,k]of Object.entries(n))(r(y)===null||o.has(y))&&(l[y]=k);let d=pK(e,l,t),c=new Set,u=new Set;hK(e,d,y=>c.add(y.key),y=>u.add(y.key));let p=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(p.size===o.size&&[...p].every(y=>o.has(y))){let y={};for(let k of i)o.has(k)||(y[k]=n[k]);return{visible:l,hidden:y,evalCtx:d}}let h=[...p].sort().join("\0");if(a.has(h)){let y=i.filter(k=>p.has(k)!==o.has(k));F(`[smartForm] visibility of ${y.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(fK,"splitWithContext");function f9(e){let n=new Map,t=[];for(let r of Gh(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:fo(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(f9,"fieldOwnership");function pK(e,n,t){let r=[];for(let o of Gh(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=dK(n,r,t);for(let o of Gh(e.sections))for(let a of o.computed??[])try{i[a.key]=kn(a.expression,{values:i})}catch{}return i}s(pK,"rawEvalContext");function mK(e,n,t){let{values:r,defaulted:i}=p9(e,n,t),o=fK(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(mK,"splitDraftValues");function p9(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of Gh(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??=pK(e,n,t);let c;try{c=kn(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(p9,"applyFieldDefaults");function Gh(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(Gh,"walkSectionsDeep");function m9(e,n,t,r=!1){if(uK(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(m9,"fieldFormatIssue");function h9(e,n){return uK(n)||e.type==="consent"&&n!==!0}s(h9,"isUnanswered");function Uh(e,n){if(!e)return!0;try{return cK(kn(e,{values:n}))}catch{return!1}}s(Uh,"isVisibleUnder");function hK(e,n,t,r){let i=s(o=>{if(Uh(o.visibleIf,n)){for(let a of o.fields)Uh(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(Uh(a.visibleIf,n))for(let l of a.fields)Uh(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(hK,"forEachVisibleField");function gK(e,n,t,r={}){let i=u9(e,n,t),o=[],a=aK(e,i);a===null&&r.requireOutcome!==!1&&o.push(uS("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 hK(e,i,d=>{let c=n[d.key];if(h9(d,c)){!l.has(d.type)&&c9(d,i,a)&&o.push(uS("required",d.key,Ul([d.label],([p],h)=>h==="de"?`${p} ist ein Pflichtfeld.`:`${p} is a required field.`)));return}if(!r.registry)return;let u=m9(d,c,r.registry,r.testMode===!0);u!==null&&o.push(uS("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(gK,"checkSubmittable");function yK(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=Ta(e),r=[];for(let i of n){let o=i.prefill??{};if(!hC(e,i.env))continue;let a=yC(e,i.env),{visible:l}=mK(t,o,a),d=gK(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:Ul([i.label,c.text],([u,p],h)=>h==="de"?`Szenario "${u}": ${p}`:`Scenario "${u}": ${p}`)})}}return r}s(yK,"validateScenarios");function zh(e){return e.filter(n=>(n.severity??"error")==="error")}s(zh,"blockingIssues");function Wh(e,n={}){return[...iK(e,n),...yK(e)]}s(Wh,"runFormValidators");function Yh(e){return zh(e)}s(Yh,"blockingFormErrors");function wK(e,n,t){return PD(e,n,t)}s(wK,"runWorkflowValidators");function kK(e){return zh(e)}s(kK,"blockingWorkflowErrors");var g9=["actionTeams","artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"];var bK={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"]}},xt={id:m.string(),label:so,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())},y9=m.object({...xt,type:m.literal("join")}),w9=m.object({...xt,type:m.literal("end")}),k9=m.object({...xt,type:m.literal("eventTrigger")}),b9=m.object({...xt,type:m.literal("form"),adoptForm:m.optional(m.any()),formExports:m.optional(m.any())}),v9=m.object({...xt,type:m.literal("roleAssign")}),x9=m.object({...xt,type:m.literal("setFlag")}),S9=m.object({...xt,type:m.literal("if"),condition:m.optional(m.any())}),A9=m.object({...xt,type:m.literal("countersign"),contract:m.optional(m.any()),signing:m.optional(m.any()),titles:m.optional(m.any())}),E9=m.object({...xt,type:m.literal("engagePush"),contract:m.optional(m.any()),engage:m.optional(m.any()),form:m.optional(m.any()),payment:m.optional(m.any())}),T9=m.object({...xt,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())}),$9=m.object({...xt,type:m.literal("review"),commentRequired:m.optional(m.any()),decisionAsTask:m.optional(m.any()),form:m.optional(m.any())}),R9=m.object({...xt,type:m.literal("waitlist")}),I9=m.object({...xt,type:m.literal("completenessCheck"),deadline:m.optional(m.any()),requires:m.optional(m.any())}),O9=m.object({...xt,type:m.literal("collectPayment")}),_9=m.object({...xt,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())}),xKe=m.union(y9,w9,k9,b9,v9,x9,S9,A9,E9,T9,$9,R9,I9,O9,_9);function vK(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 bK)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=bK[a],d=new Set(["id","type","label",...g9,...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(vK,"workflowNodeEnvelopeIssues");var xK=s(e=>e,"asEffectId"),po=s(e=>e,"asOutcomeId"),el=s(e=>e,"asSectionId"),ut=s(e=>e,"asFieldKey");var Nr=["string","boolean","consent","date","enum","email","tel","address","docRef"],gc=["person","organization","relationship","fieldMap"],mo=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],nl=["fresh","keyed","manual"];function hs(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(hs,"optionalLocalizedText");function tt(e,n){if(!(e===void 0||e===""))try{Fn(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(tt,"assertExpression");function yc(e){return Object.keys(e.smartforms??{})}s(yc,"carriedFormSlugs");function fS(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(fS,"boundFormSlugs");function Hh(e,n){let t=yc(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(Hh,"resolveFormSlug");function Jh(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(Jh,"getForm");function Ht(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(Ht,"walkSections");function fr(e,n){return Ht(e).find(t=>t.id===n)}s(fr,"findSection");function gs(e,n){for(let t of Ht(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(gs,"findField");function ys(e){let n=new Set;for(let t of Ht(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(ys,"allFieldKeys");function P9(e){let n=dn(e.label,e.labelEn,"offer form add"),t={id:el("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:po("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(P9,"buildSkeletonSmartForm");function Qh(e,n){let{key:t,label:r}=n;if(yc(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=P9({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(Qh,"addForm");function SK(e,n){if(!yc(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(fS(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(SK,"removeForm");function AK(e,n){let t=Jh(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");vn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(AK,"setForm");function EK(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(EK,"nodesOf");function TK(e,n,t){let r=EK(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(TK,"nodeOf");function $K(e){return e.flatMap(n=>{if(n.type!=="form"||It(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s($K,"creatingFormNodes");function RK(e){return Yh(Wh(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(RK,"formErrors");function Zh(e){let n="offer workflow restamp-exports",t=EK(e,n),r=[];for(let{node:i,slug:o}of $K(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=RK(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
11438
11438
  ${d.join(`
11439
11439
  `)}`);let c=sk(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"&&It(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(Zh,"restampFormExports");function IK(e){let n=e.workflow?.graph?.nodes??[];return $K(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 RK(o).length>0?[]:Pe(t.formExports)===Pe(sk(o))?[]:[{node:t.id,form:r}]})}s(IK,"staleFormExports");var pS=["string","number","boolean","date"];function OK(e,n){let t="offer form field export";for(let r of Ht(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&&!Vp(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 (${pS.join("|")}); an expression has none to infer`);if(!pS.includes(d))throw new Error(`${t}: --type "${d}" is no computed export type (${pS.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(OK,"setFieldExport");function _K(e,n,t){let r="offer workflow node set-generator",i=TK(e,n,r);if(qh(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=pi(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??{},[Qn]:{kind:"literal",value:{kind:t.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(p=>p!==Qn&&p!==Vt);return{before:l,after:{key:a,kind:t.kind},droppedStamp:c,keptParameterCells:u}}s(_K,"setGeneratorPin");function PK(e,n,t){let r="offer workflow node set-cockpit-fields",i=TK(e,n,r),o=qh(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"?pi(i)!==null:Ar(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(PK,"setCockpitFields");var N9=new Set(["graph","progressLayout","progressWiring"]);function NK(e){let{label:n,...t}=e;return t}s(NK,"definitionOf");function C9(e){let n=[];for(let o of Object.keys(e))N9.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(GO.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(...vK(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(C9,"workflowShapeIssues");function CK(e){let n=e.nodes??[],t=new Map;for(let r of n){let i=C_(r);i!==void 0&&t.set(r.id,i)}return t}s(CK,"formNodeSlugById");function D9(e,n){let t=e.smartforms??{},r=new Map;for(let[i,o]of CK(n)){let a=t[o];if(a===void 0)return;r.set(i,NK(a))}return $C(r)}s(D9,"readinessContext");function F9(e){return[...CK(e).values()]}s(F9,"formNodeSlugs");function Xh(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(Xh,"describe");function Dt(e){let n=[];for(let l of hp(e.manifest))n.push({severity:"error",area:"manifest",message:l});let t=Dn(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 np(e.index.program?.stages??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of ep(e.index.program?.runs??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of vh(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 C9(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 UO(d))n.push({severity:"error",area:"workflow",message:E});let u=[];for(let{node:E,key:T,kind:R}of Kh(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 ${Ar(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 IK(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={...D9(e,l),...p===void 0?{}:{stageKeys:new Set(p)}},y=s(E=>{let T=wK(E,{layout:d,wiring:c},h),R=new Set(kK(T));return{issues:T,isError:s(P=>R.has(P)||(P.severity??"error")==="error","isError")}},"blockingOf"),{issues:k,isError:w}=y(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=y(E),R=new Set(T.issues.filter(T.isError).map(Xh)),P=s(L=>u.some(_=>L.includes(`$node.${_}.contract`)),"namesOutput");for(let L of k){let _=Xh(L);w(L)&&!R.has(_)&&P(_)&&b.add(_)}}for(let E of k){let T=Xh(E);if(b.has(T)){n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${T}`});continue}n.push({severity:w(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=Dn(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=NK(d);for(let k of zO(u,`smartforms/${l}.json`))n.push({severity:"error",area:"smartform",message:k.de});let p=u,h=Wh(p,{stageKeys:a}),y=new Set(Yh(h));for(let k of h)n.push({severity:y.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${Xh(k)}`});for(let k of[...Fq(p),...Dq(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(F9(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(Dt,"validateBundle");async function mS(e,n,t){let r=Kh(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 y=a.get(`${p}:${u}:${h??"current"}`);if(y===void 0)throw new Error(`offer: the environment answered no stamp for ${p}:${u}`);if(y.stamp===null){if(y.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}": ${y.refusal.de}`});continue}BO(c,structuredClone(y.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:y.stamp.parts===void 0?`${p}:${u} Dokument`:`${p}:${u} kombiniert (${y.stamp.parts.map(k=>k.partKey).join(", ")})`})}return{rows:l,issues:d}}s(mS,"stampResolverPins");async function hS(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=Ar(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=Ar(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(RM(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(hS,"stampTemplatePins");async function DK(e,n,t){let r=qe(t),i=await mS(e,n,r),o=await hS(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");Nt(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=Dt(r).filter(p=>p.severity==="error"&&c(p.message));return{rows:a,refused:[],open:u}}s(DK,"restampPinsOnDisk");var L9=Y.join("contract","resolver-setup.json"),Ri="resolver setup",tl=s((e,n)=>jn(e,n,Ri),"record"),ho=s((e,n)=>Ge(e,n,Ri),"text");function M9(e,n){let t=tl(e,"Datei"),r=tl(t.contractTemplate,"contractTemplate"),i=tl(t.resolver,"resolver");return{dir:n,contractTemplate:{key:ho(r.key,"contractTemplate.key"),name:vt(r.name,"contractTemplate.name",Ri,"Vorlagennamen"),file:ho(r.file,"contractTemplate.file"),role:ho(r.role,"contractTemplate.role")},revenueAccounts:Gm(t.revenueAccounts,Ri),billingItems:zm(t.billingItems,Ri),resolver:{key:ho(i.key,"resolver.key"),name:vt(i.name,"resolver.name",Ri,"Generatornamen"),description:i.description===void 0?null:vt(i.description,"resolver.description",Ri,"Beschreibungen"),legalText:i.legalText??{},source:ho(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Bt(i.feeGroups,"resolver.feeGroups",Ri)).map((o,a)=>{let l=tl(o,`resolver.feeGroups[${a}]`);return{key:ho(l.key,"feeGroup.key"),name:vt(l.name,"feeGroup.name",Ri,"Geb\xFChrengruppen"),billingItemKeys:gS(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:gS(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:gS(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:q9(i.scenarios??[]),config:tl(i.config,"resolver.config")}}}s(M9,"parseResolverSetup");function gS(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(gS,"stringList");function q9(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=tl(n,"scenario");if(!("input"in t)||!("expected"in t))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:ho(t.key,"scenario.key"),input:t.input,expected:t.expected}})}s(q9,"parseScenarios");function eg(e){let n=Y.resolve(e);return M9(JSON.parse(he(n,"utf8")),Y.dirname(n))}s(eg,"readResolverSetup");function K9(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(K9,"configValue");function FK(e){let n=s(()=>ho(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),t=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...yS(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"?K9(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(FK,"billingSetupPayload");function LK(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(LK,"billingItemRef");function yS(e){if(Array.isArray(e))return e.flatMap(yS);if(typeof e!="object"||e===null)return[];let n=LK(e);return n!==void 0?[n]:Object.values(e).flatMap(yS)}s(yS,"billingItemRefs");function wS(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=LK(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(wS,"renderResolverConfig");function j9(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(j9,"assertPlaceholderParity");function V9(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(V9,"matchingSealedRevision");async function wc(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 Id(Y.join(t.dir,t.contractTemplate.file));j9(t.resolver.config,i);let o=await e.query(x.contractSetup.planBillingSetup,{client:n,...FK(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(P=>P.configKey===T);if(R===void 0)throw new Error(`Unknown grant template ${T}`);c[T]=R.id}let u=wS(t.resolver.config,o.billingItemIds,c),h=(await e.query(x.contractGeneratorVersions.model,{client:n})).find(T=>T.definition.key===t.resolver.key),y=h?.currentRevisionId?await e.query(x.contractGeneratorVersions.detail,{client:n,id:h.currentRevisionId}):null,k=h?.revisions.find(T=>T.status==="draft"),w=k?await e.query(x.contractGeneratorVersions.detail,{client:n,id:k.id}):null,b=l||y===null?void 0:V9([y],{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:y,draft:w,match:b,template:{documentTemplateId:a?.id??null,upload:l}}}s(wc,"planResolverSetup");async function MK(e,n,t){let r=await wc(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,...FK(t)});if(r.match)return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}};let o=r.template.upload?await Um(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:wS(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(`
11440
11440
  `));if(d=c.sourceRevision,await e.mutation(x.contractGeneratorVersions.approveScenarios,{client:n,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:wS({scenarios:t.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(x.contractGeneratorVersions.seal,{client:n,id:a,expectedSourceRevision:d}),(await wc(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(MK,"applyResolverSetup");async function kS(e,n,t){let r=Y.join(t.dir,L9);if(!Ae(r)||t.workflow===void 0)return[];let i=eg(r);if((await wc(e,n,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(kS,"pinSetupRevisions");function B9(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(B9,"nodeText");function kc(e,n){let t=[],r=[],i=[],o={},a=n.progressEvents??[],l=B9(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,y=u.tone,k={id:c,label:h,tone:y,external:u.external};u.terminal&&(k.terminal=!0),t.push(k),r.push({match:{nodeId:e.id},event:d,bus:"process",state:c});let w=u.phase,b=U9(w,e.id),E=i.find(T=>T.id===b);if(E)E.states=[...E.states,c];else{let T={id:b,label:p?h:w.label,tone:y,states:[c]};w.track&&(T.track=w.track),w.defaultCollapsed&&(T.defaultCollapsed=!0),w.waitlist&&(T.waitlist=!0),i.push(T)}u.terminal&&(o[c]=u.terminal)}return{states:t,mappings:r,columns:i,terminalSemantics:o}}s(kc,"deriveProgressEntriesForNode");function ng(e){return Object.entries(e).filter(([,n])=>n.outcome==="approved").map(([n])=>n)}s(ng,"seatedTerminalStates");function U9(e,n){return e.scope==="global"?`col.${e.key}`:`${n}.${e.key}`}s(U9,"columnIdFor");function qK(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(qK,"orderProcessColumns");var pr=s((e,n)=>({de:e,en:n}),"lt"),vS=Gs("start",[]),tg=Gs("form",[vS]),bS=Gs("end",[vS,tg]);function G9(e){let n=[kc({id:tg,type:"form",label:pr("Formular","Form")},ms.form),kc({id:bS,type:"end",label:pr("Ende","End")},ms.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=ng(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:t,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:pr("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(G9,"buildStarterProgress");function KK(e){let{slug:n,title:t,tenant:r,unit:i,responsible:o}=e,a=n,l=`${n}-form`,d=`${n}-flow`,c=[{id:vS,type:"eventTrigger",label:pr("Start","Start"),sublabel:pr("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:tg}}},{id:tg,type:"form",label:t,sublabel:pr("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:pr("Standard","Standard")}],next:{standard:{to:bS}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:bS,type:"end",label:pr("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:iC(sC([{slot:"responsible",rules:[{when:ro,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],cm({nodes:c})))},{layout:p,wiring:h}=G9(d),y={id:el("section.applicant"),label:pr("Antragsteller","Applicant"),fields:[{key:ut("applicant.vorname"),label:pr("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:ut("applicant.nachname"),label:pr("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:po("standard"),label:pr("Standard","Standard"),when:"true",output:{fields:[{path:ut("applicant.vorname")},{path:ut("applicant.nachname")}],includeForm:!0}}],w={sections:[y],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,...w}},workflow:{graph:u,progressLayout:p,progressWiring:h}}}s(KK,"buildSkeletonBundle");var ws={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function Vn(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(Vn,"findOfferHandle");function ft(e,n,t){return e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0})}s(ft,"loadConfig");function xS(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(xS,"resolveUnitId");function rl(e,n){let t=jK(e),r=e.runs.find(i=>i.key===nr(t,n));if(!r)throw new We(`offer: run "${n}" not found. Available keys: ${e.runs.map(i=>uO(t,i.key)).join(", ")||"(none)"}`);return r.runId}s(rl,"resolveRunId");function il(e,n){let t=jK(e),r=e.stages.find(i=>i.key===Us(t,n));if(!r)throw new We(`offer: level "${n}" not found. Available keys: ${e.stages.map(i=>Yr(t,i.key)).join(", ")||"(none)"}`);return r.stageId}s(il,"resolveStageId");function jK(e){if(e.programKey===null)throw new We("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(jK,"requireProgramKey");async function SS(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(SS,"linkUnit");function ks(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(ks,"parsePositiveInt");var ol=s((e="Offer slug (required)")=>f.String("--offer",{description:e}),"offerOption"),AS=s(()=>f.String("--slug",{hidden:!0}),"retiredSlugOption");function ES(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new xn(`--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 xn("Missing --offer <slug>.");return e.offer}s(ES,"requireOffer");var tn=class extends D{static{s(this,"OfferCommand")}offer=ol();retiredSlug=AS();#e;get offerSlug(){return this.#e??=ES(this),this.#e}};var bc=class extends tn{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=ol("Manifest slug to export (required)");out=f.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=bn();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=xb(this.out,this.force),t=await this.caller(),r=this.requireTenant(t),{bundle:i,generation:o,revision:a}=await Aq(t,r,this.offerSlug,this.draft?"draft":"published");return Nt({...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}},vc=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=ol("New offer slug (identity key) (required)");retiredSlug=AS();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=bn();async execute(){let n=ES(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let t=xb(this.out??Y.join("offers",this.tenant,n),this.force),r=KK({slug:n,title:nt({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 Nt({...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}},xc=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=Dt(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}},Sc=class extends D{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 VK(t,n),a=await iS(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:ws[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:ws[d],target:`smartform:${l}`,detail:d})),{kind:ws[a.workflow],target:"workflow",detail:a.workflow},...BK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...UK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...GK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...zK(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},Ac=class extends D{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 kS(t,n.index.tenant,n),i=await iS(t,n);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:ws[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:ws[a],target:`smartform:${o}`,status:a})),{icon:ws[i.workflow],target:"workflow",status:i.workflow},...BK(i),...UK(i),...GK(i),...zK(i)]),0}};async function VK(e,n){let t=await kS(e,n.index.tenant,n),r=await mS(e,n.index.tenant,n),i=await hS(e,n.index.tenant,n);return{pins:t,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Dt(n)]}}s(VK,"validateOnEnvironment");function BK(e){return e.addresses===null?[]:vq(e.addresses)}s(BK,"addressRows");function UK(e){let n={insert:"+",update:"~",archive:"-"};return e.stages.map(t=>({icon:n[t.op],target:`stage:${t.key}`,status:rp(t)}))}s(UK,"stageRows");function GK(e){return e.capacities.map(n=>({icon:"~",target:`cap:${n.run}\xD7${n.stageKey}`,status:xh(n)}))}s(GK,"capacityRows");function zK(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(zK,"publishPendingRows");var Ec=class extends D{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 VK(t,n);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
@@ -11617,6 +11617,6 @@ ${t.length} unusable ${o}:
11617
11617
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
11618
11618
  `),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>
11619
11619
  `)}else this.context.stdout.write(`No unusable identities.
11620
- `);return t.length>0?1:0}},m$=class extends wr{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 $U(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s($U,"requireOnOff");var RU=[QT,ZT,XT,e$,n$,t$,r$,i$,o$,s$,Ku,a$,l$,d$,c$,u$,f$,p$,m$];function IU(e){return e.de??e.en??Object.values(e)[0]??""}s(IU,"titleDe");function hee(e){return{id:e._id,kind:e.kind,status:e.status,title:IU(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(hee,"row");var gee=["id","kind","status","title","assignee","group","outcome"],y$=class extends D{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(hee),gee),0}},w$=class extends D{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:IU(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}},k$=class extends D{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}},b$=class extends D{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}},v$=class extends D{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}},OU=[y$,w$,k$,b$,v$];var ju=[...lO,...VF,...QF,...XL,...ZL,...E0,...P0,..._0,...EU,...RU,...AU,...dB,...hB,...TF,...v0,...fU,...sO,...qO,...uF,...D0,...C0,...M0,...q0,...k0,...o0,...OU,...nj,...Uj,...aB,...Gj,...HB,...rU,...gB,...EB,...RB,...PB,...CB,...sU,...yU,...IO];for(let e of ju){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:xR(e.usage.category,n.join(" "))})}var _U="0.1.232";function PU(){return ju.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=wR[To(t)];return{path:t,effect:$o(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(PU,"plexusCommandCatalog");import Ss from"node:path";function yee(e){let n=cn()?.workspaceRoot??process.cwd(),t=Ss.resolve(n,e),r=Ss.relative(n,t);if(Ss.isAbsolute(e)||r===".."||r.startsWith(`..${Ss.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(yee,"workspacePath");function wee(e){let{absolute:n,relative:t}=yee(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Mr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Ss.join(o,a.name);if(a.isDirectory()?i(l):r.push(Ss.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 Bn(Ss.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return $s(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(wee,"plexusWorkspace");function NU(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=Bl[t];if(!o||!Object.hasOwn(Bl,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(rw,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:rw[i.path],skillHash:Zf}}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 wee(i)},"executePlexusAgentTool")}s(NU,"createPlexusAgentToolExecutor");var Kg=NU({inspectCommand:DU,executeCommand:FU});function jg(){let e=new _s({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:_U});e.register(Al.HelpCommand),e.register(Al.VersionCommand);for(let t of ju)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 vee(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(jg,"createPlexusCli");function vee(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&Rl[t]===r&&ln(n,t,r),t in Rl&&$o(t)==="confirm"&&!Il(e)&&n.write(`plexus-cli: \`${Rl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11620
+ `);return t.length>0?1:0}},m$=class extends wr{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 $U(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s($U,"requireOnOff");var RU=[QT,ZT,XT,e$,n$,t$,r$,i$,o$,s$,Ku,a$,l$,d$,c$,u$,f$,p$,m$];function IU(e){return e.de??e.en??Object.values(e)[0]??""}s(IU,"titleDe");function hee(e){return{id:e._id,kind:e.kind,status:e.status,title:IU(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(hee,"row");var gee=["id","kind","status","title","assignee","group","outcome"],y$=class extends D{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(hee),gee),0}},w$=class extends D{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:IU(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}},k$=class extends D{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}},b$=class extends D{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}},v$=class extends D{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}},OU=[y$,w$,k$,b$,v$];var ju=[...lO,...VF,...QF,...XL,...ZL,...E0,...P0,..._0,...EU,...RU,...AU,...dB,...hB,...TF,...v0,...fU,...sO,...qO,...uF,...D0,...C0,...M0,...q0,...k0,...o0,...OU,...nj,...Uj,...aB,...Gj,...HB,...rU,...gB,...EB,...RB,...PB,...CB,...sU,...yU,...IO];for(let e of ju){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:xR(e.usage.category,n.join(" "))})}var _U="0.1.234";function PU(){return ju.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=wR[To(t)];return{path:t,effect:$o(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(PU,"plexusCommandCatalog");import Ss from"node:path";function yee(e){let n=cn()?.workspaceRoot??process.cwd(),t=Ss.resolve(n,e),r=Ss.relative(n,t);if(Ss.isAbsolute(e)||r===".."||r.startsWith(`..${Ss.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(yee,"workspacePath");function wee(e){let{absolute:n,relative:t}=yee(e.path??".");if(e.operation==="list"){if(!Ae(n))return{files:[]};let r=[],i=s(o=>{for(let a of Mr(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Ss.join(o,a.name);if(a.isDirectory()?i(l):r.push(Ss.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 Bn(Ss.dirname(n),{recursive:!0}),ze(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return $s(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(wee,"plexusWorkspace");function NU(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=Bl[t];if(!o||!Object.hasOwn(Bl,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(rw,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:rw[i.path],skillHash:Zf}}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 wee(i)},"executePlexusAgentTool")}s(NU,"createPlexusAgentToolExecutor");var Kg=NU({inspectCommand:DU,executeCommand:FU});function jg(){let e=new _s({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:_U});e.register(Al.HelpCommand),e.register(Al.VersionCommand);for(let t of ju)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 vee(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(jg,"createPlexusCli");function vee(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&Rl[t]===r&&ln(n,t,r),t in Rl&&$o(t)==="confirm"&&!Il(e)&&n.write(`plexus-cli: \`${Rl[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
11621
11621
  `)}s(vee,"noteRetiredPath");function DU(e){let n=jg().process(hl(e),{executePlexusAgentTool:Kg}),t=n.path.join(" ");if(t.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=PU().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"?mh(Wa(Ya),i.fn??"",i.kind):void 0,a=xf(t,{confirm:Il(n),callKind:o});return{...r,writes:a}}s(DU,"inspectPlexusCommand");async function FU(e,n){if(n)return S$(n,()=>FU(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=jg();if(cn()){let l=DU(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(hl(e.argv),{executePlexusAgentTool:Kg,stdin:bee.from(e.stdin===void 0?[]:[e.stdin]),stdout:new CU({write(l,d,c){t+=String(l),c()}}),stderr:new CU({write(l,d,c){r+=String(l),c()}})}),stdout:t,stderr:r}}s(FU,"executePlexusCommand");R$({source:xee.join(import.meta.dirname,"skill")});jg().runExit(hl(process.argv.slice(2)),{executePlexusAgentTool:Kg});
11622
11622
  //# sourceMappingURL=cli.mjs.map