@smartkomm/plexus-cli 0.1.105 → 0.1.106

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
@@ -8938,8 +8938,13 @@ plexus-cli --env <env> platform storage orphans plan # orphaned: 0 (or only w
8938
8938
  - The plan reads every row that can carry a file reference in free text; on a
8939
8939
  large deployment it takes minutes (prod, Nov 2026: \u2248 275 s) \u2014 the command
8940
8940
  waits on the run, not on one HTTP call.
8941
- - A run's result file and record stay; the sweep counts the file as held by its
8942
- run, never as an orphan.
8941
+ - A run stays retrievable (\`status <runId>\`, its result file, the ids an apply
8942
+ deleted) for **30 days** after its start. Then a daily job deletes a run that
8943
+ is \`done\` or \`failed\`, with its result file and its list of deleted ids; a
8944
+ run still \`queued\` or \`running\` is never deleted. Keep what you need longer
8945
+ with \`status <runId> --out\` / \`--json\`.
8946
+ - Until then the sweep counts a run's result file as held by its run, never as
8947
+ an orphan.
8943
8948
  - The nightly report never deletes.
8944
8949
 
8945
8950
  ## Related
@@ -10494,7 +10499,7 @@ plexus-cli --env prod jobs list --status running # nothing unexpectedly in
10494
10499
  ## Related
10495
10500
  - Command reference: \`plexus-cli jobs list --help\`, \`plexus-cli platform workers reap --help\`,
10496
10501
  \`plexus-cli platform imports cleanup-orphaned --help\`.
10497
- `};var Wu="0d3bd9c6a4972f08555489de6088734aacbef8cfa1d126d86dc62967f0e287af",_g=uR;var Ng=class extends xe{static{s(this,"AgentToolsCommand")}static paths=[["agent","tools"]];static usage=T.Usage({category:"Agents",description:"Show the shared platform/CLI agent tool schemas and skill revision."});async execute(){return this.print({skillHash:Wu,tools:il}),0}},Cg=class extends xe{static{s(this,"AgentInvokeCommand")}static paths=[["agent","invoke"]];static usage=T.Usage({category:"Agents",description:"Invoke a shared agent tool; pipe its JSON input on stdin."});tool=p.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 Pg(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},fR=[Ng,Cg];var Dg=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],yse=new Set(Dg.map(e=>e.key));function mR(e,n,t,r){let i=e.flatMap(l=>l.angebote).find(l=>l.offerKey===n);if(i===void 0){let l=e.flatMap(d=>d.angebote.map(c=>c.offerKey));throw new Error(`applications start-test: no offer "${n}" (offers: ${l.join(", ")||"none"})`)}let o=i.stages.find(l=>l.stageKey===r||l.stageId===r);if(o===void 0){let l=i.stages.map(d=>`${d.stageKey} (${d.stageId})`);throw new Error(`applications start-test: no level "${r}" in ${n} \u2014 name it by key or id: ${l.join(", ")}`)}let a=o.runs.find(l=>l.runKey===t||l.runId===t);if(a===void 0){let l=o.runs.map(d=>`${d.runKey} (${d.runId})`);throw new Error(`applications start-test: no school year "${t}" for level ${o.stageKey} \u2014 name it by key or id: ${l.join(", ")}`)}if(!a.isOpen)throw new Error(`applications start-test: school year ${a.runKey} is closed for level ${o.stageKey}`);return{programRunId:a.runId,programStageId:o.stageId}}s(mR,"resolveStartTarget");function sG(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(sG,"applicantText");function hR(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:sG(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(hR,"applicationRows");var pR=Dg.map(e=>e.email);function gR(e,n,t,r){if(t===void 0&&r===void 0)throw new Error("applications start-test: name the applicant \u2014 --party <partyId> or --applicant <email>");if(t!==void 0&&r!==void 0)throw new Error("applications start-test: --party or --applicant, not both");if(Rg(e,n)&&(r===void 0||!pR.includes(r.trim().toLowerCase())))throw new Error(`applications start-test: on prod only for the test account ${pR.join(", ")} (--applicant) \u2014 never a real family's`)}s(gR,"assertStartApplicant");function yR(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(yR,"processStoreJson");function aG(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.revisionNumber}`} \xB7 ${e.contractStatus}`;case"contracts":return e.contracts.map(n=>`${n.partKey}: contract ${n.contractId} \xB7 ${n.revision===null?"keine Fassung":`Fassung ${n.revision.revisionNumber}`} \xB7 ${n.contractStatus}`).join("; ")}}s(aG,"refText");function lG(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?aG(e.ref):JSON.stringify(e.value)}s(lG,"holds");function wR(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:lG(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(wR,"storeRows");function Yu(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(Yu,"parseKv");var kR="started",Hu="submitted",Ju="submitted",bR="load-scenario:";var vR="(Bewerbung)";function xR(e){return{nodeId:vR,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(xR,"sharedAsList");function SR(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(SR,"disabledText");function AR(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:SR(r)})))}s(AR,"actionRows");function ER(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: ${SR(a)}`);if(i!==vR)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(ER,"nodeOfferingAction");function TR(e,n,t){if(e.startsWith(bR)){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(TR,"runParams");async function dG(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(dG,"currentNodeIds");function cG(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(cG,"refusalText");async function Qu(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${cG(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,xR(r.actions)]}s(Qu,"actionsOf");async function $R(e,n,t){return t!==void 0?[t]:await dG(e,n)}s($R,"nodesOf");var Fg=class extends D{static{s(this,"TestActionsListCommand")}static paths=[["test-actions","list"]];static usage=T.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=p.String("--application",{required:!0,description:"Application id (a test application)"});node=p.String("--node",{description:"Node id (default: the application's current nodes)"});async execute(){let n=await this.caller(),t=await Qu(n,this.application,await $R(n,this.application,this.node));return this.print(t,AR,["node","action","label","disabled"]),0}},Lg=class extends D{static{s(this,"TestActionsRunCommand")}application=p.String("--application",{required:!0,description:"Application id (a test application)"});node=p.String("--node",{description:"Node id (default: the application's current nodes)"});static paths=[["test-actions","run"]];static usage=T.Usage({category:"Admission",description:"Run one test-mode action; a scenario (load-scenario:<id>) also submits unless --no-auto-submit"});action=p.String("--action",{required:!0,description:"Action id, e.g. load-scenario:standard, auto-fill-files, submit-form"});autoSubmit=p.Boolean("--auto-submit",!0,{description:"Scenario only: stub the file fields and submit after loading (default on; --no-auto-submit only loads)"});param=p.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=TR(this.action,this.autoSubmit,Yu(this.param??[]).values),t=await this.caller(),r=this.application,i=await $R(t,this.application,this.node),o=ER(await Qu(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}},RR=[Fg,Lg];var ze=["de","en"];function hs(e,n){return ze.every(t=>e[t]===n[t])}s(hs,"sameText");function Rn(e){if(e===null||typeof e!="object"||Array.isArray(e))return"not-localized";let n=e;return Object.keys(n).some(r=>!ze.includes(r))?"not-localized":ze.filter(r=>{let i=n[r];return typeof i!="string"||i.trim()===""})}s(Rn,"missingLocales");function Ti(e){let n=Rn(e);return n!=="not-localized"&&n.length===0}s(Ti,"isLocalizedText");function ol(e,n){let t={};for(let r of ze){let i=e.map(o=>o[r]);t[r]=i.every(o=>typeof o=="string"&&o.trim()!=="")?n(i,r):""}return t}s(ol,"composeTexts");var fr=/^[a-z][A-Za-z0-9]*$/;function Mg(e){return typeof e=="string"&&fr.test(e)}s(Mg,"isNodeId");function gs(e,n){Mg(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${fr.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 $i="$env";function se(e){if(e.scope==="env")return`${$i}.${e.key}`;let n=e.scope==="derived"?`$derived.${e.key}`:`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(se,"formatAddress");var Nr=/^[a-z][a-zA-Z0-9_]*$/,uG=/^[A-Za-z_][A-Za-z0-9_]*$/;function po(e){return typeof e=="string"&&e.split(".").every(n=>uG.test(n))}s(po,"isPath");function Qr(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&&po(i)?{scope:"env",key:i}:null}case"derived":{let[i,...o]=r;return i===void 0||!Nr.test(i)?null:IR({scope:"derived",key:i},o)}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Nr.test(o)||(t==="node"?!fr.test(i):!Nr.test(i))?null:IR({scope:t,owner:i,key:o},a)}default:return null}}s(Qr,"tryParseAddress");function IR(e,n){if(n.length===0)return e;let t=n.join(".");return po(t)?{...e,path:t}:null}s(IR,"withPath");function we(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=n.scope==="env"?["scope","key"]:n.scope==="derived"?["scope","key","path"]:["scope","owner","key","path"];if(Object.keys(n).some(r=>!t.includes(r))||n.path!==void 0&&!po(n.path))return!1;switch(n.scope){case"env":return po(n.key);case"derived":return typeof n.key=="string"&&Nr.test(n.key);case"node":return typeof n.owner=="string"&&fr.test(n.owner)&&typeof n.key=="string"&&Nr.test(n.key);case"task":return typeof n.owner=="string"&&Nr.test(n.owner)&&typeof n.key=="string"&&Nr.test(n.key);default:return!1}}s(we,"isAddress");var Zr={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"}},ys=Object.keys(Zr);function ws(e){return Object.hasOwn(Zr,e)}s(ws,"isEnvKey");var fG=["self-service","staff"];function OR(e,n){return{kind:"fixed",values:e,labels:n}}s(OR,"fixedSet");var Zu={of:"applicant.language",withoutValue:"de"},Xr={"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:Zu},"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:Zu},"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:Zu},"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:Zu},"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:OR(ze,{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:OR(fG,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},Xu={types:Zr,fields:Xr},ef=ys.flatMap(e=>Object.keys(Zr[e]).map(n=>`${e}.${n}`));function pr(e){return Object.hasOwn(Xr,e)}s(pr,"isEnvLeaf");function nf(e){return`${$i}.${e}`}s(nf,"envIdentifier");function mo(e){let n=Xr[e],[t,r]=e.split("."),i=Zr[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(mo,"envLeaf");var PR="staffInput";var pG=["boolean"],sl=/^[a-z][A-Za-z0-9]*$/;function tf(e){return e.staffInputs??[]}s(tf,"staffInputsOf");function rf(e){return`${PR}.${e}`}s(rf,"staffInputLeaf");function _R(e){return`${$i}.${rf(e)}`}s(_R,"staffInputIdentifier");function mG(e){let n=`${PR}.`;return e.startsWith(n)?e.slice(n.length):null}s(mG,"staffInputKeyOfLeaf");function al(e,n){let t=mG(n);return t===null?void 0:tf(e).find(r=>r.key===t)}s(al,"declaredStaffInput");function hG(e){return[...tf(e).map(n=>({leaf:rf(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...ef.map(n=>{let t=mo(n);return{leaf:n,type:t.type,label:t.label,valueSet:Xr[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(hG,"envLeavesFor");function NR(e){return hG(e).filter(n=>!n.cohortBound)}s(NR,"conditionEnvLeaves");function CR(e){let n={},t={};for(let{leaf:r,type:i,valueSet:o,nullable:a}of NR(e)){let[l="",d=""]=r.split(".");n[l]={...n[l]??{},[d]:i},t[r]={valueSet:o,nullable:a}}return{types:n,fields:t}}s(CR,"envConditionSchemaFor");function DR(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}"`};sl.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),pG.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=Rn(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(DR,"staffInputIssues");var Wg={required:!0,description:"Offer slug (its offerKey)"},qg=class extends D{static{s(this,"ApplicationsListCommand")}static paths=[["applications","list"]];static usage=T.Usage({category:"Admission",description:"List an offer's applications (id, status, board state, applicant, test)"});offer=p.String("--offer",Wg);testOnly=p.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=hR(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},Kg=class extends D{static{s(this,"ApplicationsCountsCommand")}static paths=[["applications","counts"]];static usage=T.Usage({category:"Admission",description:"Count an offer's applications per list"});offer=p.String("--offer",Wg);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}},jg=class extends D{static{s(this,"ApplicationsShowCommand")}static paths=[["applications","show"]];static usage=T.Usage({category:"Admission",description:"One application: status, test flag, offer, current workflow nodes"});application=p.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 Error(`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}},Bg=class extends D{static{s(this,"ApplicationsStoreCommand")}static paths=[["applications","store"]];static usage=T.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, $derived\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=p.String({required:!0});async execute(){let t=await(await this.caller()).query(x.processStoreView.get,{applicationId:this.application});return this.print(yR(t),()=>wR(t),["address","state","holds","producer","written"]),0}},Ug=class extends D{static{s(this,"ApplicationsStartTestCommand")}static paths=[["applications","start-test"]];static usage=T.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=p.String("--offer",Wg);run=p.String("--run",{required:!0,description:"School year: its key or id (never its name)"});stage=p.String("--stage",{required:!0,description:"Level: its key or id (never its name)"});party=p.String("--party",{description:"Applicant party id"});applicant=p.String("--applicant",{description:"Applicant account login address (e.g. the test account test@example.com)"});version=p.String("--version",{description:"Offer version id to test (default: the live generation)"});staffInput=p.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=p.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();gR(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=mR(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 Error(`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:LR(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 Qu(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}},Vg=class extends D{static{s(this,"ApplicationsDiscardTestCommand")}static paths=[["applications","discard-test"]];static usage=T.Usage({category:"Admission",description:"Discard a TEST application (the server refuses a real one)"});application=p.String({required:!0});async execute(){return await(await this.caller()).mutation(x.admission.discardTest,{applicationId:this.application}),this.print({discarded:this.application},t=>[{key:"discarded",value:t.discarded}]),0}},Gg=class extends D{static{s(this,"ApplicationsStaffInputListCommand")}static paths=[["applications","staff-input","list"]];static usage=T.Usage({category:"Admission",description:"An application's internal inputs (set at the start): value, and why one can no longer be corrected"});application=p.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}},zg=class extends D{static{s(this,"ApplicationsStaffInputSetCommand")}static paths=[["applications","staff-input","set"]];static usage=T.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=p.String({required:!0});input=p.String("--input",{required:!0,description:"key=true|false"});reason=p.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}]=LR([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}},FR=[qg,Kg,jg,Bg,Ug,Vg,Gg,zg];function LR(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!sl.test(t)||r!=="true"&&r!=="false"||i.length>0)throw new Error(`--staff-input "${n}": expected key=true or key=false`);return{key:t,value:r==="true"}})}s(LR,"parseStaffInputs");var Kn="contractGenerator",ho="documentTemplate";function ll(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(ll,"isGeneratorRef");function MR(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(MR,"literalOf");function ei(e){let n=MR(e,Kn);return ll(n)?n:null}s(ei,"generatorRefOfNode");function mr(e){let n=MR(e,ho);return typeof n=="string"&&n.length>0?n:null}s(mr,"documentTemplateKeyOfNode");function qR(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(qR,"generatorRefLabel");var gG=["formExports","generatorStamp"];function KR(e,n,t){let r=e.inputs?.[Kn];(r?.kind!=="literal"||!ll(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Kn} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Kn]={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}}}s(KR,"applyGeneratorStamp");var yG=["reads"];function ks(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 gG)delete r[i];for(let i of yG)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(ks,"comparableWorkflowGraph");var dl={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 of(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=dl[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(of,"manifestIssues");function wG(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(wG,"validateProgressLayoutExternalCopy");function jR(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"]:wG(e)}s(jR,"progressLayoutIssues");var BR=new Set(["nodes","assignmentRules","channels","processStore","pricingRules","staffInputs"]);var kG=new Set(["sections","effects","outcomes","testScenarios","env"]),sf={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 UR(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(kG.has(i))continue;let o=sf[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(UR,"smartFormDefinitionShapeIssues");var bt=["granted","rejected","waitlisted","other"];function Ri(e){return typeof e=="string"&&bt.includes(e)}s(Ri,"isOutcomeSemantic");var Yt=["arrival","manual"],VR={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function bG(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(bG,"literal");function Yg(e){let n=bG(e,"waitlistOrder");return Yt.includes(n)?{waitlistOrder:n}:null}s(Yg,"waitlistPolicyOrNull");var gn="responsible",Hg="team:";function af(e){return`${Hg}${e}`}s(af,"teamSlot");function lf(e){return e.startsWith(Hg)?e.slice(Hg.length):null}s(lf,"teamKeyOfSlot");function GR(e){return e.kind==="responsible"?gn:af(e.groupKey)}s(GR,"slotIdOf");function df(e){if(e===gn)return{kind:"responsible"};let n=lf(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(df,"slotOfId");var Jg="review",Qg="checkField",zR="reviewed",WR="reviewing",cf=["rejected","waitlisted"];function Zg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Zg,"isObject");var vG=new Set(["decision",Jg]),YR={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function Xg(e){return Object.hasOwn(YR,e)?YR[e]:void 0}s(Xg,"legacySemanticOfId");function xG(e){return e===Jg?bt.filter(n=>!cf.includes(n)):bt}s(xG,"allowedSemanticsFor");var SG="other";function HR(e){return Zg(e)&&vG.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(HR,"outcomesOf");function JR(e){return(e?.nodes??[]).some(n=>HR(n).some(t=>Zg(t)&&!("semantic"in t)))}s(JR,"needsOutcomeSemantics");function QR(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=HR(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),f=xG(u),m=!1,y=l.map(k=>{if(!Zg(k))return k;let g=String(k.id);if("semantic"in k)return Ri(k.semantic)||i.push({nodeId:c,outcomeId:g,value:String(k.semantic)}),k;let b=`${c}.${g}`,A=Object.hasOwn(n,b)?n[b]:void 0;if(A!==void 0)return f.includes(A)?(t.push({nodeId:c,outcomeId:g,semantic:A,source:"answer"}),m=!0,{...k,semantic:A}):(r.push({nodeId:c,nodeType:u,outcomeId:g,allowed:f,answer:A}),k);let $=Xg(g),O=$??SG;return f.includes(O)?(t.push({nodeId:c,outcomeId:g,semantic:O,source:$===void 0?"formerDefault":"legacyTable"}),m=!0,{...k,semantic:O}):(r.push({nodeId:c,nodeType:u,outcomeId:g,allowed:f}),k)});return m?{...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(QR,"addOutcomeSemantics");var hr="bewerbungOffen";function go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(go,"isObject");var ey=["event","effect"];function ZR(e){return go(e)&&e.type==="eventTrigger"}s(ZR,"isTrigger");function XR(e){let n=go(e.inputs)?e.inputs:{};return"outcomes"in e||ey.some(t=>t in e||t in n)}s(XR,"oldShape");function eI(e){return(e?.nodes??[]).some(n=>ZR(n)&&XR(n))}s(eI,"needsEventTriggerStartMove");function AG(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>go(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===hr))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(go(e.next)?e.next:{});if(!(i.length===1&&i[0]===hr))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=go(e.inputs)?{...e.inputs}:{};for(let l of ey){let d=o[l];if(go(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of ey)delete a[l],delete o[l];return go(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(AG,"moveNode");function nI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!ZR(i)||!XR(i))return i;let o=AG(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(nI,"moveEventTriggerStart");function cl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(cl,"isObject");var tI={waitlistOrder:"arrival"};function rI(e){return!cl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(cl(e.inputs)?e.inputs:{}))}s(rI,"lacksPolicy");function EG(e){return(e?.nodes??[]).some(rI)}s(EG,"needsWaitlistPolicyMove");function ny(e){return cl(e)&&Yt.includes(e.waitlistOrder)}s(ny,"isWaitlistPolicy");function TG(e){if(e===void 0)return{policy:tI,stated:!1};if(!cl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!Yt.includes(n)?"malformed":{policy:{waitlistOrder:n??tI.waitlistOrder},stated:n!==void 0}}s(TG,"policyOfSelection");function iI(e,n,t={}){let r=[],i=[];if(!EG(e))return{graph:e,moved:r,refused:i};let o=TG(n),a=e.nodes.map(l=>{if(!rI(l))return l;let d=l,c=String(d.id),u=cl(d.inputs)?{...d.inputs}:{},f=Object.hasOwn(t,c)?t[c]:void 0,m,y;if(f!==void 0)m=f,y="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;m=o.policy,y=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:m.waitlistOrder},r.push({nodeId:c,policy:m,source:y}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(iI,"moveWaitlistPolicyToInputs");function yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(yo,"isObject");var $G=[Kn,ho],RG=["inputSchema","parties","schemaDigest","parts"];function oI(e){return yo(e)&&e.type==="governedDocument"&&("resolver"in e||yo(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(oI,"oldShape");function sI(e){return(e?.nodes??[]).some(oI)}s(sI,"needsGeneratorInputMove");function IG(e){let n=yo(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!yo(i))return{unmoved:"resolverNotObject"};if(Kn 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((yo(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>yo(d)&&$G.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Kn]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(RG.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(yo(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(ho in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[ho]={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(IG,"moveNode");function aI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!oI(i))return i;let o=IG(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(aI,"moveGeneratorPinsToInputs");var lI=/^\d{4}-\d{2}-\d{2}$/;function gr(e,n){return{de:e,en:n}}s(gr,"issue");function wo(e){if(typeof e!="object"||e===null)return gr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:gr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return gr(`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?gr("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"||!lI.test(r)?gr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!lI.test(i)?gr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?gr("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)?gr("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))?gr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?gr("unbekannte Angaben","unknown details"):null:gr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(wo,"reductionShapeIssue");function Ii(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||wo(n.reduction)===null&&n.reduction.kind==="amount")}s(Ii,"isPricedItemValue");var bs=["freetext","recommendation","choice","pricedItem","record","reduction"],vs=[...bs,"appointment"];function cI(e){return typeof e=="string"&&vs.includes(e)}s(cI,"isTaskResultKind");function Oi(e){return typeof e=="string"&&bs.includes(e)}s(Oi,"isRecordedTaskResultKind");function xs(e){return Oi(e.kind)}s(xs,"isRecordedTaskResult");var uf=["number","boolean","enum"];function ty(e){return typeof e=="string"&&uf.includes(e)}s(ty,"isRecordFieldType");var ry=["form","siblingRank"];var ni={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 uI(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(uI,"isProseResult");function ff(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&ty(n.type)).map(n=>({key:n.writes,valueType:n.type,field:n})):OG(e)}s(ff,"draftResultStoreWrites");function OG(e){let n=ni[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(OG,"singleStoreWrite");var dI="team:";function Ss(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(dI)){let n=e.slice(dI.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(Ss,"parseTaskResultChat");var Ze={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]",reductionPrices:"[taskResult/reductionPrices]",pricesOnNonReduction:"[taskResult/pricesOnNonReduction]"};var PG=new Set(["if","else","in","true","false","null"]),_G=new Set(["==","!=","<=",">=","&&","||"]);function NG(e){return e>="0"&&e<="9"}s(NG,"isDigit");function CG(e){return/[a-zA-Z_$]/.test(e)}s(CG,"isIdentStart");function DG(e){return/[a-zA-Z0-9_.$]/.test(e)}s(DG,"isIdentCont");function FG(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
10502
+ `};var Wu="f33ef945c9d57411fb45cd87ceaa4be8125637493948b6277f49e033de264272",_g=uR;var Ng=class extends xe{static{s(this,"AgentToolsCommand")}static paths=[["agent","tools"]];static usage=T.Usage({category:"Agents",description:"Show the shared platform/CLI agent tool schemas and skill revision."});async execute(){return this.print({skillHash:Wu,tools:il}),0}},Cg=class extends xe{static{s(this,"AgentInvokeCommand")}static paths=[["agent","invoke"]];static usage=T.Usage({category:"Agents",description:"Invoke a shared agent tool; pipe its JSON input on stdin."});tool=p.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 Pg(this.context.stdin)),t=await this.context.executePlexusAgentTool(this.tool,n);return this.print(t),0}},fR=[Ng,Cg];var Dg=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],yse=new Set(Dg.map(e=>e.key));function mR(e,n,t,r){let i=e.flatMap(l=>l.angebote).find(l=>l.offerKey===n);if(i===void 0){let l=e.flatMap(d=>d.angebote.map(c=>c.offerKey));throw new Error(`applications start-test: no offer "${n}" (offers: ${l.join(", ")||"none"})`)}let o=i.stages.find(l=>l.stageKey===r||l.stageId===r);if(o===void 0){let l=i.stages.map(d=>`${d.stageKey} (${d.stageId})`);throw new Error(`applications start-test: no level "${r}" in ${n} \u2014 name it by key or id: ${l.join(", ")}`)}let a=o.runs.find(l=>l.runKey===t||l.runId===t);if(a===void 0){let l=o.runs.map(d=>`${d.runKey} (${d.runId})`);throw new Error(`applications start-test: no school year "${t}" for level ${o.stageKey} \u2014 name it by key or id: ${l.join(", ")}`)}if(!a.isOpen)throw new Error(`applications start-test: school year ${a.runKey} is closed for level ${o.stageKey}`);return{programRunId:a.runId,programStageId:o.stageId}}s(mR,"resolveStartTarget");function sG(e){return e.kind==="named"?e.name:`(${e.standIn??e.fallback})`}s(sG,"applicantText");function hR(e){return e.map(n=>({id:n.application._id,status:n.deletedAt?`${n.application.status} (gel\xF6scht)`:n.application.status,state:n.currentProcessStateId??"",applicant:sG(n.applicantName),test:n.application.testMode===!0?"test":""}))}s(hR,"applicationRows");var pR=Dg.map(e=>e.email);function gR(e,n,t,r){if(t===void 0&&r===void 0)throw new Error("applications start-test: name the applicant \u2014 --party <partyId> or --applicant <email>");if(t!==void 0&&r!==void 0)throw new Error("applications start-test: --party or --applicant, not both");if(Rg(e,n)&&(r===void 0||!pR.includes(r.trim().toLowerCase())))throw new Error(`applications start-test: on prod only for the test account ${pR.join(", ")} (--applicant) \u2014 never a real family's`)}s(gR,"assertStartApplicant");function yR(e){let n={};for(let{address:t,...r}of e.entries)n[t]=r;return{applicationId:e.applicationId,store:n}}s(yR,"processStoreJson");function aG(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.revisionNumber}`} \xB7 ${e.contractStatus}`;case"contracts":return e.contracts.map(n=>`${n.partKey}: contract ${n.contractId} \xB7 ${n.revision===null?"keine Fassung":`Fassung ${n.revision.revisionNumber}`} \xB7 ${n.contractStatus}`).join("; ")}}s(aG,"refText");function lG(e){return e.state!=="present"?e.reason?.de??"":e.ref!==void 0?aG(e.ref):JSON.stringify(e.value)}s(lG,"holds");function wR(e){return e.entries.map(n=>({address:n.address,state:n.state,holds:lG(n),producer:n.producer?.label??"",written:n.writtenAt===void 0?"":new Date(n.writtenAt).toISOString()}))}s(wR,"storeRows");function Yu(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(Yu,"parseKv");var kR="started",Hu="submitted",Ju="submitted",bR="load-scenario:";var vR="(Bewerbung)";function xR(e){return{nodeId:vR,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(xR,"sharedAsList");function SR(e){return e.disabledReason===void 0?"":e.disabledCount===void 0?e.disabledReason:`${e.disabledReason} (${e.disabledCount})`}s(SR,"disabledText");function AR(e){return e.flatMap(({nodeId:n,actions:t})=>t.map(r=>({node:n,action:r.id,label:r.label.de,disabled:SR(r)})))}s(AR,"actionRows");function ER(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: ${SR(a)}`);if(i!==vR)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(ER,"nodeOfferingAction");function TR(e,n,t){if(e.startsWith(bR)){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(TR,"runParams");async function dG(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(dG,"currentNodeIds");function cG(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(cG,"refusalText");async function Qu(e,n,t){let r=await e.query(x.workflow.listSharedTestActions,{applicationId:n});if(!r.permitted)throw new Error(`test-actions: not permitted \u2014 ${cG(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,xR(r.actions)]}s(Qu,"actionsOf");async function $R(e,n,t){return t!==void 0?[t]:await dG(e,n)}s($R,"nodesOf");var Fg=class extends D{static{s(this,"TestActionsListCommand")}static paths=[["test-actions","list"]];static usage=T.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=p.String("--application",{required:!0,description:"Application id (a test application)"});node=p.String("--node",{description:"Node id (default: the application's current nodes)"});async execute(){let n=await this.caller(),t=await Qu(n,this.application,await $R(n,this.application,this.node));return this.print(t,AR,["node","action","label","disabled"]),0}},Lg=class extends D{static{s(this,"TestActionsRunCommand")}application=p.String("--application",{required:!0,description:"Application id (a test application)"});node=p.String("--node",{description:"Node id (default: the application's current nodes)"});static paths=[["test-actions","run"]];static usage=T.Usage({category:"Admission",description:"Run one test-mode action; a scenario (load-scenario:<id>) also submits unless --no-auto-submit"});action=p.String("--action",{required:!0,description:"Action id, e.g. load-scenario:standard, auto-fill-files, submit-form"});autoSubmit=p.Boolean("--auto-submit",!0,{description:"Scenario only: stub the file fields and submit after loading (default on; --no-auto-submit only loads)"});param=p.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=TR(this.action,this.autoSubmit,Yu(this.param??[]).values),t=await this.caller(),r=this.application,i=await $R(t,this.application,this.node),o=ER(await Qu(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}},RR=[Fg,Lg];var ze=["de","en"];function hs(e,n){return ze.every(t=>e[t]===n[t])}s(hs,"sameText");function Rn(e){if(e===null||typeof e!="object"||Array.isArray(e))return"not-localized";let n=e;return Object.keys(n).some(r=>!ze.includes(r))?"not-localized":ze.filter(r=>{let i=n[r];return typeof i!="string"||i.trim()===""})}s(Rn,"missingLocales");function Ti(e){let n=Rn(e);return n!=="not-localized"&&n.length===0}s(Ti,"isLocalizedText");function ol(e,n){let t={};for(let r of ze){let i=e.map(o=>o[r]);t[r]=i.every(o=>typeof o=="string"&&o.trim()!=="")?n(i,r):""}return t}s(ol,"composeTexts");var fr=/^[a-z][A-Za-z0-9]*$/;function Mg(e){return typeof e=="string"&&fr.test(e)}s(Mg,"isNodeId");function gs(e,n){Mg(e)||F(`[graph/nodeIdFormat] "${e}" cannot name a node: a node id is ${fr.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 $i="$env";function se(e){if(e.scope==="env")return`${$i}.${e.key}`;let n=e.scope==="derived"?`$derived.${e.key}`:`$${e.scope}.${e.owner}.${e.key}`;return e.path===void 0?n:`${n}.${e.path}`}s(se,"formatAddress");var Nr=/^[a-z][a-zA-Z0-9_]*$/,uG=/^[A-Za-z_][A-Za-z0-9_]*$/;function po(e){return typeof e=="string"&&e.split(".").every(n=>uG.test(n))}s(po,"isPath");function Qr(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&&po(i)?{scope:"env",key:i}:null}case"derived":{let[i,...o]=r;return i===void 0||!Nr.test(i)?null:IR({scope:"derived",key:i},o)}case"node":case"task":{let[i,o,...a]=r;return i===void 0||o===void 0||!Nr.test(o)||(t==="node"?!fr.test(i):!Nr.test(i))?null:IR({scope:t,owner:i,key:o},a)}default:return null}}s(Qr,"tryParseAddress");function IR(e,n){if(n.length===0)return e;let t=n.join(".");return po(t)?{...e,path:t}:null}s(IR,"withPath");function we(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e,t=n.scope==="env"?["scope","key"]:n.scope==="derived"?["scope","key","path"]:["scope","owner","key","path"];if(Object.keys(n).some(r=>!t.includes(r))||n.path!==void 0&&!po(n.path))return!1;switch(n.scope){case"env":return po(n.key);case"derived":return typeof n.key=="string"&&Nr.test(n.key);case"node":return typeof n.owner=="string"&&fr.test(n.owner)&&typeof n.key=="string"&&Nr.test(n.key);case"task":return typeof n.owner=="string"&&Nr.test(n.owner)&&typeof n.key=="string"&&Nr.test(n.key);default:return!1}}s(we,"isAddress");var Zr={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"}},ys=Object.keys(Zr);function ws(e){return Object.hasOwn(Zr,e)}s(ws,"isEnvKey");var fG=["self-service","staff"];function OR(e,n){return{kind:"fixed",values:e,labels:n}}s(OR,"fixedSet");var Zu={of:"applicant.language",withoutValue:"de"},Xr={"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:Zu},"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:Zu},"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:Zu},"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:Zu},"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:OR(ze,{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:OR(fG,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},Xu={types:Zr,fields:Xr},ef=ys.flatMap(e=>Object.keys(Zr[e]).map(n=>`${e}.${n}`));function pr(e){return Object.hasOwn(Xr,e)}s(pr,"isEnvLeaf");function nf(e){return`${$i}.${e}`}s(nf,"envIdentifier");function mo(e){let n=Xr[e],[t,r]=e.split("."),i=Zr[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(mo,"envLeaf");var PR="staffInput";var pG=["boolean"],sl=/^[a-z][A-Za-z0-9]*$/;function tf(e){return e.staffInputs??[]}s(tf,"staffInputsOf");function rf(e){return`${PR}.${e}`}s(rf,"staffInputLeaf");function _R(e){return`${$i}.${rf(e)}`}s(_R,"staffInputIdentifier");function mG(e){let n=`${PR}.`;return e.startsWith(n)?e.slice(n.length):null}s(mG,"staffInputKeyOfLeaf");function al(e,n){let t=mG(n);return t===null?void 0:tf(e).find(r=>r.key===t)}s(al,"declaredStaffInput");function hG(e){return[...tf(e).map(n=>({leaf:rf(n.key),type:n.type,label:n.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...ef.map(n=>{let t=mo(n);return{leaf:n,type:t.type,label:t.label,valueSet:Xr[n].valueSet,nullable:t.nullable,cohortBound:t.cohortBound===!0}})]}s(hG,"envLeavesFor");function NR(e){return hG(e).filter(n=>!n.cohortBound)}s(NR,"conditionEnvLeaves");function CR(e){let n={},t={};for(let{leaf:r,type:i,valueSet:o,nullable:a}of NR(e)){let[l="",d=""]=r.split(".");n[l]={...n[l]??{},[d]:i},t[r]={valueSet:o,nullable:a}}return{types:n,fields:t}}s(CR,"envConditionSchemaFor");function DR(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}"`};sl.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),pG.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=Rn(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(DR,"staffInputIssues");var Wg={required:!0,description:"Offer slug (its offerKey)"},qg=class extends D{static{s(this,"ApplicationsListCommand")}static paths=[["applications","list"]];static usage=T.Usage({category:"Admission",description:"List an offer's applications (id, status, board state, applicant, test)"});offer=p.String("--offer",Wg);testOnly=p.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=hR(t).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},Kg=class extends D{static{s(this,"ApplicationsCountsCommand")}static paths=[["applications","counts"]];static usage=T.Usage({category:"Admission",description:"Count an offer's applications per list"});offer=p.String("--offer",Wg);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}},jg=class extends D{static{s(this,"ApplicationsShowCommand")}static paths=[["applications","show"]];static usage=T.Usage({category:"Admission",description:"One application: status, test flag, offer, current workflow nodes"});application=p.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 Error(`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}},Bg=class extends D{static{s(this,"ApplicationsStoreCommand")}static paths=[["applications","store"]];static usage=T.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, $derived\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=p.String({required:!0});async execute(){let t=await(await this.caller()).query(x.processStoreView.get,{applicationId:this.application});return this.print(yR(t),()=>wR(t),["address","state","holds","producer","written"]),0}},Ug=class extends D{static{s(this,"ApplicationsStartTestCommand")}static paths=[["applications","start-test"]];static usage=T.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=p.String("--offer",Wg);run=p.String("--run",{required:!0,description:"School year: its key or id (never its name)"});stage=p.String("--stage",{required:!0,description:"Level: its key or id (never its name)"});party=p.String("--party",{description:"Applicant party id"});applicant=p.String("--applicant",{description:"Applicant account login address (e.g. the test account test@example.com)"});version=p.String("--version",{description:"Offer version id to test (default: the live generation)"});staffInput=p.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=p.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();gR(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let t=this.requireTenant(n),r=mR(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 Error(`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:LR(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 Qu(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}},Vg=class extends D{static{s(this,"ApplicationsDiscardTestCommand")}static paths=[["applications","discard-test"]];static usage=T.Usage({category:"Admission",description:"Discard a TEST application (the server refuses a real one)"});application=p.String({required:!0});async execute(){return await(await this.caller()).mutation(x.admission.discardTest,{applicationId:this.application}),this.print({discarded:this.application},t=>[{key:"discarded",value:t.discarded}]),0}},Gg=class extends D{static{s(this,"ApplicationsStaffInputListCommand")}static paths=[["applications","staff-input","list"]];static usage=T.Usage({category:"Admission",description:"An application's internal inputs (set at the start): value, and why one can no longer be corrected"});application=p.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}},zg=class extends D{static{s(this,"ApplicationsStaffInputSetCommand")}static paths=[["applications","staff-input","set"]];static usage=T.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=p.String({required:!0});input=p.String("--input",{required:!0,description:"key=true|false"});reason=p.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}]=LR([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}},FR=[qg,Kg,jg,Bg,Ug,Vg,Gg,zg];function LR(e){return e.map(n=>{let[t="",r,...i]=n.split("=");if(!sl.test(t)||r!=="true"&&r!=="false"||i.length>0)throw new Error(`--staff-input "${n}": expected key=true or key=false`);return{key:t,value:r==="true"}})}s(LR,"parseStaffInputs");var Kn="contractGenerator",ho="documentTemplate";function ll(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(ll,"isGeneratorRef");function MR(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(MR,"literalOf");function ei(e){let n=MR(e,Kn);return ll(n)?n:null}s(ei,"generatorRefOfNode");function mr(e){let n=MR(e,ho);return typeof n=="string"&&n.length>0?n:null}s(mr,"documentTemplateKeyOfNode");function qR(e){return`${e.kind}:${e.key}${e.revision===void 0?"":`@${e.revision}`}`}s(qR,"generatorRefLabel");var gG=["formExports","generatorStamp"];function KR(e,n,t){let r=e.inputs?.[Kn];(r?.kind!=="literal"||!ll(r.value))&&F(`applyGeneratorStamp: the node names no generator in inputs.${Kn} \u2014 a stamp derives from it`),t.freezeRevision&&n.revision!==void 0&&(e.inputs[Kn]={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}}}s(KR,"applyGeneratorStamp");var yG=["reads"];function ks(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 gG)delete r[i];for(let i of yG)Array.isArray(r[i])&&r[i].length===0&&delete r[i];return r})),n}s(ks,"comparableWorkflowGraph");var dl={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 of(e){return e===null||typeof e!="object"||Array.isArray(e)?["manifest: data must be an object"]:Object.keys(e).map(n=>{let t=dl[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(of,"manifestIssues");function wG(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(wG,"validateProgressLayoutExternalCopy");function jR(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"]:wG(e)}s(jR,"progressLayoutIssues");var BR=new Set(["nodes","assignmentRules","channels","processStore","pricingRules","staffInputs"]);var kG=new Set(["sections","effects","outcomes","testScenarios","env"]),sf={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 UR(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(kG.has(i))continue;let o=sf[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(UR,"smartFormDefinitionShapeIssues");var bt=["granted","rejected","waitlisted","other"];function Ri(e){return typeof e=="string"&&bt.includes(e)}s(Ri,"isOutcomeSemantic");var Yt=["arrival","manual"],VR={arrival:{de:"Nach Eingang",en:"By arrival"},manual:{de:"Von Hand sortiert",en:"Sorted by hand"}};function bG(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(bG,"literal");function Yg(e){let n=bG(e,"waitlistOrder");return Yt.includes(n)?{waitlistOrder:n}:null}s(Yg,"waitlistPolicyOrNull");var gn="responsible",Hg="team:";function af(e){return`${Hg}${e}`}s(af,"teamSlot");function lf(e){return e.startsWith(Hg)?e.slice(Hg.length):null}s(lf,"teamKeyOfSlot");function GR(e){return e.kind==="responsible"?gn:af(e.groupKey)}s(GR,"slotIdOf");function df(e){if(e===gn)return{kind:"responsible"};let n=lf(e);return n===null||n.length===0?null:{kind:"team",groupKey:n}}s(df,"slotOfId");var Jg="review",Qg="checkField",zR="reviewed",WR="reviewing",cf=["rejected","waitlisted"];function Zg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Zg,"isObject");var vG=new Set(["decision",Jg]),YR={approved:"granted",accepted:"granted",admitted:"granted",direkt:"granted",rejected:"rejected",absage:"rejected",declined:"rejected",waitlisted:"waitlisted",warteliste:"waitlisted"};function Xg(e){return Object.hasOwn(YR,e)?YR[e]:void 0}s(Xg,"legacySemanticOfId");function xG(e){return e===Jg?bt.filter(n=>!cf.includes(n)):bt}s(xG,"allowedSemanticsFor");var SG="other";function HR(e){return Zg(e)&&vG.has(String(e.type))&&Array.isArray(e.outcomes)?e.outcomes:[]}s(HR,"outcomesOf");function JR(e){return(e?.nodes??[]).some(n=>HR(n).some(t=>Zg(t)&&!("semantic"in t)))}s(JR,"needsOutcomeSemantics");function QR(e,n={}){let t=[],r=[],i=[],o=e.nodes.map(a=>{let l=HR(a);if(l.length===0)return a;let d=a,c=String(d.id),u=String(d.type),f=xG(u),m=!1,y=l.map(k=>{if(!Zg(k))return k;let g=String(k.id);if("semantic"in k)return Ri(k.semantic)||i.push({nodeId:c,outcomeId:g,value:String(k.semantic)}),k;let b=`${c}.${g}`,A=Object.hasOwn(n,b)?n[b]:void 0;if(A!==void 0)return f.includes(A)?(t.push({nodeId:c,outcomeId:g,semantic:A,source:"answer"}),m=!0,{...k,semantic:A}):(r.push({nodeId:c,nodeType:u,outcomeId:g,allowed:f,answer:A}),k);let $=Xg(g),O=$??SG;return f.includes(O)?(t.push({nodeId:c,outcomeId:g,semantic:O,source:$===void 0?"formerDefault":"legacyTable"}),m=!0,{...k,semantic:O}):(r.push({nodeId:c,nodeType:u,outcomeId:g,allowed:f}),k)});return m?{...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(QR,"addOutcomeSemantics");var hr="bewerbungOffen";function go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(go,"isObject");var ey=["event","effect"];function ZR(e){return go(e)&&e.type==="eventTrigger"}s(ZR,"isTrigger");function XR(e){let n=go(e.inputs)?e.inputs:{};return"outcomes"in e||ey.some(t=>t in e||t in n)}s(XR,"oldShape");function eI(e){return(e?.nodes??[]).some(n=>ZR(n)&&XR(n))}s(eI,"needsEventTriggerStartMove");function AG(e){let n=String(e.id),r=(Array.isArray(e.outcomes)?e.outcomes:[]).map(l=>go(l)?l.id:void 0);if("outcomes"in e&&!(r.length===1&&r[0]===hr))return{unmoved:{nodeId:n,reason:"outcomesNotStart"}};let i=Object.keys(go(e.next)?e.next:{});if(!(i.length===1&&i[0]===hr))return{unmoved:{nodeId:n,reason:"nextNotStart"}};let o=go(e.inputs)?{...e.inputs}:{};for(let l of ey){let d=o[l];if(go(d)&&d.kind==="binding")return{unmoved:{nodeId:n,reason:"bindingCell"}}}let a={...e};delete a.outcomes;for(let l of ey)delete a[l],delete o[l];return go(e.inputs)&&(Object.keys(o).length>0?a.inputs=o:delete a.inputs),{node:a}}s(AG,"moveNode");function nI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!ZR(i)||!XR(i))return i;let o=AG(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(nI,"moveEventTriggerStart");function cl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(cl,"isObject");var tI={waitlistOrder:"arrival"};function rI(e){return!cl(e)||e.type!=="waitlist"?!1:!("waitlistOrder"in(cl(e.inputs)?e.inputs:{}))}s(rI,"lacksPolicy");function EG(e){return(e?.nodes??[]).some(rI)}s(EG,"needsWaitlistPolicyMove");function ny(e){return cl(e)&&Yt.includes(e.waitlistOrder)}s(ny,"isWaitlistPolicy");function TG(e){if(e===void 0)return{policy:tI,stated:!1};if(!cl(e))return"malformed";let n=e.waitlistOrder;return n!==void 0&&!Yt.includes(n)?"malformed":{policy:{waitlistOrder:n??tI.waitlistOrder},stated:n!==void 0}}s(TG,"policyOfSelection");function iI(e,n,t={}){let r=[],i=[];if(!EG(e))return{graph:e,moved:r,refused:i};let o=TG(n),a=e.nodes.map(l=>{if(!rI(l))return l;let d=l,c=String(d.id),u=cl(d.inputs)?{...d.inputs}:{},f=Object.hasOwn(t,c)?t[c]:void 0,m,y;if(f!==void 0)m=f,y="answer";else{if(o==="malformed")return i.push({nodeId:c,reason:"selectionMalformed"}),l;m=o.policy,y=o.stated?"manifest":"formerDefault"}return u.waitlistOrder={kind:"literal",value:m.waitlistOrder},r.push({nodeId:c,policy:m,source:y}),{...d,inputs:u}});return r.length===0?{graph:e,moved:r,refused:i}:{graph:{...e,nodes:a},moved:r,refused:i}}s(iI,"moveWaitlistPolicyToInputs");function yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(yo,"isObject");var $G=[Kn,ho],RG=["inputSchema","parties","schemaDigest","parts"];function oI(e){return yo(e)&&e.type==="governedDocument"&&("resolver"in e||yo(e.template)&&("key"in e.template||"cockpitFields"in e.template))}s(oI,"oldShape");function sI(e){return(e?.nodes??[]).some(oI)}s(sI,"needsGeneratorInputMove");function IG(e){let n=yo(e.inputs)?{...e.inputs}:{},t={...e},r;if("resolver"in e){let i=e.resolver;if(!yo(i))return{unmoved:"resolverNotObject"};if(Kn 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((yo(i.inputSchema)&&Array.isArray(i.inputSchema.fields)?i.inputSchema.fields:[]).find(d=>yo(d)&&$G.includes(String(d.key)))!==void 0)return{unmoved:"stampDeclaresReservedKey"};n[Kn]={kind:"literal",value:{kind:i.kind,key:i.key,...i.revision===void 0?{}:{revision:i.revision}}};let l=Object.fromEntries(RG.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(yo(e.template)&&("key"in e.template||"cockpitFields"in e.template)){let{key:i,cockpitFields:o,...a}=e.template;if("key"in e.template){if(ho in n)return{unmoved:"templateInputExists"};if(typeof i!="string"||i.length===0)return{unmoved:"templateKeyInvalid"};n[ho]={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(IG,"moveNode");function aI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!oI(i))return i;let o=IG(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(aI,"moveGeneratorPinsToInputs");var lI=/^\d{4}-\d{2}-\d{2}$/;function gr(e,n){return{de:e,en:n}}s(gr,"issue");function wo(e){if(typeof e!="object"||e===null)return gr("keine Reduktion","not a reduction");let n=e;if(n.kind==="none")return Object.keys(n).length===1?null:gr('\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben','"no reduction" carries no further details');if(n.kind!=="amount")return gr(`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?gr("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"||!lI.test(r)?gr("der Beginn fehlt (JJJJ-MM-TT)","the start is missing (YYYY-MM-DD)"):typeof i!="string"||!lI.test(i)?gr("das Ende fehlt (JJJJ-MM-TT)","the end is missing (YYYY-MM-DD)"):i<r?gr("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)?gr("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))?gr("ung\xFCltige Preisperiode","invalid price period"):Object.keys(n).some(o=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(o))?gr("unbekannte Angaben","unknown details"):null:gr("der Betrag hat mehr als zwei Nachkommastellen","the amount has more than two decimal places")}s(wo,"reductionShapeIssue");function Ii(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||wo(n.reduction)===null&&n.reduction.kind==="amount")}s(Ii,"isPricedItemValue");var bs=["freetext","recommendation","choice","pricedItem","record","reduction"],vs=[...bs,"appointment"];function cI(e){return typeof e=="string"&&vs.includes(e)}s(cI,"isTaskResultKind");function Oi(e){return typeof e=="string"&&bs.includes(e)}s(Oi,"isRecordedTaskResultKind");function xs(e){return Oi(e.kind)}s(xs,"isRecordedTaskResult");var uf=["number","boolean","enum"];function ty(e){return typeof e=="string"&&uf.includes(e)}s(ty,"isRecordFieldType");var ry=["form","siblingRank"];var ni={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 uI(e){return(e.kind==="freetext"||e.kind==="recommendation"||e.kind==="choice")&&e.writes===void 0}s(uI,"isProseResult");function ff(e){return e.kind==="record"?(e.fields??[]).filter(n=>typeof n.writes=="string"&&n.writes.length>0&&ty(n.type)).map(n=>({key:n.writes,valueType:n.type,field:n})):OG(e)}s(ff,"draftResultStoreWrites");function OG(e){let n=ni[e.kind].valueType;return e.writes===void 0||n===null?[]:[{key:e.writes,valueType:n}]}s(OG,"singleStoreWrite");var dI="team:";function Ss(e){if(e==="all")return{kind:"all"};if(e==="external"||e.length===0)return null;if(e.startsWith(dI)){let n=e.slice(dI.length);return n.length===0?null:{kind:"team",groupKey:n}}return{kind:"channel",channelKey:e}}s(Ss,"parseTaskResultChat");var Ze={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]",reductionPrices:"[taskResult/reductionPrices]",pricesOnNonReduction:"[taskResult/pricesOnNonReduction]"};var PG=new Set(["if","else","in","true","false","null"]),_G=new Set(["==","!=","<=",">=","&&","||"]);function NG(e){return e>="0"&&e<="9"}s(NG,"isDigit");function CG(e){return/[a-zA-Z_$]/.test(e)}s(CG,"isIdentStart");function DG(e){return/[a-zA-Z0-9_.$]/.test(e)}s(DG,"isIdentCont");function FG(e){let n=[],t=0;for(;t<e.length;){let r=e.charAt(t);if(r===" "||r===" "||r===`
10498
10503
  `||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(NG(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(CG(r)){let o=t;for(;o<e.length&&DG(e.charAt(o));)o++;let a=e.slice(t,o);PG.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(_G.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(FG,"tokenise");var fI=1e4,pI=128;function As(e){e.depth++,e.depth>pI&&F(`Expression nesting too deep (> ${pI})`)}s(As,"enterDepth");function kI(e){return e.pos<e.tokens.length?e.tokens[e.pos]:null}s(kI,"peek");function jn(e){let n=e.tokens[e.pos];return n||F(`Unexpected end at ${e.pos}`),e.pos++,n}s(jn,"take");function Bn(e,n,t){let r=kI(e);return!(!r||r.t!==n||t!==void 0&&r.v!==t)}s(Bn,"match");function ko(e,n,t){return Bn(e,n,t)||F(`Expected ${n}${t?`:${t}`:""} at ${e.pos}`),jn(e)}s(ko,"expect");function ri(e){As(e);try{return Bn(e,"kw","if")?LG(e):MG(e)}finally{e.depth--}}s(ri,"parseExpr");function LG(e){ko(e,"kw","if"),ko(e,"punct","(");let n=ri(e);ko(e,"punct",")");let t=ri(e);ko(e,"kw","else");let r=ri(e);return{kind:"if",cond:n,then:t,else:r}}s(LG,"parseIf");function MG(e){let n=mI(e),t=0;try{for(;Bn(e,"op","||");){jn(e),As(e),t++;let r=mI(e);n={kind:"binary",op:"||",left:n,right:r}}}finally{e.depth-=t}return n}s(MG,"parseLogicOr");function mI(e){let n=hI(e),t=0;try{for(;Bn(e,"op","&&");){jn(e),As(e),t++;let r=hI(e);n={kind:"binary",op:"&&",left:n,right:r}}}finally{e.depth-=t}return n}s(mI,"parseLogicAnd");function hI(e){let n=gI(e),t=0;try{for(;Bn(e,"op","==")||Bn(e,"op","!=");){let r=jn(e).v;As(e),t++;let i=gI(e);n={kind:"binary",op:r,left:n,right:i}}}finally{e.depth-=t}return n}s(hI,"parseEquality");function gI(e){let n=oy(e),t=0;try{for(;Bn(e,"op","<")||Bn(e,"op","<=")||Bn(e,"op",">")||Bn(e,"op",">=")||Bn(e,"kw","in");){let r=jn(e),i=r.t==="kw"?"in":r.v;As(e),t++;let o=oy(e);n={kind:"binary",op:i,left:n,right:o}}}finally{e.depth-=t}return n}s(gI,"parseCompare");function oy(e){if(Bn(e,"op","!")){jn(e),As(e);try{return{kind:"unary",op:"!",operand:oy(e)}}finally{e.depth--}}return qG(e)}s(oy,"parseUnary");function qG(e){let n=kI(e);if(n||F("Unexpected end"),n.t==="num")return jn(e),{kind:"num",value:n.v};if(n.t==="str")return jn(e),{kind:"str",value:n.v};if(n.t==="kw"&&n.v==="true")return jn(e),{kind:"bool",value:!0};if(n.t==="kw"&&n.v==="false")return jn(e),{kind:"bool",value:!1};if(n.t==="kw"&&n.v==="null")return jn(e),{kind:"null"};if(n.t==="punct"&&n.v==="("){jn(e);let t=ri(e);return ko(e,"punct",")"),t}if(n.t==="punct"&&n.v==="["){jn(e);let t=[];if(!Bn(e,"punct","]"))for(t.push(ri(e));Bn(e,"punct",",");)jn(e),t.push(ri(e));return ko(e,"punct","]"),{kind:"arr",items:t}}if(n.t==="ident"){let t=n.v;if(jn(e),Bn(e,"punct","(")){jn(e);let r=[];if(!Bn(e,"punct",")"))for(r.push(ri(e));Bn(e,"punct",",");)jn(e),r.push(ri(e));return ko(e,"punct",")"),{kind:"call",name:t,args:r}}return{kind:"ident",path:t}}F(`Unexpected token at ${e.pos}`)}s(qG,"parsePrimary");function Un(e){e.length>fI&&F(`Expression too long (${e.length} > ${fI})`);let n={tokens:FG(e),pos:0,depth:0},t=ri(n);return n.pos<n.tokens.length&&F(`Unexpected trailing token at ${n.pos}`),t}s(Un,"parseExpression");var KG=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 yn(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=>yn(t,n));case"unary":{let t=yn(e.operand,n);return!Pi(t)}case"call":{let t=n.functions!==void 0&&Object.hasOwn(n.functions,e.name)?n.functions[e.name]:KG.get(e.name);t||F(`Unknown function '${e.name}'`);let r=e.args.map(i=>yn(i,n));return t(...r)}case"binary":return jG(e.op,e.left,e.right,n);case"if":return Pi(yn(e.cond,n))?yn(e.then,n):yn(e.else,n)}}s(yn,"evaluate");function jG(e,n,t,r){if(e==="&&"){let a=yn(n,r);return Pi(a)?Pi(yn(t,r)):!1}if(e==="||"){let a=yn(n,r);return Pi(a)?!0:Pi(yn(t,r))}let i=yn(n,r),o=yn(t,r);switch(e){case"==":return iy(i,o);case"!=":return!iy(i,o);case"<":{let[a,l]=pf(i,o);return a!==null&&l!==null&&a<l}case"<=":{let[a,l]=pf(i,o);return a!==null&&l!==null&&a<=l}case">":{let[a,l]=pf(i,o);return a!==null&&l!==null&&a>l}case">=":{let[a,l]=pf(i,o);return a!==null&&l!==null&&a>=l}case"in":return Array.isArray(o)?o.some(a=>iy(a,i)):!1}}s(jG,"evalBinary");function pf(e,n){return[yI(e),yI(n)]}s(pf,"orderedOperands");function yI(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(yI,"numericOperand");function iy(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(iy,"looseEq");function Pi(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(Pi,"truthy");function bn(e){let n=new Set;return ti(e,n),[...n]}s(bn,"dependencies");function ti(e,n){switch(e.kind){case"ident":n.add(e.path);return;case"call":e.args.forEach(t=>ti(t,n));return;case"arr":e.items.forEach(t=>ti(t,n));return;case"unary":ti(e.operand,n);return;case"binary":ti(e.left,n),ti(e.right,n);return;case"if":ti(e.cond,n),ti(e.then,n),ti(e.else,n);return;default:return}}s(ti,"walk");var wI=new Map;function yr(e){let n=wI.get(e);return n||(n=Un(e),wI.set(e,n)),n}s(yr,"parseCached");function BG(e,n){return yn(yr(e),n)}s(BG,"evalExpression");function bI(e,n){return Pi(BG(e,n))}s(bI,"evalBoolean");function mf(e){let n=e.pricingRules;return n===void 0?[]:(Array.isArray(n)||F("graph.pricingRules must be an array \u2014 the graph validator refuses anything else"),n)}s(mf,"pricingRuleSets");function sy(e){return e.derive!==void 0}s(sy,"isDerivedKey");function UG(e,n){let t=mf(e);return(n.rules??[]).map(r=>{let i=t.find(o=>o.key===r);return i===void 0&&F(`[process] derivation names the unknown rule set "${r}" \u2014 publish refuses that`),i})}s(UG,"ruleSetsOfDerivation");function xI(e){return[...new Set(e.rows.flatMap(n=>bn(yr(n.when))))]}s(xI,"ruleSetDependencies");function SI(e){let n=Qr(e);return n!==null&&se(n)===e?n:null}s(SI,"ruleIdentifierAddress");function ay(e,n){let r=[...new Set(UG(e,n).flatMap(xI))].map(o=>{let a=SI(o);return a===null&&F(`[address/bareIdentifier] rule identifier "${o}" is no address \u2014 publish refuses that`),{address:a,id:o,role:"rule"}}),i=n.reduction;return i===void 0?r:(we(i)||F(`[address/bareIdentifier] derive.reduction ${JSON.stringify(i)} is no address \u2014 publish refuses that`),[...r,{address:i,id:se(i),role:"reduction"}])}s(ay,"derivationSources");function AI(e,n){let t=mf(e);for(let r of n.rules??[]){let i=t.find(o=>o.key===r);if(i===void 0||i.rows.some(o=>ul(o.when)!==null)||xI(i).some(o=>SI(o)===null))return null}return n.reduction!==void 0&&!we(n.reduction)?null:ay(e,n)}s(AI,"draftDerivationSources");function ul(e){if(typeof e!="string"||e.trim().length===0)return"leere Bedingung";try{return yr(e),null}catch(n){return n instanceof Error?n.message:String(n)}}s(ul,"conditionIssue");function vI(e){return e.item!==void 0&&e.group===void 0?{kind:"item",key:e.item}:e.group!==void 0&&e.item===void 0?{kind:"group",key:e.group}:null}s(vI,"rowTarget");function ly(e){if(e.byStage===void 0){let n=vI(e);return n===null?[]:[{...n,stages:null}]}return e.item!==void 0||e.group!==void 0?[]:e.byStage.flatMap(n=>{let t=vI(n);return t===null?[]:[{...t,stages:n.stages}]})}s(ly,"derivationTargets");function EI(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(EI,"assertNoCustomNodeExports");var dy=null;function TI(e){for(let[n,t]of Object.entries(e))EI(n,t);dy=e}s(TI,"setSpecs");function $I(){return dy||F("[workflow/registry] Specs not initialised. Import convex/model/admission/specs before calling specFor()."),dy}s($I,"requireSpecs");function He(e){let n=$I(),t=n[e.type];return t===void 0&&le("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(He,"specFor");function RI(){return Object.keys($I()).sort()}s(RI,"registeredNodeTypes");var II=ef.filter(e=>Xr[e].cohortBound!==!0);function cy(e){return pr(e)&&Xr[e].cohortBound!==!0}s(cy,"isEnvAddressLeaf");function uy(e){return mo(e).type}s(uy,"envType");function fy(e){return mo(e).label}s(fy,"envLabel");function hf(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};case"derived":return{scope:"derived",key:e.key}}}s(hf,"addressBase");function wr(e){return e.scope==="node"&&e.key===it&&e.path===void 0}s(wr,"isInstanceAddress");function dn(e){return we(e)&&e.scope==="node"&&e.key===it&&e.path!==void 0}s(dn,"isFormFieldAddress");function OI(e){return dn(e)?{owner:e.owner,path:e.path}:null}s(OI,"formFieldOf");function py(e){return bn(yr(e)).map(n=>{if(!n.startsWith("$"))return{identifier:n,address:null,reason:"bareIdentifier"};let t=Qr(n);return t===null?{identifier:n,address:null,reason:"shape"}:{identifier:n,address:t}})}s(py,"expressionAddresses");var it="admission",hl="document",Es="contract",Ts="contracts",PI="payment",my=new Set(["adoptForm","setFlagTarget","form","familyRequestFrom"]);var ct={id:"identity",type:"identity",label:"display",sublabel:"display",library:"display",outcomes:"control",outputLabels:"display",inputs:"input",next:"control",tasks:"config",assign:"reference",optionalActions:"config",artifacts:"config",notifications:"config"},_le={join:{...ct},end:{...ct},eventTrigger:{...ct},form:{...ct,adoptForm:"address",formExports:"stamp"},roleAssign:{...ct},setFlag:{...ct},if:{...ct,condition:"address"},countersign:{...ct,contract:"address",titles:"display",signing:"config"},engagePush:{...ct,engage:"tenantRef",form:"address",contract:"address",payment:"address"},decision:{...ct,commentRequired:"config",decisionAsTask:"config",reads:"address",requiresOneOf:"config"},review:{...ct,form:"address",commentRequired:"config",decisionAsTask:"config"},waitlist:{...ct},completenessCheck:{...ct,requires:"address",deadline:"config"},collectPayment:{...ct},governedDocument:{...ct,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 Cr(e){return Array.isArray(e)?e:[]}s(Cr,"listOf");function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}s(Vn,"record");function _I(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(_I,"dataSourceFieldsOf");function NI(e){return e.type==="review"?[]:e.type==="engagePush"?["form"]:_I(e)}s(NI,"requiredDataSourceFields");var VG={setFlag:{target:"setFlagTarget"}};function gl(e,n={}){let t=[],r=e,i=`nodes.${e.id}`,o=s((d,c,u,f={})=>{t.push({kind:d,at:c,nodeId:e.id,value:u,judgedTogether:null,...f})},"field"),a=new Map(n.slotTypes===!1?[]:(He(e).inputs?.(e)??[]).map(d=>[d.id,d.type])),l=VG[e.type]??{};for(let[d,c]of Object.entries(Vn(r.inputs)??{})){let u=Vn(c);if(u?.kind!=="binding")continue;let f="address"in u?u.address:u.path,m=l[d];if(m!==void 0){o(m,`${i}.inputs.${d}`,f);continue}let y=a.get(d);o("binding",`${i}.inputs.${d}`,f,y!==void 0?{expectedType:y}:{})}for(let[d,c]of Cr(r.reads).entries())o("nodeReads",`${i}.reads.${d}`,c,{judgedTogether:`${i}.reads`});for(let[d,c]of Cr(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 _I(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 Cr(r.tasks).entries())t.push(...CI(e.id,c,d));return t}s(gl,"nodeAddressFields");function CI(e,n,t){let r=Vn(n);if(r===null)return[];let i=[],o=typeof r.key=="string"?r.key:String(t),a=`nodes.${e}.tasks.${o}`,l=s((f,m,y,k={})=>{i.push({kind:f,at:m,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[f,m]of Cr(r.reads).entries())l("taskReads",`${a}.reads.${f}`,m,{judgedTogether:d});for(let[f,m]of Cr(r.documents).entries()){let y=Vn(m);y===null||y.kind==="artifact"||l("taskDocument",`${a}.documents.${f}`,"address"in y?y.address:y.key)}let c=Vn(r.familyRequest);if(c!==null){for(let[f,m]of Cr(c.fields).entries())l("familyRequestFields",`${a}.familyRequest.fields.${f}`,m,{judgedTogether:`${a}.familyRequest.fields`});c.from!==void 0&&l("familyRequestFrom",`${a}.familyRequest.from`,c.from)}let u=Vn(r.result);if(u?.kind==="record")for(let[f,m]of Cr(u.fields).entries()){let y=Vn(Vn(m)?.suggest);if(y?.kind!=="form")continue;let k=Vn(m)?.type;l("suggest",`${a}.result.fields.${f}.suggest`,"address"in y?y.address:y.key,typeof k=="string"?{expectedType:k}:{})}return i}s(CI,"taskAddressFields");function gf(e){let n=[];for(let[t,r]of Cr(e.processStore).entries()){let i=Vn(Vn(r)?.derive);if(i?.reduction!==void 0){let o=String(Vn(r)?.key);n.push({kind:"reduction",at:`processStore.${t}.derive.reduction`,nodeId:null,priceKey:o,value:i.reduction,judgedTogether:null})}}for(let[t,r]of Cr(e.pricingRules).entries())for(let[i,o]of Cr(Vn(r)?.rows).entries())n.push({kind:"pricingRule",at:`pricingRules.${t}.rows.${i}.when`,nodeId:null,value:Vn(o)?.when,judgedTogether:null});return n}s(gf,"priceAddressFields");function $s(e){return hy(e)?(yf(e.value)??[]).flatMap(n=>n.address===null?[]:[n.address]):we(e.value)?[e.value]:[]}s($s,"addressesInField");function hy(e){return e.kind==="pricingRule"||e.kind==="condition"}s(hy,"isExpressionField");function yf(e){return ul(e)===null?py(e):null}s(yf,"ruleConditionAddresses");function vt(e){return e.type==="form"&&e.adoptForm!==void 0&&e.adoptForm!==!1}s(vt,"adoptsForm");function DI(e){if(e.type!=="form"||vt({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(DI,"createdSmartFormSlug");function GG(e,n){return e.type!=="governedDocument"||e.production!=="resolver"||n!==hl?n:e.generatorStamp?.parts!==void 0?Ts:Es}s(GG,"addressKeyOfPort");function gy(e){let n=e.result;return n===void 0||!xs(n)?[]:ff(n).map(t=>t.key)}s(gy,"storeWritesOf");function pl(e,n){return(Array.isArray(e.processStore)?e.processStore:[]).find(t=>t.key===n)}s(pl,"declaredKey");function Dr(e,n){let t=[];if(!vt(n))for(let r of He(n).outputs?.(n)??[])t.push({address:{scope:"node",owner:n.id,key:GG(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 gy(r)){let o=pl(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(Dr,"producedAddresses");function FI(e,n,t){for(let r of e.nodes)for(let i of Array.isArray(r.tasks)?r.tasks:[])if(i.key===n&&gy(i).includes(t))return{nodeId:r.id,template:i};return null}s(FI,"taskWriter");function Fr(e,n,t){return FI(e,n,t)?.nodeId??null}s(Fr,"taskOwnerNode");function ml(e,n){let t=pl(e,n)?.derive;if(t===void 0)return null;let r=Array.isArray(e.pricingRules)?e.pricingRules:[],i=[];for(let a of t.rules??[]){let l=r.find(d=>d.key===a);if(l===void 0)return null;for(let d of l.rows){let c=yf(d.when);if(c===null)return null;for(let u of c)u.address!==null&&i.push(u.address)}}let o=t.reduction;return we(o)&&i.push(o),zG(i)}s(ml,"derivedSources");function zG(e){let n=new Set;return e.filter(t=>{let r=se(t);return n.has(r)?!1:(n.add(r),!0)})}s(zG,"dedupe");function WG(e){return gl(e,{slotTypes:!1}).flatMap(n=>$s(n).map(t=>({address:t,field:n})))}s(WG,"writtenAddressesOf");function bo(e,n){let t=[],r=new Set,i=s((l,d,c,u)=>{let f=`${se(l)}|${d}|${c.at}|${u===void 0?"":se(u)}`;r.has(f)||(r.add(f),t.push({address:l,origin:d,field:c,...u!==void 0?{via:u}:{}}))},"push"),o=s((l,d,c=new Set)=>{let u=se(l);if(!c.has(u)){if(c.add(u),l.scope==="task"){let f=FI(e,l.owner,l.key);if(f===null)return;for(let m of CI(f.nodeId,f.template))if(!(m.kind!=="taskWhen"&&m.kind!=="taskReads"))for(let y of $s(m))i(y,"evidence",d,l)}if(l.scope==="derived")for(let f of ml(e,l.key)??[])i(f,"derivedSource",d,l),o(f,d,c)}},"carried");for(let{address:l,field:d}of WG(n))i(l,"written",d),o(l,d);let a=new Set((Array.isArray(n.tasks)?n.tasks:[]).flatMap(l=>gy(l).map(d=>`${l.key}.${d}`)));for(let l of gf(e))if(!(l.kind!=="reduction"||!we(l.value)||l.value.scope!=="task")&&a.has(`${l.value.owner}.${l.value.key}`))for(let d of ml(e,l.priceKey)??[])d.scope==="task"&&a.has(`${d.owner}.${d.key}`)||(i(d,"priceCheck",l,{scope:"derived",key:l.priceKey}),o(d,l));return t}s(bo,"addressReadsOf");function yy(e,n){switch(n.scope){case"env":return pr(n.key)?uy(n.key):al(e,n.key)?.type;case"derived":case"task":{if(n.path!==void 0||n.scope==="task"&&Fr(e,n.owner,n.key)===null)return;let t=pl(e,n.key);return t===void 0||n.scope==="derived"!=(t.derive!==void 0)?void 0:t.type}case"node":{let t=e.nodes.find(i=>i.id===n.owner);if(t===void 0)return;let r=Dr(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(yy,"addressType");function fl(e,n){let t=Vn(e)?.[n];return typeof t=="string"&&t.length>0?t:void 0}s(fl,"labelText");function Oe(e,n,t){let r=e.nodes.find(i=>i.id===n);return fl(r?.label,t)??n}s(Oe,"nodeDisplayName");function vo(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 fl(i.title,t)??n}return n}s(vo,"taskDisplayName");function Ue(e,n,t){let r=[];switch(n.scope){case"env":r.push(pr(n.key)?fy(n.key)[t]:al(e,n.key)?.label[t]??n.key);break;case"derived":r.push(fl(pl(e,n.key)?.label,t)??n.key);break;case"task":r.push(vo(e,n.owner,t),fl(pl(e,n.key)?.label,t)??n.key);break;case"node":{r.push(Oe(e,n.owner,t));let i=e.nodes.find(a=>a.id===n.owner),o=i===void 0?void 0:Dr(e,i).find(a=>a.address.scope==="node"&&a.address.key===n.key);r.push(fl(o?.label,t)??n.key);break}}return n.scope!=="env"&&n.path!==void 0&&r.push(n.path),`${r.join(" \u203A ")} (${se(n)})`}s(Ue,"displayAddress");var yl=["beneficiary","signers"];function LI(e,n){return Array.isArray(e.artifacts)&&e.artifacts.some(t=>t?.key===n)}s(LI,"ownsSlot");function wl(e){let n=[];for(let[t,r]of Object.entries(Vn(e.inputs)??{})){let i=Vn(r);i?.kind==="binding"&&we(i.address)&&n.push({slot:t,address:i.address})}return n}s(wl,"bindingAddresses");function MI(e,n){return wl(e).find(t=>t.slot===n)?.address??null}s(MI,"bindingAddressAt");function qI(e,n){let t=s(i=>i.scope==="node"&&i.owner===n||i.scope==="task"&&Fr(e,i.owner,i.key)===n,"names");return[...e.nodes.filter(i=>i.id!==n).flatMap(i=>gl(i,{slotTypes:!1})),...gf(e)].flatMap(i=>$s(i).filter(t).map(o=>({at:i.at,nodeId:i.nodeId,address:o})))}s(qI,"addressesNaming");var In={target:"target",flagKey:"flagKey",value:"value"};function YG(e){return MI(e,In.target)}s(YG,"setFlagTarget");function KI(e){let n=YG(e);return n!==null&&wr(n)?n.owner:null}s(KI,"setFlagTargetOwner");function wf(e){let n=e.inputs?.[In.flagKey];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(wf,"setFlagKey");function jI(e){let n=e.inputs?.[In.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)}": \`${In.value}\` is no yes/no literal \u2014 publish refuses that`)}s(jI,"setFlagValue");function BI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(BI,"isObject");var UI=["target","flagKey","value"];function VI(e){return BI(e)&&e.type==="setFlag"&&UI.some(n=>n in e)}s(VI,"oldShape");function GI(e){return(e?.nodes??[]).some(VI)}s(GI,"needsSetFlagInputMove");function HG(e){let n=BI(e.inputs)?{...e.inputs}:{};if(UI.some(a=>a in e&&In[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[In.target]={kind:"binding",address:t}),typeof r=="string"&&r.length>0&&(n[In.flagKey]={kind:"literal",value:r}),i!==void 0&&(n[In.value]={kind:"literal",value:i}),{node:{...o,inputs:n}}}s(HG,"moveNode");function zI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!VI(i))return i;let o=HG(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(zI,"moveSetFlagConfigToInputs");function WI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(WI,"isObject");var wy={countersign:{dueInDays:"number"},decision:{allowSkipInTest:"boolean"},completenessCheck:{guestRole:"string"},governedDocument:{responseDueInDays:"number"}},ky={review:["allowSkipInTest"]};function YI(e){return wy[String(e)]??{}}s(YI,"movesOf");function HI(e){return ky[String(e)]??[]}s(HI,"deadOf");function JI(e){return WI(e)&&[...Object.keys(YI(e.type)),...HI(e.type)].some(n=>n in e)}s(JI,"oldShape");function QI(e){return(e?.nodes??[]).some(JI)}s(QI,"needsScalarInputMove");function JG(e,n){return n==="number"?typeof e=="number"&&Number.isInteger(e)&&e>=1:typeof e===n}s(JG,"wellTyped");function QG(e){let n=WI(e.inputs)?{...e.inputs}:{},t={...e};for(let[r,i]of Object.entries(YI(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==="")&&!JG(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 HI(e.type))delete t[r];return t.inputs=n,{node:t}}s(QG,"moveNode");function ZI(e){let n=[],t=[],r=e.nodes.map(i=>{if(!JI(i))return i;let o=QG(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(ZI,"moveScalarConfigToInputs");var Rs={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 kf(e){return typeof e=="string"&&Object.hasOwn(Rs,e)}s(kf,"isResourceType");var Wle=Object.keys(Rs).filter(e=>Rs[e].existence.check==="generic");function XI(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||wo(n.reduction)===null&&n.reduction.kind==="amount")&&Object.keys(n).every(t=>t==="groupKey"||t==="grantKeys"||t==="reduction")}s(XI,"isPricedGroupValue");var by=["street","hausnr","plz","ort","land"];function eO(e){return by.includes(e)}s(eO,"isAddressPart");var ZG=["municipality","municipalityKey","district","districtKey"],vy=[...by,...ZG],xy={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"},Is=Object.keys(xy);function _i(e){return typeof e=="string"&&e in xy}s(_i,"isValueType");function xt(e){return e===void 0?void 0:xy[e]}s(xt,"dataTypeOf");function bf(e,n){let t=xt(e),r=xt(n);return t!==void 0&&t===r}s(bf,"valueTypesCompatible");function vf(e){return e===null?"null is not a text in both languages":kl(e,{type:"localizedText"})}s(vf,"completeLocalizedTextIssue");function kl(e,n){if(kf(n.type)&&!_i(n.type))return typeof e=="string"&&e.length>0?null:`${JSON.stringify(e)} is not a ${n.type} key`;let t=xt(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")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 XI(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 ll(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=wo(e);return o===null?null:`${r} is not a reduction \u2014 ${o.en}`}}}s(kl,"literalTypeIssue");function nO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(nO,"isObject");var XG={collectPayment:{reason:"reason"}},ez={governedDocument:["mockAutoProduce"]},tO={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 Sy(e){return XG[String(e)]??{}}s(Sy,"movesOf");function rO(e){return ez[String(e)]??[]}s(rO,"deadOf");function iO(e){return nO(e)&&[...Object.keys(Sy(e.type)),...rO(e.type)].some(n=>n in e)}s(iO,"oldShape");function oO(e){return(e?.nodes??[]).some(iO)}s(oO,"needsNodeConfigInputMove");function nz(e){return vf(e)===null}s(nz,"isCompleteText");function tz(e){let n=nO(e.inputs)?{...e.inputs}:{},t={...e};for(let[r,i]of Object.entries(Sy(e.type)))if(r in e){if(i in n)return{unmoved:{nodeId:String(e.id),key:r,reason:"inputExists"}};if(!nz(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 rO(e.type))delete t[r];return Object.keys(Sy(e.type)).some(r=>r in e)&&(t.inputs=n),{node:t}}s(tz,"moveNode");function sO(e){let n=[],t=[],r=e.nodes.map(i=>{if(!iO(i))return i;let o=tz(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(sO,"moveNodeConfigToInputs");var Ay="collectPayment",Os=["online","separate"];function xf(e){return Os.includes(e)}s(xf,"isCollectPaymentSettlement");var Ps="paid",Ey="skipPayment",Ni="article",Ht="settlement",Ci="reason",Jt="payee",Ty=["one_time"];function Sf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Sf,"isObject");function aO(e){if(!Sf(e)||e.type!==Ay)return!1;let n=Sf(e.inputs)?e.inputs:{},t=n[Ht];return!Sf(t)||t.kind!=="literal"||t.value!=="online"?!1:!(Jt in n)}s(aO,"isOnlinePaymentWithoutPayee");function lO(e){return(e?.nodes??[]).some(aO)}s(lO,"needsPayee");function dO(e,n={}){let t=[],r=[],i=e.nodes.map(o=>{if(!aO(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=Sf(o.inputs)?o.inputs:{};return{...o,inputs:{...d,[Jt]:{kind:"literal",value:l}}}});return t.length===0?{graph:e,set:t,refused:r}:{graph:{...e,nodes:i},set:t,refused:r}}s(dO,"setPayeeOnOnlinePayments");function Af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Af,"isObject");function $y(e){return Af(e)&&Af(e.assign)&&"userId"in e.assign}s($y,"namesUser");function Ef(e){return(e?.nodes??[]).flatMap(n=>Af(n)&&Array.isArray(n.tasks)?n.tasks.filter($y).map(t=>({nodeId:String(n.id),taskKey:String(t.key),hasTeam:typeof t.assign.group=="string"&&t.assign.group.length>0})):[])}s(Ef,"taskUserAssignments");function cO(e){let n=Ef(e);if(n.length===0)return{graph:e,dropped:n};let t=e.nodes.map(r=>{if(!Af(r)||!Array.isArray(r.tasks)||!r.tasks.some($y))return r;let i=r.tasks.map(o=>{if(!$y(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(cO,"dropTaskAssignUserIds");var _s={"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"}},"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"}},"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"}}},Ry=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,"record");function uO(e,n){if(typeof n!="string"||n.length===0)return null;if(e==="key")return n;let t=Ss(n);return t?.kind==="team"?t.groupKey:null}s(uO,"decodeKey");function rz(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(rz,"locate");function Tf(e){let n=[],t=e;for(let[r,i]of Object.entries(Ry(t.assign)??{})){let o=uO("key",i);n.push({path:`assign.${r}`,leaf:"assign{}",owner:r,key:o,missing:typeof i!="string"||i.length===0})}for(let r of Object.keys(_s)){if(r==="assign{}")continue;let i=_s[r],{list:o,field:a,key:l}=rz(r);for(let d of Array.isArray(t[o])?t[o]:[]){let c=Ry(d);if(c===null||typeof c.key!="string")continue;let f=(a===null?c:Ry(c[a]))?.[l];if(f===void 0&&!i.required)continue;let m=typeof f!="string"||f.length===0;n.push({path:`${o}.${c.key}${a===null?"":`.${a}`}.${l}`,leaf:r,owner:c.key,key:uO(i.codec,f),missing:m})}}return n}s(Tf,"nodeResourceReferences");var fO=s(e=>(e??[]).map(n=>`\u201E${n}\u201C`).join(", "),"list"),pO=s(e=>(e??[]).map(n=>`"${n}"`).join(", "),"listEn"),iz={"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 (${fO(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 (${pO(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/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 (${fO(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 (${pO(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 Ns(e,n,t){let{problem:r,remedy:i}=iz[e][t](n);return`[${e}] ${r} ${i}`}s(Ns,"addressMessage");function _t(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(_t,"derivedEdges");function $f(e,n,t){if(n===t)return!0;let r=new Map,i=new Set;for(let l of _t(e.nodes)){let d=r.get(l.source)??[];d.push(l.target),r.set(l.source,d),i.add(l.target)}let 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($f,"dominates");function mO(e,n,t){if(n===t)return!0;let r=new Map;for(let a of _t(e.nodes)){let l=r.get(a.source)??[];l.push(a.target),r.set(a.source,l)}let 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(mO,"reaches");function Iy(e,n){let t=[],r=s(a=>({address:a.address,type:a.type,...a.label!==void 0?{label:a.label}:{},nodeId:a.nodeId}),"toVisible");for(let a of e.nodes)if($f(e,a.id,n))for(let l of Dr(e,a))t.push(r(l));for(let a of II)t.push({address:{scope:"env",key:a},type:uy(a),label:fy(a),nodeId:null});for(let a of tf(e))t.push({address:{scope:"env",key:rf(a.key)},type:a.type,label:a.label,nodeId:null});let i=new Set(t.map(a=>se(a.address))),o=(Array.isArray(e.processStore)?e.processStore:[]).filter(a=>a.derive!==void 0);for(let a=!0;a;){a=!1;for(let l of o){let d=se({scope:"derived",key:l.key});if(i.has(d))continue;let c=ml(e,l.key);c===null||!c.every(u=>i.has(se(hf(u))))||(t.push({address:{scope:"derived",key:l.key},type:l.type,label:l.label,nodeId:null}),i.add(d),a=!0)}}return t}s(Iy,"visibleAddressesAt");function ii(e,n){let t=e?.readinessFormFieldsByFormNode?.get(n.owner);if(t!==void 0)return t.get(n.path)??null}s(ii,"formFieldEntryOf");var hO={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"},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"},reduction:{de:"Erm\xE4\xDFigung des Preises",en:"Reduction of the price"},pricingRule:{de:"Preisregel",en:"Pricing rule"}},oz=new Set(["nodeReads","requires","taskReads","taskDocument","familyRequestFields"]);function sz(e,n,t){let r=[];n.taskKey!==void 0&&r.push(`${t==="de"?"Aufgabe":"task"} \u201E${vo(e,n.taskKey,t)}\u201C`);let i=n.kind==="binding"?` \u201E${n.at.split(".").pop()}\u201C`:"";return r.push(`${hO[n.kind][t]}${i}`),r.join(" \u203A ")}s(sz,"addressFieldWhere");function bl(e,n,t){let r=sz(e,n,t);return n.nodeId===null?r:`\u201E${Oe(e,n.nodeId,t)}\u201C \u203A ${r}`}s(bl,"whereOf");function gO(e,n,t){if(n.scope==="node")return Oe(e,n.owner,t);if(n.scope==="task")return vo(e,n.owner,t)}s(gO,"producerName");function yO(e,n){let t=[],r=new Set,i=s((l,d,c)=>{let u={de:Ns(l,c("de"),"de"),en:Ns(l,c("en"),"en")},f=`${d}|${u.de}`;r.has(f)||(r.add(f),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=>gl(l)),...gf(e)];for(let l of a){let d=s(c=>bl(e,l,c),"where");for(let c of az(e,l,i))dz(e,l,c,i)&&(uz(e,l,c,n,i),my.has(l.kind)&&!pz(o,c)&&i("address/notFormInstance",l.at,u=>({where:d(u),address:Ue(e,c,u)})))}return mz(e,i),hz(e,a,i),kz(e,i),vz(e,i),t}s(yO,"checkAddresses");function az(e,n,t){let r=s(i=>bl(e,n,i),"where");if(hy(n)){let i=yf(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 $s(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(az,"checkFieldShape");function wO(e,n,t,r){let i=gO(e,t,r);return{where:bl(e,n,r),address:Ue(e,t,r),...i!==void 0?{producer:i}:{}}}s(wO,"addressParams");function lz(e,n,t){return cy(n)?null:al(e,n)!==void 0?t==="condition"||t==="binding"?null:"address/staffInputConditionOnly":pr(n)?"address/envCohortBound":"address/unknownKey"}s(lz,"envAddressRefusal");function dz(e,n,t,r){let i=s(o=>wO(e,n,t,o),"params");switch(t.scope){case"env":{let o=lz(e,t.key,n.kind);return o===null?!0:(r(o,n.at,i),!1)}case"derived":return(e.processStore??[]).find(a=>a.key===t.key)?.derive!==void 0?!0:(r("address/unknownKey",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&&a.derive===void 0)?Fr(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):Dr(e,o).some(a=>a.address.scope==="node"&&a.address.key===t.key)?!0:(r(my.has(n.kind)&&vt(o)?"address/notFormInstance":"address/unknownKey",n.at,i),!1)}}}s(dz,"resolves");function cz(e,n){return e===void 0||n===void 0||xt(n)===void 0?!0:xt(e)!==void 0&&bf(e,n)}s(cz,"addressTypeFits");function uz(e,n,t,r,i){let o=s(l=>wO(e,n,t,l),"params");if(t.scope!=="env"&&t.path!==void 0&&!fz(e,n,t,r)){i("address/pathNotInTarget",n.at,o);return}if(n.expectedType===void 0)return;let a=yy(e,t);cz(a,n.expectedType)||i("address/typeMismatch",n.at,l=>({...o(l),expected:n.expectedType,actual:a}))}s(uz,"checkPathAndType");function fz(e,n,t,r){if(t.scope!=="node")return!1;if(yy(e,t)!==void 0)return!0;if(t.key!==it)return!1;if(!oz.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(fz,"pathExists");function pz(e,n){if(!wr(n))return!1;let t=e.get(n.owner);return t!==void 0&&t.type==="form"&&!vt(t)}s(pz,"isCreatingFormInstance");function mz(e,n){for(let t of e.nodes){let r=new Set(gl(t).map(i=>i.kind));for(let i of NI(t))r.has(i)||n("address/missing",`nodes.${t.id}.${i}`,o=>({where:`\u201E${Oe(e,t.id,o)}\u201C \u203A ${hO[i][o]}`}))}}s(mz,"checkRequiredFields");function hz(e,n,t){let r=new Map;for(let i of n)if(i.judgedTogether!==null)for(let o of $s(i)){if(o.scope!=="node"||o.key!==it)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:bl(e,o[0].field,l),names:a.map(d=>Oe(e,d,l))}))}}s(hz,"checkMixedForms");function gz(e,n){return e.type==="engagePush"&&n.kind==="payment"}s(gz,"readSkipsAbsentProducer");function yz(e,n,t){return n!==t&&mO(e,n,t)}s(yz,"precedesOnSomePath");function wz(e,n,t,r){let i=hf(t.address);return r.has(se(i))||!bz(e,i)?!0:t.origin==="written"&&i.scope==="node"&&gz(n,t.field)&&yz(e,i.owner,n.id)}s(wz,"readPassesVisibility");function kz(e,n){for(let t of e.nodes){let r=bo(e,t);if(r.length===0)continue;let i=new Set(Iy(e,t.id).map(o=>se(o.address)));for(let o of r){let a=hf(o.address);if(wz(e,t,o,i))continue;let l=a.scope==="task"?Fr(e,a.owner,a.key):a.scope==="node"?a.owner:null;n("address/notVisible",o.field.at,d=>({where:bl(e,o.field,d),address:Ue(e,o.address,d),producer:gO(e,a,d)??Ue(e,a,d),...l!==null?{producerNode:Oe(e,l,d)}:{},reader:Oe(e,t.id,d)}))}}}s(kz,"checkVisibility");function bz(e,n){if(n.scope==="env")return cy(n.key);if(n.scope==="derived")return ml(e,n.key)!==null;let t=se(n);return e.nodes.some(r=>Dr(e,r).some(i=>se(i.address)===t))}s(bz,"producedSomewhere");function vz(e,n){let t=new Map;for(let r of e.nodes){let i=new Set(Dr(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"||!Nr.test(l)){n("workItems/keyFormat",`nodes.${r.id}.tasks.${o}.key`,c=>({where:`\u201E${Oe(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${Oe(e,o.nodeId,a)}\u201C \u203A ${a==="de"?"Aufgabe":"task"} \u201E${vo(e,r,a)}\u201C`,names:i.map(l=>Oe(e,l.nodeId,a))}))}s(vz,"checkTaskKeys");function Rf(e,n){return e.label[n]??""}s(Rf,"wordingIn");function Di(e,n){let t=kO(e,n),r=Rf(e.qualifier,n);return t===""||r===""&&Rf(e.qualifier,"de")!==""?"":r===""?t:`${r} \xB7 ${t}`}s(Di,"fieldLabelIn");function kO(e,n){return Rf(e,n)}s(kO,"fieldOwnLabelIn");function Cs(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:Di(e,"de"),en:Di(e,"en")}}}s(Cs,"catalogField");function Ds(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(Ds,"catalogFieldRefusal");function If(e,n){let t=e.buses.find(r=>r.key===n);return t||F(`[progress] layout '${e.id}' has no bus '${n}'`),t}s(If,"progressBus");function vl(e,n){return e.states.some(t=>t.id===n)}s(vl,"isBusState");function bO(e,n){let t=e.terminalSemantics?.[n];return t||F(`[progress] no terminal semantics for state '${n}' on bus '${e.key}'`),t}s(bO,"terminalSemantics");function Of(e,n){return!!e.terminalSemantics&&Object.prototype.hasOwnProperty.call(e.terminalSemantics,n)}s(Of,"hasTerminalSemantics");function xz(e,n){return(e.boards??[]).find(t=>t.audience===n||t.audience==="both")??null}s(xz,"boardForAudience");function vO(e){return xz(If(e,"process"),"internal")}s(vO,"internalProcessBoard");function Fs(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(Fs,"resolveProgressEvent");var Ls={approved:"enrolled",rejected:"declined",withdrawn:"declined",expired:"declined"},oi=Object.keys(Ls);function xo(e){return Object.hasOwn(Ls,e)}s(xo,"isEndNodeOutcome");var Oy={approved:{de:"Angenommen",en:"Admitted"},rejected:{de:"Abgelehnt",en:"Rejected"},withdrawn:{de:"Zur\xFCckgezogen",en:"Withdrawn"},expired:{de:"Abgelaufen",en:"Expired"}};var Fi=["commit","discard"],Vde=w.union(...Fi.map(e=>w.literal(e)));function Pf(e){return typeof e=="string"&&Fi.includes(e)}s(Pf,"isApplicationDataDecision");function Dn(e){return Object.keys(e)}s(Dn,"progressEventsOf");var te=s((e,n)=>({de:e,en:n}),"lt"),en=s((e,n,t,r,i=null,o=null)=>({chipLabel:e,tone:n,nextAction:i,affordance:o,title:t,body:r}),"ex"),xO={key:"eingeschrieben",label:te("Eingeschrieben","Enrolled"),scope:"global",defaultCollapsed:!0},_f={key:"abgesagt",label:te("Abgesagt","Declined"),scope:"global",track:"exit",defaultCollapsed:!0},SO={key:"abgelehnt",label:te("Abgelehnt","Rejected"),scope:"global",track:"exit",defaultCollapsed:!0};var AO={enrolled:{label:te("Eingeschrieben","Enrolled"),tone:"green",terminal:{lifecycleStatus:"completed",outcome:"approved"},phase:xO,external:en(te("Eingeschrieben","Enrolled"),"green",te("Sie sind eingeschrieben!","You are enrolled!"),te("Ihre Anmeldung ist abgeschlossen und Ihr Platz ist gesichert. Wir freuen uns auf Sie.","Your enrolment is complete and your place is secured. We look forward to welcoming you."))},declined:{label:te("Abgesagt","Declined"),tone:"red",terminal:{lifecycleStatus:"completed",outcome:"rejected"},phase:_f,external:en(te("Abgesagt","Declined"),"red",te("Die Bewerbung wurde beendet","The application has ended"),te("Ihre Bewerbung wurde nicht fortgef\xFChrt.","Your application was not continued."))}},EO={role:"effect",effect:"pure",progressDefaults:AO,progressEvents:Dn(AO),inputs:s(()=>[{id:"applicationOutcome",label:{de:"Ergebnis",en:"Outcome"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:oi.map(e=>({value:e,label:Oy[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=>[...Sz(e),...Az(e),...Ez(e)],"validate")},Ms=s((e,n,t,r)=>({layer:"GRAPH",kind:"nodeRule",path:`node.${e.id}.inputs.${n}`,reason:{de:t,en:r},severity:"error"}),"nodeIssue");function xl(e){let n=e.inputs?.applicationOutcome;return n?.kind==="literal"&&n.value!=null?String(n.value):null}s(xl,"literalOutcome");function Sz(e){if(e.type!=="end")return[];let n=e.inputs?.applicationOutcome;if(n===void 0||n.kind==="unset")return[];let t=xl(e);return t===null?[Ms(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`)]:xo(t)?[]:[Ms(e,"applicationOutcome",`[end/applicationOutcome] ${e.label.de}: '${t}' ist kein Ausgang eines Endknotens (${oi.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 (${oi.join("|")}) \u2014 the waitlist ends through the closed outcome of its waitlist node`)]}s(Sz,"checkEndApplicationOutcome");function Az(e){if(e.type!=="end")return[];let n=e.inputs?.dataDecision;return!n||n.kind!=="literal"||n.value==null?[Ms(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)`)]:Pf(n.value)?[]:[Ms(e,"dataDecision",`[end/dataDecision] ${e.label.de}: dataDecision '${String(n.value)}' ist ung\xFCltig (${Fi.join("|")})`,`[end/dataDecision] ${e.label.en}: dataDecision '${String(n.value)}' is invalid (${Fi.join("|")})`)]}s(Az,"checkEndDataDecision");function Ez(e){if(e.type!=="end")return[];let n=xl(e);if(n===null||!xo(n)||n==="approved")return[];let t=e.inputs?.dataDecision;if(t?.kind!=="literal"||t.value!=="commit")return[];let r=Oy[n];return[{...Ms(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(Ez,"checkEndCommitWithoutApproval");function TO(e,n){if(!n?.layout||!n.wiring)return[];let t=[];for(let r of e.nodes){if(r.type!=="end")continue;let i=xl(r);if(i===null||!xo(i))continue;let o=Ls[i],a=Fs(n.wiring,r,o);if(a===null)continue;let l=n.layout.buses.find(c=>c.key===a.bus);if(l===void 0||!Of(l,a.state))continue;let d=bO(l,a.state).outcome;d!==i&&t.push(Ms(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(TO,"checkEndOutcomeMatchesTerminal");function qs(e){let n=He(e);return typeof n.inputs=="function"?n.inputs(e):[]}s(qs,"inputSlots");function Tz(e,n){return qs(e).find(t=>t.id===n)}s(Tz,"findInputSlot");function $z(e,n){let t=Tz(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($z,"resolveInput");function $O(e){return qs(e).filter(n=>$z(e,n.id).source==="missing")}s($O,"missingRequiredInputs");var Rz=["personRef","formRef","documentRef","docRef"];function Iz(e){let n=He(e);return typeof n.inputs!="function"?[]:n.inputs(e).map(t=>({id:t.id,type:t.type}))}s(Iz,"listInputs");function RO(e){let n=[];for(let t of e.nodes)for(let r of Iz(t))!Rz.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(RO,"findParamValueRefSlotErrors");function IO(e){let n=[];for(let t of e.nodes){let r=He(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(IO,"findInspectorKindErrors");function OO(e){let n=[];for(let t of e.nodes)for(let r of $O(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(OO,"findMissingRequiredInputs");function Nf(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(Nf,"processStoreKeys");function _O(e){let n=[];for(let t of e.tasks??[]){let r=t.result;if(!(r===void 0||!xs(r)))for(let i of ff(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(_O,"storeWritersOn");function NO(e){let n=new Map;for(let t of e.nodes)for(let r of _O(t)){let i=n.get(r.key)??[];i.push(r),n.set(r.key,i)}return n}s(NO,"processStoreWriters");function Oz(e,n,t){for(let r of e.nodes){let i=_O(r).find(o=>o.taskKey===n&&o.key===t);if(i!==void 0)return i}return null}s(Oz,"writerAt");function PO(e,n,t){(n.scope!=="task"||n.path!==void 0)&&F(`[process] ${t}: ${se(n)} is no task value`);let r=Oz(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(PO,"sourceOfAddress");function Py(e,n){(n.scope!=="task"&&n.scope!=="derived"||n.path!==void 0)&&F(`[process] ${se(n)} is no store address`);let t=Nf(e).find(o=>o.key===n.key);t===void 0&&F(`[address/unknownKey] ${se(n)}: "${n.key}" is not declared in processStore`);let r={key:t.key,type:t.type,label:t.label,audience:t.audience};if(n.scope==="task")return sy(t)&&F(`[address/unknownKey] ${se(n)}: "${n.key}" is a derived price \u2014 read it as $derived`),{...r,sources:[PO(e,n,se(n))]};sy(t)||F(`[address/unknownKey] ${se(n)}: "${n.key}" is a written value \u2014 read it as $task`);let i=ay(e,t.derive).map(o=>PO(e,o.address,se(n)));return{...r,sources:i,derive:t.derive}}s(Py,"processLeafOf");var _y=new Set(["enum","pricedItem","number","boolean","reduction"]),Ny=new Set(["pricedItem","pricedGroup"]),Cy=new Set(["number","boolean","enum"]),Fe={invalidKey:"[process/invalidKey]",unknownKey:"[process/unknownKey]",secondWriter:"[process/secondWriter]",noWriter:"[process/noWriter]",writerTypeMismatch:"[process/writerTypeMismatch]",pricedItemWritesNothing:"[process/pricedItemWritesNothing]",ruleSet:"[process/ruleSet]",ruleCondition:"[process/ruleCondition]",ruleSource:"[process/ruleSource]",ruleReadsAbsent:"[process/ruleReadsAbsent]",absentValue:"[process/absentValue]",derive:"[process/derive]",derivedHasWriter:"[process/derivedHasWriter]",ruleGrantUnknown:"[process/ruleGrantUnknown]",ruleGrantUnused:"[process/ruleGrantUnused]",derivePriceUnknown:"[process/derivePriceUnknown]",derivePriceNotInProgram:"[process/derivePriceNotInProgram]",derivePriceOfferWithoutProgram:"[process/derivePriceOfferWithoutProgram]",deriveStageUnknown:"[process/deriveStageUnknown]",deriveStageUncovered:"[process/deriveStageUncovered]",reductionPrices:"[process/reductionPrices]",internalInDocument:"[process/internalInDocument]",writerMustBlock:"[process/writerMustBlock]",absentWithoutDefault:"[process/absentWithoutDefault]",defaultItemMismatch:"[process/defaultItemMismatch]"};function Le(e,n,t,r){return{layer:"GRAPH",kind:"contractGap",path:e,reason:{de:`${n} ${t}`,en:`${n} ${r}`},severity:"error"}}s(Le,"err");function CO(e,n={}){let t=[],r=Nf(e),i=new Map(r.map(d=>[d.key,d])),o=new Set;for(let[d,c]of r.entries()){let u=`processStore[${d}]`;if(typeof c.key!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(c.key)){t.push(Le(u,Fe.invalidKey,`Vorgangs-Schl\xFCssel ${JSON.stringify(c.key)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,`Process key ${JSON.stringify(c.key)} \u2014 letters, digits and _ are allowed, starting with a lowercase letter.`));continue}o.has(c.key)&&t.push(Le(u,Fe.invalidKey,`Vorgangs-Schl\xFCssel "${c.key}" ist doppelt deklariert.`,`Process key "${c.key}" is declared twice.`)),o.add(c.key),(c.derive!==void 0?!Ny.has(c.type):!_y.has(c.type))&&t.push(c.derive!==void 0?Le(u,Fe.derive,`Vorgangs-Schl\xFCssel "${c.key}" ist abgeleitet, hat aber den Typ "${c.type}" \u2014 abgeleitet wird nur ein Preis: ${[...Ny].join(", ")}.`,`Process key "${c.key}" is derived but has the type "${c.type}" \u2014 only a price can be derived: ${[...Ny].join(", ")}.`):Le(u,Fe.invalidKey,`Vorgangs-Schl\xFCssel "${c.key}" hat den Typ "${c.type}" \u2014 der Vorgang speichert nur Ergebnisse mit Wert: ${[..._y].join(", ")}${c.type==="pricedGroup"?" (ein Paket wird abgeleitet: derive)":""}.`,`Process key "${c.key}" has the type "${c.type}" \u2014 the process only stores results with a value: ${[..._y].join(", ")}${c.type==="pricedGroup"?" (a package is derived: derive)":""}.`)),(!c.label?.de?.trim()||!c.label?.en?.trim())&&t.push(Le(u,Fe.invalidKey,`Vorgangs-Schl\xFCssel "${c.key}" braucht ein Label in beiden Sprachen.`,`Process key "${c.key}" needs a label in both languages.`)),c.audience!=="internal"&&c.audience!=="printable"&&t.push(Le(u,Fe.invalidKey,`Vorgangs-Schl\xFCssel "${c.key}": audience muss 'internal' oder 'printable' sein.`,`Process key "${c.key}": audience must be 'internal' or 'printable'.`))}let a=NO(e);for(let d of e.nodes)for(let c of d.tasks??[]){let u=c.result;u?.kind==="pricedItem"&&u.writes===void 0&&t.push(Le(`node.${d.id}.tasks.${c.key}.result.writes`,Fe.pricedItemWritesNothing,`Aufgabe "${c.key}" (Knoten "${d.id}") bepreist einen Artikel, schreibt das Ergebnis aber in keinen Vorgangs-Schl\xFCssel ('result.writes') \u2014 niemand k\xF6nnte den Preis lesen.`,`Task "${c.key}" (node "${d.id}") prices an article but writes the result to no process key ('result.writes') \u2014 nobody could read the price.`))}for(let[d,c]of a){let u=i.get(d);for(let f of c){let m=f.fieldKey===void 0?`node.${f.nodeId}.tasks.${f.taskKey}.result.writes`:`node.${f.nodeId}.tasks.${f.taskKey}.result.fields.${f.fieldKey}.writes`;if(u===void 0){t.push(Le(m,Fe.unknownKey,`${f.fieldKey===void 0?"":`Feld "${f.fieldKey}" der `}Aufgabe "${f.taskKey}" schreibt "${d}", aber der Workflow deklariert keinen solchen Vorgangs-Schl\xFCssel (graph.processStore).`,`${f.fieldKey===void 0?"Task":`Field "${f.fieldKey}" of task`} "${f.taskKey}" writes "${d}", but the workflow declares no such process key (graph.processStore).`));continue}if(f.valueType!==u.type){let y=f.fieldKey===void 0?`Aufgabe "${f.taskKey}"`:`Feld "${f.fieldKey}" der Aufgabe "${f.taskKey}"`,k=f.fieldKey===void 0?`Task "${f.taskKey}"`:`Field "${f.fieldKey}" of task "${f.taskKey}"`;t.push(Le(m,Fe.writerTypeMismatch,`${y} liefert ${f.valueType}, der Vorgangs-Schl\xFCssel "${d}" ist aber als ${u.type} deklariert.`,`${k} delivers ${f.valueType}, but the process key "${d}" is declared as ${u.type}.`))}}if(c.length>1){let f=c.map(m=>`${m.nodeId}/${m.taskKey}${m.fieldKey===void 0?"":`.${m.fieldKey}`}`).join(", ");t.push(Le(`processStore.${d}`,Fe.secondWriter,`Vorgangs-Schl\xFCssel "${d}" wird ${c.length}-mal geschrieben (${f}) \u2014 genau ein Schreiber je Schl\xFCssel.`,`Process key "${d}" is written ${c.length} times (${f}) \u2014 exactly one writer per key.`))}}for(let d of r){if(d.derive!==void 0){if(a.has(d.key)){let c=a.get(d.key).map(u=>`${u.nodeId}/${u.taskKey}`).join(", ");t.push(Le(`processStore.${d.key}`,Fe.derivedHasWriter,`Vorgangs-Schl\xFCssel "${d.key}" wird abgeleitet (derive) \u2014 keine Aufgabe darf ihn schreiben (${c}).`,`Process key "${d.key}" is derived (derive) \u2014 no task may write it (${c}).`))}continue}a.has(d.key)||t.push(Le(`processStore.${d.key}`,Fe.noWriter,`Vorgangs-Schl\xFCssel "${d.key}" ist deklariert, aber keine Aufgabe schreibt ihn ('result.writes').`,`Process key "${d.key}" is declared, but no task writes it ('result.writes').`))}t.push(...Pz(e,r,a,n));let l=new Map;for(let d of e.nodes){let c=He(d),u=typeof c.inputs=="function"?c.inputs(d):[];for(let f of u){let m=d.inputs?.[f.id];if(m?.kind!=="binding")continue;let y=_z(e,m.address);if(y===null)continue;let k=`node.${d.id}.input.${f.id}`,g=se(m.address);for(let A of y.sources){let $=l.get(A.key)??new Set;$.add(d.id),l.set(A.key,$)}if(y.audience==="internal"&&t.push(Le(k,Fe.internalInDocument,`${d.label.de}: "${f.id}" liest den internen Vorgangs-Schl\xFCssel "${y.key}" \u2014 ein Dokument dieses Knotens geht an die Familie; nur 'printable'-Schl\xFCssel d\xFCrfen hinein.`,`${d.label.en}: "${f.id}" reads the internal process key "${y.key}" \u2014 a document of this node goes to the family; only 'printable' keys may go in.`)),y.derive!==void 0)continue;let b=Nz(a,y.sources[0].key,y.sources[0].taskKey);if(b.template.when!==void 0&&f.required===!0&&f.defaultValue===void 0&&t.push(Le(k,Fe.absentWithoutDefault,`${d.label.de}: "${f.id}" ist Pflicht und an ${g} gebunden, aber die schreibende Aufgabe entsteht nur unter einer Bedingung (when: ${Cf(b.template.when)}) \u2014 ohne Vorgabewert bliebe das Feld dann f\xFCr immer leer.`,`${d.label.en}: "${f.id}" is required and bound to ${g}, but the writing task only exists under a condition (when: ${Cf(b.template.when)}) \u2014 without a default value the field would stay empty forever.`)),b.result.kind==="pricedItem"&&f.defaultValue!==void 0){let A=f.defaultValue;(!Ii(A)||A.itemKey!==b.result.item||A.grantKeys.length>0)&&t.push(Le(k,Fe.defaultItemMismatch,`${d.label.de}: der Vorgabewert von "${f.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.`,`${d.label.en}: the default value of "${f.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[d,c]of l){let u=a.get(d)[0],f=u.template.blocks,m=f===void 0?void 0:f.node??u.nodeId,y=m!==void 0&&c.has(m)&&(()=>{let g=e.nodes.find(b=>b.id===m);return g!==void 0&&He(g).processHoldTemplate?.(g)===f.templateKey})(),k=`node.${u.nodeId}.tasks.${u.taskKey}.blocks`;if(!y){let g=[...c][0],b=e.nodes.find($=>$.id===g),A=He(b).processHoldTemplate?.(b)??"?";t.push(Le(k,Fe.writerMustBlock,`Die Aufgabe "${u.taskKey}" schreibt "${d}", h\xE4lt aber keinen der lesenden Knoten (${[...c].join(", ")}) zur\xFCck \u2014 sie muss den ersten blockieren, z. B. blocks: { ${g===u.nodeId?"":`node: '${g}', `}templateKey: '${A}' }, sonst arbeitet er, bevor der Wert existiert.`,`The task "${u.taskKey}" writes "${d}" but holds back none of the reading nodes (${[...c].join(", ")}) \u2014 it must block the first one, e.g. blocks: { ${g===u.nodeId?"":`node: '${g}', `}templateKey: '${A}' }, otherwise it works before the value exists.`));continue}for(let g of c)g===m||$f(e,m,g)||t.push(Le(k,Fe.writerMustBlock,`"${g}" liest "${d}", liegt aber nicht hinter dem zur\xFCckgehaltenen Knoten "${m}" \u2014 auf einem Weg an ihm vorbei l\xE4se er den Wert, bevor er feststeht.`,`"${g}" reads "${d}" but does not lie behind the held-back node "${m}" \u2014 on a path past it, it would read the value before it is settled.`))}return t}s(CO,"processBindingIssues");function Pz(e,n,t,r){let i=[],o=new Map(n.map(u=>[u.key,u])),a=mf(e),l=new Set;for(let[u,f]of a.entries()){let m=`pricingRules[${u}]`;if((typeof f.key!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(f.key)||l.has(f.key))&&i.push(Le(m,Fe.ruleSet,`Regelgruppe ${JSON.stringify(f.key)} \u2014 ein eindeutiger Schl\xFCssel aus Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`,`Rule group ${JSON.stringify(f.key)} \u2014 a unique key of letters, digits and _, starting with a lowercase letter.`)),l.add(f.key),(!f.label?.de?.trim()||!f.label?.en?.trim())&&i.push(Le(m,Fe.ruleSet,`Regelgruppe "${f.key}" braucht ein Label in beiden Sprachen.`,`Rule group "${f.key}" needs a label in both languages.`)),!Array.isArray(f.rows)||f.rows.length===0){i.push(Le(m,Fe.ruleSet,`Regelgruppe "${f.key}" hat keine Zeilen.`,`Rule group "${f.key}" has no rows.`));continue}for(let[y,k]of f.rows.entries()){let g=`${m}.rows[${y}]`;(!Array.isArray(k.grants)||k.grants.length===0||k.grants.some(A=>typeof A!="string"||A.length===0))&&i.push(Le(g,Fe.ruleSet,`Regelgruppe "${f.key}", Zeile ${y+1}: nennt keine Rabattvorlage \u2014 eine Zeile ohne Rabatt ist die fehlende Zeile.`,`Rule group "${f.key}", row ${y+1}: names no discount template \u2014 a row without a discount is the missing row.`));let b=ul(k.when);if(b!==null){i.push(Le(g,Fe.ruleCondition,`Regelgruppe "${f.key}", Zeile ${y+1}: Bedingung ${JSON.stringify(k.when)} \u2014 ${b}.`,`Rule group "${f.key}", row ${y+1}: condition ${JSON.stringify(k.when)} \u2014 ${b==="leere Bedingung"?"empty condition":b}.`));continue}for(let{identifier:A,address:$}of py(k.when)){if($===null)continue;let O=Cz($,o,t);if(O==="ruleSource")i.push(Le(g,Fe.ruleSource,`Regelgruppe "${f.key}", Zeile ${y+1}: liest ${A} \u2014 eine Bedingung liest nur Werte, die eine Aufgabe schreibt ($task.<aufgabe>.<schl\xFCssel>), vom Typ ${[...Cy].join(", ")}.`,`Rule group "${f.key}", row ${y+1}: reads ${A} \u2014 a condition only reads values that a task writes ($task.<task>.<key>), of type ${[...Cy].join(", ")}.`));else if(O==="ruleReadsAbsent"){let E=t.get($.key).find(I=>I.taskKey===$.owner);i.push(Le(g,Fe.ruleReadsAbsent,`Regelgruppe "${f.key}" liest ${A}, dessen Aufgabe entfallen kann (${E.template.when!==void 0?`when: ${Cf(E.template.when)}`:"sie endet mit ihrem Knoten"}) \u2014 der Schl\xFCssel muss sagen, wof\xFCr er ohne Aufgabe steht ('absentValue'), sonst entschiede die Regel still \xFCber einen fehlenden Wert.`,`Rule group "${f.key}" reads ${A}, whose task can lapse (${E.template.when!==void 0?`when: ${Cf(E.template.when)}`:"it ends with its node"}) \u2014 the key must say what it stands for without a task ('absentValue'), otherwise the rule would silently decide on a missing value.`))}}}}for(let u of n){if(u.absentValue===void 0)continue;let f=`processStore.${u.key}.absentValue`;if(!(u.type==="number"&&typeof u.absentValue=="number"||u.type==="boolean"&&typeof u.absentValue=="boolean"||u.type==="enum"&&typeof u.absentValue=="string"&&u.absentValue.length>0)){i.push(Le(f,Fe.absentValue,`Vorgangs-Schl\xFCssel "${u.key}" (${u.type}): absentValue ${JSON.stringify(u.absentValue)} passt nicht zum Typ.`,`Process key "${u.key}" (${u.type}): absentValue ${JSON.stringify(u.absentValue)} does not fit the type.`));continue}let y=t.get(u.key)?.[0];y!==void 0&&!DO(y)&&i.push(Le(f,Fe.absentValue,`Vorgangs-Schl\xFCssel "${u.key}": seine Aufgabe ist immer geschuldet und \xFCberlebt ihren Knoten \u2014 ein absentValue w\xFCrde nie gelesen.`,`Process key "${u.key}": its task is always owed and outlives its node \u2014 an absentValue would never be read.`))}let d=[];for(let u of n){let f=u.derive;if(f===void 0)continue;let m=`processStore.${u.key}.derive`,y=u.type==="pricedGroup"?"group":"item",k=[f.item,f.group,f.byStage].filter(I=>I!==void 0).length,g=ly(f),b=f.byStage??[];(k!==1||g.length===0||g.length!==Math.max(b.length,1)||g.some(I=>I.kind!==y))&&i.push(Le(m,Fe.derive,`"${u.key}" (${u.type}) leitet ${y==="group"?"ein Paket ab: genau 'group' oder 'byStage' mit je einem 'group'":"einen Artikel ab: genau 'item' oder 'byStage' mit je einem 'item'"}.`,`"${u.key}" (${u.type}) derives ${y==="group"?"a package: exactly 'group' or 'byStage' with one 'group' each":"an article: exactly 'item' or 'byStage' with one 'item' each"}.`));let A=new Set;for(let[I,v]of b.entries()){if(!Array.isArray(v.stages)||v.stages.length===0){i.push(Le(`${m}.byStage[${I}]`,Fe.derive,`"${u.key}": die Zeile ${I+1} nennt keine Stufe.`,`"${u.key}": row ${I+1} names no stage.`));continue}for(let R of v.stages)A.has(R)&&i.push(Le(`${m}.byStage[${I}]`,Fe.derive,`"${u.key}": die Stufe "${R}" steht in mehr als einer Zeile \u2014 welcher Preis gilt, w\xE4re geraten.`,`"${u.key}": the stage "${R}" is in more than one row \u2014 which price applies would be a guess.`)),A.add(R)}let $=new Set;for(let I of f.rules??[]){let v=a.find(R=>R.key===I);if(v===void 0){i.push(Le(m,Fe.derive,`"${u.key}" nennt die Regelgruppe "${I}", die der Workflow nicht deklariert (bekannt: ${a.map(R=>R.key).join(", ")||"keine"}).`,`"${u.key}" names the rule group "${I}", which the workflow does not declare (known: ${a.map(R=>R.key).join(", ")||"none"}).`));continue}for(let R of v.rows??[])for(let K of R.grants??[])$.add(K)}let O=f.reduction;we(O)&&(Dz(O,o)||i.push(Le(m,Fe.derive,`"${u.key}": Reduktion ${se(O)} ist kein von einer Aufgabe geschriebener Wert vom Typ reduction ($task.<aufgabe>.<schl\xFCssel>).`,`"${u.key}": reduction ${se(O)} is not a value of type reduction written by a task ($task.<task>.<key>).`)));for(let I of g)d.push({key:u.key,target:I,grants:$}),(I.kind==="item"?r.billingItemKeys?.has(I.key):r.groupArticleKeys?.has(I.key))===!1?i.push(Le(m,Fe.derivePriceUnknown,`"${u.key}": ${I.kind==="item"?"der Artikel":"das Paket"} "${I.key}" ist nicht im Katalog des Mandanten.`,`"${u.key}": the ${I.kind==="item"?"article":"package"} "${I.key}" is not in the school's catalog.`)):r.offerProgram===null?i.push(Le(m,Fe.derivePriceOfferWithoutProgram,`"${u.key}": das Angebot ist keinem Programm zugeordnet, also geh\xF6rt ${I.kind==="item"?"kein Artikel":"kein Paket"} zu ihm; dem Angebot ein Programm geben.`,`"${u.key}": the offer is not assigned to a program, so no ${I.kind==="item"?"article":"package"} belongs to it; give the offer a program.`)):r.offerProgram!==void 0&&((I.kind==="item"?r.offerProgram.billingItemKeys:r.offerProgram.groupKeys).has(I.key)||i.push(Le(m,Fe.derivePriceNotInProgram,`"${u.key}": ${I.kind==="item"?"der Artikel":"das Paket"} "${I.key}" ist dem Programm \u201E${r.offerProgram.nameDe}\u201C des Angebots nicht zugeordnet${I.kind==="group"?" oder wird nicht angeboten":""} (unter Finanzen \u2192 Artikel zuordnen).`,`"${u.key}": the ${I.kind==="item"?"article":"package"} "${I.key}" is not assigned to the offer's program "${r.offerProgram.nameDe}"${I.kind==="group"?" or is not offered":""} (under Finance \u2192 assign articles).`)));let E=r.offerProgram?.stageKeys;if(f.byStage!==void 0&&E!==void 0){let I=[...A].filter(R=>!E.all.has(R));I.length>0&&i.push(Le(m,Fe.deriveStageUnknown,`"${u.key}": ${I.map(R=>`"${R}"`).join(", ")} ist keine Stufe des Programms \u201E${r.offerProgram.nameDe}\u201C (Stufen: ${[...E.all].join(", ")||"keine"}).`,`"${u.key}": ${I.map(R=>`"${R}"`).join(", ")} ${I.length===1?"is not a stage":"are not stages"} of the program "${r.offerProgram.nameDe}" (stages: ${[...E.all].join(", ")||"none"}).`));let v=[...E.active].filter(R=>!A.has(R));v.length>0&&i.push(Le(m,Fe.deriveStageUncovered,`"${u.key}": f\xFCr ${v.map(R=>`"${R}"`).join(", ")} nennt byStage keinen ${y==="group"?"Paket":"Artikel"} \u2014 diese Stufe h\xE4tte keinen Preis.`,`"${u.key}": for ${v.map(R=>`"${R}"`).join(", ")} byStage names no ${y==="group"?"package":"article"} \u2014 that stage would have no price.`))}}for(let u of t.values())for(let f of u){if(f.result.kind!=="reduction"||f.result.prices===void 0||f.result.writes===void 0)continue;let m=`node.${f.nodeId}.tasks.${f.taskKey}.result.prices`,k=o.get(f.result.prices)?.derive?.reduction;we(k)&&k.scope==="task"&&k.owner===f.taskKey&&k.key===f.result.writes||i.push(Le(m,Fe.reductionPrices,`Aufgabe "${f.taskKey}" senkt "${f.result.prices}" \u2014 das muss ein abgeleiteter Preis sein, dessen derive.reduction $task.${f.taskKey}.${f.result.writes} ist.`,`Task "${f.taskKey}" reduces "${f.result.prices}" \u2014 that must be a derived price whose derive.reduction is $task.${f.taskKey}.${f.result.writes}.`))}let c=r.grantTemplates;if(c!==void 0){let u=new Set(a.flatMap(f=>(f.rows??[]).flatMap(m=>m.grants??[])));for(let f of u){let m=c.get(f);if(m===void 0){i.push(Le("pricingRules",Fe.ruleGrantUnknown,`Eine Regelgruppe vergibt "${f}", aber keine Rabattvorlage des Mandanten tr\xE4gt diesen Schl\xFCssel.`,`A rule group grants "${f}", but no discount template of the school has this key.`));continue}d.some(({target:k,grants:g})=>{if(!g.has(f))return!1;if(k.kind==="item")return m.itemKeys.includes(k.key);let b=r.groupArticleKeys?.get(k.key);return m.itemKeys.some(A=>b?.has(A))})||i.push(Le("pricingRules",Fe.ruleGrantUnused,`Die Rabattvorlage "${f}" (gebunden an Artikel "${m.itemKeys.join(", ")}") wird vergeben, aber kein abgeleiteter Preis, der ihre Regelgruppe liest, enth\xE4lt ihr Ziel \u2014 sie wirkte nirgends.`,`The discount template "${f}" (bound to article "${m.itemKeys.join(", ")}") is granted, but no derived price reading its rule group contains its target \u2014 it would have no effect anywhere.`))}}return i}s(Pz,"derivedPriceIssues");function _z(e,n){if(!we(n)||n.scope!=="task"&&n.scope!=="derived"||n.path!==void 0)return null;let t=Nf(e).find(o=>o.key===n.key);if(t===void 0||n.scope==="derived"!=(t.derive!==void 0))return null;if(n.scope==="task")return Fr(e,n.owner,n.key)===null?null:Py(e,n);let r=AI(e,t.derive),i=s(o=>o.scope==="task"&&o.path===void 0&&Fr(e,o.owner,o.key)!==null,"resolvable");return r!==null&&r.every(o=>i(o.address))?Py(e,n):null}s(_z,"draftLeafOf");function Nz(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(Nz,"writerOf");function Cf(e){return we(e)?se(e):JSON.stringify(e)}s(Cf,"shown");function Cz(e,n,t){let r=e.scope==="task"&&e.path===void 0?n.get(e.key):void 0;if(e.scope==="task"&&e.path===void 0&&r===void 0)return null;if(e.scope!=="task"||r===void 0||r.derive!==void 0||!Cy.has(r.type))return"ruleSource";let i=t.get(r.key)?.find(o=>o.taskKey===e.owner);return i!==void 0&&DO(i)&&r.absentValue===void 0?"ruleReadsAbsent":null}s(Cz,"ruleSourceRefusal");function Dz(e,n){let t=e.scope==="task"&&e.path===void 0?n.get(e.key):void 0;return t!==void 0&&t.type==="reduction"&&t.derive===void 0}s(Dz,"isReductionValue");function DO(e){return e.template.when!==void 0||e.template.blocks?.node===void 0}s(DO,"writerMayBeNotOwed");function Dy(e){let n=He(e);return e.outcomes&&e.outcomes.length>0?[...e.outcomes]:n.outcomes&&n.outcomes.length>0?[...n.outcomes]:null}s(Dy,"nodeOutcomes");var Fz=["documentChangeRequested","documentReturned"];function FO(e){return Fz.includes(e)}s(FO,"isNonAdvancingExternalEvent");var Ks=["offer","contract"];function Df(e){return typeof e=="string"&&Ks.includes(e)}s(Df,"isArtifactSlotType");var LO="open",js="done";function Fy(e){let n={};for(let t of ze)n[t]=e(t);return n}s(Fy,"localized");var MO=[{key:"tenantSlug",type:"string"}];var Lz=/^(\d{4})-(\d{2})-(\d{2})$/;function Mz(e){return e>=1900&&e<=2100}s(Mz,"isSupportedYear");function qz(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(qz,"isRealDate");function Ly(e){if(typeof e!="string")return null;let n=Lz.exec(e);if(n===null)return null;let[,t,r,i]=n;return t===void 0||r===void 0||i===void 0||!Mz(Number(t))||!qz(Number(t),Number(r),Number(i))?null:{year:t,month:r,day:i}}s(Ly,"isoDateParts");var Kz="Europe/Berlin";function KO(){return Kz}s(KO,"tenantTimeZone");var qO=new Map;function jz(e){let n=qO.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{le("INVALID",{de:`Unbekannte Zeitzone "${e}".`,en:`Unknown time zone "${e}".`})}return qO.set(e,t),t}s(jz,"formatterFor");function Bz(e,n){let t=new Map(jz(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(Bz,"zoneOffsetAt");function My(e,n){let t=e+Bz(n,e);return{wallClock:new Date(t).toISOString().slice(0,19),timeZone:n}}s(My,"instantToLocalDateTime");var qy=3;function jO(e){return My(e,KO()).wallClock.slice(0,10)}s(jO,"localIsoDate");var Ff=["login","security","admission","tasks","deadlines","schoolMessages","staffTasks","staffAppointments","staffDeadlines","staffWaitlist","familyMessages","mentions"],BO=w.union(...Ff.map(e=>w.literal(e)));var rue=w.union(w.literal("admission"),w.literal("tasks"),w.literal("staff"),w.literal("chat")),Ky=["loginOnly","all"],iue=w.union(w.literal("loginOnly"),w.literal("all"));function UO(e){return typeof e=="string"&&Ky.includes(e)}s(UO,"isMailLevel");var Sl="subject";function VO(e){return e.category==="login"}s(VO,"isSignInLetter");var cn={key:"schoolName",label:"Name der Schule"},GO={de:"Zu Ihren Bewerbungen",en:"View your applications"},Sn={key:"portalLink",label:"Link zum Bewerberportal",required:!0,link:!0,actionLabel:GO},jy={key:Sn.key,label:Sn.label,link:!0,actionLabel:GO},zO={key:"authorName",label:"Name der schreibenden Person"},Bs={key:"applicationLink",label:"Link zur Bewerbung",required:!0,link:!0,actionLabel:{de:"Bewerbung \xF6ffnen",en:"Open application"}},Al={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"}},Vz={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"}},WO={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"}},El={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"15 Minuten",en:"15 minutes"}},YO={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"24 Stunden",en:"24 hours"}},Gz={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"60 Minuten",en:"60 minutes"}};function Me(e){return{key:Sl,label:"Betreff",default:e}}s(Me,"subjectSlot");var Li=w.object({de:w.string(),en:w.string()}),On={tenantSlug:w.string(),applicationId:w.id("applications")},zz=w.object({tenantSlug:w.string()}),Wz={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:zz,channels:["email"],portalVisible:!0,placeholders:[cn,Sn],slots:[Me({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:
10499
10504
 
10500
10505
  {{portalLink}}`,en:`Thank you for registering with {{schoolName}}. You can view and continue your applications at any time using the link below:
@@ -10808,14 +10813,14 @@ ${i.map(d=>` ${yd(d)}
10808
10813
  `),0}},hD=[rb,ib,ob];var sb=class extends D{static{s(this,"LeadsListCommand")}static paths=[["leads","list"],["interessenten","list"]];static usage=T.Usage({category:"Admission",description:"List Interessenten (leads) for the active tenant",details:"Lists the tenant's OPEN Interessenten (program interests), newest first. Converted leads are Bewerbungen (listed under applications); withdrawn/declined leads are removed. Use --json for the rich shape.",examples:[["List open Interessenten","plexus-cli leads list"],["As JSON","plexus-cli leads list --json"]]});async execute(){let 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":_e(o.programName),stufe:o.stageName===null?"\u2014":_e(o.stageName),lauf:o.runName===null?"\u2014":_e(o.runName)})),["name","angebot","stufe","lauf"]),0}},gD=[sb];function hb(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(hb,"ts");function wD(e){return e==null?"":`${Math.round((Date.now()-e)/6e4)}m`}s(wD,"ago");var yD=["queued","running","succeeded","failed","canceled"];function s6(e){let n=yD.find(t=>t===e);if(n===void 0)throw new Error(`jobs list: --status must be one of ${yD.join(" | ")}, got "${e}".`);return n}s(s6,"jobStatus");var ab=class extends D{static{s(this,"JobsListCommand")}static paths=[["jobs","list"]];static usage=T.Usage({category:"Jobs",description:"List jobs newest-first (platform-admin). --status / --kind filter."});status=p.String("--status",{description:"queued | running | succeeded | failed | canceled"});kind=p.String("--kind",{description:"import | dummy | document_template_export"});limit=p.String("--limit",{description:"Max rows (default 100)."});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let n=await this.caller(),t=this.all?void 0:ju(this.limit,100),r=await this.paginate(n,x.jobs.listPage,this.status?{status:s6(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:wD(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},lb=class extends D{static{s(this,"JobsShowCommand")}static paths=[["jobs","show"]];static usage=T.Usage({category:"Jobs",description:"Show one job's full detail + per-attempt run timeline."});jobId=p.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}},db=class extends D{static{s(this,"JobsLogsCommand")}static paths=[["jobs","logs"]];static usage=T.Usage({category:"Jobs",description:"Tail a job's captured worker output (oldest-first)."});jobId=p.String({required:!0});limit=p.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:hb(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},cb=class extends D{static{s(this,"JobsCancelCommand")}static paths=[["jobs","cancel"]];static usage=T.Usage({category:"Jobs",description:"Cancel a queued/running job (the worker aborts; the domain row is failed) \u2014 irreversible, plan unless --confirm."});jobId=p.String({required:!0});confirm=p.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}},ub=class extends D{static{s(this,"WorkersLogsCommand")}static paths=[["platform","workers","logs"],["workers","logs"]];static usage=T.Usage({category:"Platform",description:"Tail one worker's captured stdout/stderr."});workerId=p.String({required:!0});limit=p.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:hb(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},fb=class extends D{static{s(this,"WorkersReaperStatusCommand")}static paths=[["platform","workers","reaper-status"],["workers","reaper-status"]];static usage=T.Usage({category:"Platform",description:"Show the last worker-reaper tick (confirm the cron is firing)."});async execute(){let t=await(await this.caller()).query(x.workers.reaperStatus,{});return t===null?(this.print({reaper:"no tick recorded yet"}),0):(this.print({...t,ranAt:hb(t.ranAt)}),0)}},pb=class extends D{static{s(this,"WorkersReapCommand")}static paths=[["platform","workers","reap"],["workers","reap"]];static usage=T.Usage({category:"Platform",description:"Force a reaper pass NOW (free dead leases / fail stalled jobs)."});async execute(){let t=await(await this.caller()).mutation(x.workers.reap,{});return this.print(t),0}},mb=class extends D{static{s(this,"ImportsCleanupOrphansCommand")}static paths=[["platform","imports","cleanup-orphaned"],["imports","cleanup-orphaned"]];static usage=T.Usage({category:"Imports",description:"Find/fail orphaned import runs (status 'running' with no active job). Dry-run unless --confirm."});allTenants=p.Boolean("--all-tenants",!1,{description:"Scan every tenant (default: the active --tenant only)."});confirm=p.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:wD(o.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},kD=[ab,lb,db,cb,ub,fb,pb,mb];var a6=/^(\d+)([mhd])$/,l6={m:6e4,h:36e5,d:864e5};function qp(e,n=Date.now()){let t=e.trim(),r=a6.exec(t);if(r!==null)return n-Number(r[1])*l6[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(qp,"parseSince");function Kp(e){return e==null?"":new Date(e).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}s(Kp,"ts");function $b(e,n){if(e===void 0)throw new Error(`notifications ${n}: --locale is required (${ze.join("|")}) \u2014 every letter exists in each language, and each is worded on its own`);if(!kp(e))throw new Error(`notifications: --locale "${e}" is not a supported locale (${ze.join("|")})`);return e}s($b,"parseLocale");function d6(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=>ye(o.trim(),"utf8"));return t}s(d6,"parseSlots");var gb=class extends D{static{s(this,"NotificationsListCommand")}static paths=[["platform","notifications","list"],["notifications","list"]];static usage=T.Usage({category:"Notifications",description:"List mail deliveries newest-first (platform-admin). Filter by --status, --template, --to, --since; the smtp column is the relay's answer (`250 \u2026 queued as <id>` = accepted).",examples:[["Dead-letters only","$0 notifications list --status dead"],["Everything still in flight","$0 notifications list --status queued"],["Did the login-page link to this address go out today?","$0 notifications list --template account.loginLink --to steffi@schule.example --since 24h"]]});status=p.String("--status",{description:"queued | sending | sent | skipped | dead"});template=p.String("--template",{description:"Only this letter, e.g. account.loginLink."});to=p.String("--to",{description:"Only deliveries to this address."});since=p.String("--since",{description:"Created since: 90m, 24h, 2d or an ISO date/time."});limit=p.String("--limit",{description:"Max rows (default 100)."});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)."});async execute(){let n=await this.caller(),t=this.all?void 0:ju(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:qp(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:Kp(o.createdAt),settled:Kp(o.settledAt),smtp:o.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function c6(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(c6,"showView");var yb=class extends D{static{s(this,"NotificationsShowCommand")}static paths=[["platform","notifications","show"],["notifications","show"]];static usage=T.Usage({category:"Notifications",description:"Show one delivery in full: SMTP evidence, lease, sweeper bookkeeping, template summary."});deliveryId=p.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(c6(t)),0}},wb=class extends D{static{s(this,"NotificationsRetryCommand")}static paths=[["platform","notifications","retry"],["notifications","retry"]];static usage=T.Usage({category:"Notifications",description:"Retry a DEAD delivery: a fresh attempt through the normal claim path. Check `show` first \u2014 a `possibleDuplicate` row may already have reached the recipient."});deliveryId=p.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}},kb=class extends D{static{s(this,"NotificationsSweeperStatusCommand")}static paths=[["platform","notifications","sweeper-status"],["notifications","sweeper-status"]];static usage=T.Usage({category:"Notifications",description:"Last tick of the notification sweeper cron (deadLastHour is the number to watch)."});async execute(){let 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:Kp(t.ranAt),lastDeadAt:Kp(t.lastDeadAt)}),0)}},bb=class extends D{static{s(this,"NotificationsSelfTestCommand")}static paths=[["platform","notifications","self-test"],["notifications","self-test"]];static usage=T.Usage({category:"Notifications",description:"Resolve the deployment's mail config, verify the SMTP connection + credentials, and send ONE test mail to --to with the raw SMTP transcript. A redirect deployment redirects the test too; dry sends nothing.",examples:[["Probe staging","$0 --env staging notifications self-test --to you@example.com"]]});to=p.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}},vb=class extends D{static{s(this,"NotificationsLettersListCommand")}static paths=[["notifications","letters","list"]];static usage=T.Usage({category:"Notifications",description:"The letter catalog for one school: what it can reword, and what it already did.",details:"Only the letters a school may actually write are listed \u2014 addressed to families, and with blocks to rewrite. A staff-internal letter or a retired one is not offered at all. `reworded` names the languages in which this school has already deviated from a letter.",examples:[["The catalog","$0 --tenant test notifications letters list"],["Only the reworded ones","$0 --tenant test notifications letters list --json"]]});async execute(){let 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}},xb=class extends D{static{s(this,"NotificationsLettersShowCommand")}static paths=[["notifications","letters","show"]];static usage=T.Usage({category:"Notifications",description:"One letter block by block: the current text, whether it deviates, and the placeholders it may use.",examples:[["The welcome letter","$0 --tenant test notifications letters show applicant.welcome --locale de"],["Its English version","$0 --tenant test notifications letters show applicant.welcome --locale en"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.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:$b(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}
10809
10814
  Platzhalter: ${i||"\u2014"}
10810
10815
 
10811
- `)}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}},Sb=class extends D{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=p.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let n=d6(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:$b(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}},Ab=class extends D{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"Block key to reset (repeatable)"});all=p.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:$b(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}},bd=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function jp(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":bd(n[r],""),...t===null?{}:{platform:bd(t[r],"")}}))}s(jp,"chromeTextRows");var Eb=class extends D{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let n=await this.caller(),t=await n.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(n)});return this.print(t,r=>[...jp("greeting",r.greeting,r.defaults.greeting),...jp("closing",r.closing,r.defaults.closing),{field:"senderName",school:bd(r.senderName,"\u2014 (platform)"),platform:bd(r.defaults.senderName,"")}],["field","school","platform"]),0}},Tb=class extends D{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=p.String("--greeting-de",{description:"Opening line, German"});greetingEn=p.String("--greeting-en",{description:"Opening line, English"});closingDe=p.String("--closing-de",{description:"Sign-off, German"});closingEn=p.String("--closing-en",{description:"Sign-off, English"});senderName=p.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=>[...jp("greeting",l.greeting,null),...jp("closing",l.closing,null),{field:"senderName",school:bd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},bD=[gb,yb,wb,kb,bb,vb,xb,Sb,Ab,Eb,Tb];var u6="-stufe-",f6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Rb(e){return`${e}${u6}`}s(Rb,"stageKeyPrefix");function Ib(e,n){return`${Rb(e)}${n}`}s(Ib,"stageStorageKey");function xD(e,n){let t=Rb(e);return n.startsWith(t)&&n.length>t.length}s(xD,"isUnderProgram");function jr(e,n){let t=Rb(e);return xD(e,n)||le("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(jr,"bareStageKey");function Bp(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Rn(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"||!f6.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(Bp,"stageSpecIssues");function vD(e){return{de:e.de.trim(),en:e.en.trim()}}s(vD,"trimmedText");function p6(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(p6,"describeNameChange");function Up(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:vD(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:vD(a)},u=Ib(e,c.key);i.add(u);let f=d+1,m=r.get(u);if(m===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:f});return}let y={};hs(m.name,c.name)||(y.name=[m.name,c.name]);let k=m.gradeLevel??null,g=c.gradeLevel??null;k!==g&&(y.gradeLevel=[k,g]),m.sequence!==f&&(y.sequence=[m.sequence,f]),(Object.keys(y).length>0||m.archived)&&o.push({op:"update",key:c.key,stageId:m.stageId,name:c.name,changes:y,unarchive:m.archived})});for(let a of[...n].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:xD(e,a.key)?jr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Up,"planStageReconcile");function Vp(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(p6(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(Vp,"describeStageStep");var m6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ci(e,n){return`${e}-${n}`}s(ci,"runStorageKey");function SD(e,n){typeof n!="string"&&le("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)&&le("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(SD,"bareRunKey");function Gp(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Rn(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"||!m6.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(Gp,"runSpecIssues");var h6={capacity:null,isOpen:!1},g6={capacity:null,isOpen:!0};function y6(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(y6,"isCapacity");function zp(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)||!y6(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(zp,"capacitySpecIssues");function ED(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(jr(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(f=>f.key===ci(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[f,m]of Object.entries(c.capacities)){let y=i.get(f);if(y===void 0&&!o.has(f))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${f}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:m.capacity,isOpen:m.isOpen},g=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,b=g!==void 0?{capacity:g.capacity,isOpen:g.isOpen}:u===void 0?h6:g6;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:b,to:k})}}return d}s(ED,"planRunCapacities");function AD(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(AD,"describeCell");function Wp(e){return`~cap ${e.run}\xD7${e.stageKey} ${AD(e.from)} \u2192 ${AD(e.to)}`}s(Wp,"describeCapacityStep");function TD(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(TD,"assertBackendHasStageKeys");async function Ob(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}));TD(i);let a=Up(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 f=c.get(u.stageId);if(f===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:f.activeApplications,openLeads:f.openLeads}}})}s(Ob,"planStages");async function Yp(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});TD(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>jr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return ED(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===ci(d,c)))})}s(Yp,"planCapacities");async function w6(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===ci(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(w6,"assertNoArchivedRunKey");var Pb={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...Bp(o??[]),...Gp(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=zp(t.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await w6(e,i,n,t);let d=await Yp(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=k6(t);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let f=c.units.find(g=>g.key===u);if(!f)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(g=>g.key===null?[]:[g.key]).join(", ")||"(none)"}`);let m=[];if(r.dryRun||(await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:i,unitId:f.unitId}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:i,offerKey:n,unitId:f.unitId,...t.program?.key!==void 0?{programKey:t.program.key}:{}})),m.push(`unit=${u}`),o!==void 0)if(r.dryRun){let g=await Ob(e,i,n,o);m.push(...g.map(Vp))}else{let g=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}:{}}))});m.push(...g.steps,...g.warnings.map(b=>`warning ${b}`))}let y=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let g of t.program?.runs??[]){let b=y.programKey===null?void 0:y.runs.find(A=>A.key===ci(y.programKey,g.key));if(b!==void 0){hs(b.name,g.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:g.name}),m.push(`~run ${g.key} ("${_e(b.name)}" \u2192 "${_e(g.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,key:g.key,name:g.name,isOpen:g.capacities!==void 0?!1:g.isOpen??!0,...g.startDate?{startDate:g.startDate}:{},...g.endDate?{endDate:g.endDate}:{}}),m.push(`+run ${g.key} (${_e(g.name)})`)}let k=r.dryRun?d:await Yp(e,i,n,t);if(!r.dryRun&&k.length>0){let g=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=g.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of k){let $=g.runs.find(E=>E.key===ci(b,A.run))?.runId,O=g.stages.find(E=>jr(b,E.key)===A.stageKey)?.stageId;if($===void 0||O===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:n,runId:$,stageId:O,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return m.push(...k.map(Wp)),m.join(", ")}};function k6(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(k6,"bundleUnitKey");var $D={role:"control",effect:"pure",cardinality:"N-to-1"};var Hp=["add","remove","replace"];function RD(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(RD,"roleAssignLiteral");var ID={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=RD(e,"roleKey")?.trim()??"",o=RD(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"}),Hp.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 ${Hp.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Hp.join(" | ")}.`},severity:"error"}),r},"validate")};var b6=["event","effect","outcomes"],_b=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),OD={outcomes:[{id:hr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of b6)i in r&&t.push(_b(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${hr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${hr}" itself.`));return _t(n.nodes).some(i=>i.target===e.id)&&t.push(_b(`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?.[hr]===void 0&&t.push(_b(`nodes.${e.id}.next.${hr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${hr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${hr}" nowhere.`)),t},"validate")};var v6="submit",PD=[{id:v6,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function _D(e){return e==="draft"}s(_D,"isWritableSmartFormState");var Nb=["draft","committed"],FEe=Nb.filter(e=>_D(e));async function ND(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(ND,"getSmartFormInstance");var CD="form:fill",Cb="request:collectPayment";var x6={key:CD,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},DD={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},FD={[kR]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:DD,external:en(te("Entwurf","Draft"),"neutral",te("Bewerbung fortsetzen","Continue application"),te("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),te("Bewerbung fortsetzen","Continue application"),"continue-form")},[Hu]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:DD,external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung ist eingereicht","Your application has been submitted"),te("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},LD={role:"user-action",effect:"side-effect",progressDefaults:FD,progressEvents:Dn(FD),actions:s(()=>PD,"actions"),workItemTemplates:s(()=>[x6],"workItemTemplates"),states:Nb,currentState:s(async(e,n)=>{let t=await ND(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=>vt(e)?[]:[{id:Ju,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 MD={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:In.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:In.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:In.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:jI(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[In.flagKey]?.kind==="literal"&&wf(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${In.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?.[In.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${In.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 S6="true",A6="false",Db=[{id:S6,label:{de:"Ja",en:"Yes"}},{id:A6,label:{de:"Nein",en:"No"}}];var qD={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Db,validate:s((e,n,t)=>E6(e,n,t),"validate")};function E6(e,n,t){let r=s(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${d.de}`,en:`[if/condition] Node "${e.id}": ${d.en}`},severity:"error"}),"issue"),i=Db.filter(d=>e.next?.[d.id]===void 0).map(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${d.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${d.label.de}\u201C (${d.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${d.label.en}" (${d.id}) leads nowhere.`},severity:"error"}));if(typeof e.condition!="string"||e.condition.trim()==="")return[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})];let o=CR(n),a=zf(e.condition,o).filter(d=>d.severity==="error").map(d=>r(d.message)),l=[...i,...a];if(a.length>0||t?.liveEnvKeys===void 0)return l;for(let d of Qy(e.condition,o)){let c=kP(d.path,t.liveEnvKeys);c===null&&F(`[if/condition] no live-key universe for '${d.path}' \u2014 extend liveKeyUniverse`),c.has(d.value)||l.push(r({de:`$env.${d.path} == '${d.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${d.path} == '${d.value}' names no key of this school.`}))}return l}s(E6,"ifNodeIssues");var vd="decision",T6=new Set(["decision","review"]),lTe=new Set([...T6,"governedDocument"]);var jD=[{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"}],KD={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:en(te("Freigegeben","Released"),"green",te("Ihre Bewerbung wurde freigegeben","Your application has been released"),te("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Do={role:"user-action",effect:"side-effect",outcomes:jD,progressDefaults:KD,progressEvents:Dn(KD),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,...Ri(n.semantic)?{semantic:n.semantic}:{}})),...ZP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:vd,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===vd&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),validate:Fb};function Fb(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(f=>typeof f=="string"&&f.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 ${bt.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${bt.join(", ")}.`},severity:"error"}):Ri(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: ${bt.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${bt.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(Fb,"validateDecisionNode");var Lb=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],BD=[{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 er="processFooter";var Mb="promoted";var UD="promote",VD="Nachr\xFCcken";var qb={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},GD={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:qb,external:en(te("Warteliste","Waiting list"),"amber",te("Sie stehen auf der Warteliste","You are on the waiting list"),te("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:te("Nachger\xFCckt","Promoted"),tone:"green",phase:qb,external:en(te("Nachger\xFCckt","Moved up"),"green",te("Sie sind nachger\xFCckt","You have moved up"),te("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:te("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:qb,external:en(te("Warteliste geschlossen","Waiting list closed"),"red",te("Die Warteliste wurde geschlossen","The waiting list has been closed"),te("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},zD={outcomes:Lb,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Yt.map(e=>({value:e,label:VR[e]}))}],"inputs"),validate:s((e,n)=>{let t=Yg(e);if(t===null)return[];let r=n.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=n.nodes.indexOf(e);for(let o of r){if(n.nodes.indexOf(o)>i)continue;let a=Yg(o);if(a!==null&&a.waitlistOrder!==t.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different orders \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:GD,progressEvents:Dn(GD),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:Lb).some(t=>t.id===Mb)?[{id:UD,kind:"advance",outcome:Mb,semantic:"other",label:{de:VD,en:"Promote from waitlist"},surface:er,superUserOnly:!0}]:[],"actions")};var Kb="complete",xd="acceptedIncomplete",Jp="rejected",$6="absage",WD="closeWithoutDocuments",YD="rejectAtCompleteness",HD="Ohne Nachreichung abschlie\xDFen",JD="Ablehnen",QD="awaitingDocuments",jb="documentsComplete",Bb="closedWithoutDocuments",Ub="rejected",Vb="withdrawn",ZD="requested",OTe={[Kb]:{event:jb,status:"complete",endsRole:!0},[xd]:{event:Bb,status:"acceptedIncomplete",endsRole:!1},[Jp]:{event:Ub,status:"rejected",endsRole:!0},[$6]:{event:Vb,status:"withdrawn",endsRole:!0}};var Sd=s(()=>yl[0],"beneficiary"),Gb=366;function R6(e){let n=e.reads,t=wl(e).flatMap(({address:r})=>dn(r)&&!yl.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(dn):[],...t]}s(R6,"printedFields");function I6(e,n){let t=se(n);return e.nodes.filter(r=>r.type==="governedDocument"&&R6(r).some(i=>se(i)===t))}s(I6,"documentsPrinting");function O6(e,n){if(!dn(n)||n.path!==Sd())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!vt(t)}s(O6,"isCreatedFormBeneficiary");function Fn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Fn,"issue");function P6(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Kb,xd].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)&&wr(d.form)&&d.form.owner===t)){if(d.type==="end"){if(xl(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(P6,"reachesApprovedEndUnreviewed");var zb={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},XD={[QD]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:zb,external:en(te("Unterlagen fehlen","Documents missing"),"amber",te("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),te("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[jb]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:zb,external:en(te("Unterlagen vollst\xE4ndig","Documents complete"),"green",te("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),te("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[Bb]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:zb,external:en(te("Abgeschlossen","Closed"),"neutral",te("Die Nachreichung ist abgeschlossen","The document request is closed"),te("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[Ub]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:SO,external:en(te("Abgelehnt","Rejected"),"red",te("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),te("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[Vb]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:_f,external:en(te("Zur\xFCckgezogen","Withdrawn"),"red",te("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),te("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},eF={outcomes:BD,progressDefaults:XD,progressEvents:Dn(XD),notificationEvents:s(()=>[{id:ZD,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(xd)&&t.push({id:WD,kind:"advance",outcome:xd,semantic:"other",label:{de:HD,en:"Close without documents"},surface:er,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(Jp)&&t.push({id:YD,kind:"advance",outcome:Jp,semantic:"rejected",label:{de:JD,en:"Reject application"},surface:er,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(A=>Ue(n,A,"de"),"shown"),l=s(A=>Ue(n,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Fn(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let $ of d){if(!we($))continue;let O=se($);if(A.has(O)){r.push(Fn(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a($)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l($)} appears twice in \`requires\`.`}));continue}if(A.add(O),!dn($)){r.push(Fn(e,"requires",{de:`[completenessCheck/unknownField] ${a($)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l($)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let E=ii(t,$);if(E==null)continue;let I=Ds("requires",Cs(E));I==="computed"||I==="repeated"?r.push(Fn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a($)} ist ${E.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l($)} is ${E.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):I==="untranslated"&&r.push(Fn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a($)} (\u201E${Di(E,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l($)} ("${Di(E,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},f="inDays"in u,m="until"in u;if(f===m)r.push(Fn(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(f){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>Gb)&&r.push(Fn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${Gb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${Gb} days.`}))}else typeof u.until!="string"||Ly(u.until)===null?r.push(Fn(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<jO(Date.now())&&r.push({...Fn(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(dn).map($=>[se($),$]));for(let $ of A.values())for(let O of I6(n,$))r.push(Fn(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a($)} flie\xDFt in das Dokument \u201E${O.label?.de??O.id}" (${O.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($)} flows into the document "${O.label?.en||O.id}" (${O.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 A=d.filter(dn).filter(E=>{let I=ii(t,E);return I!=null&&Jf(I)}),O=[...new Set(A.map(E=>E.owner))].filter(E=>P6(n,e,E));if(O.length>0){let E=A.filter(I=>O.includes(I.owner));r.push({...Fn(e,"next",{de:`[review/unreviewedAfterSupply] ${E.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] ${E.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,g=e.inputs?.person,b=g?.kind==="binding"?g.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Fn(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(Fn(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(Fn(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(Fn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${it}.${Sd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${it}.${Sd()}).`}))),we(b)&&!O6(n,b)&&r.push(Fn(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>.${it}.${Sd()}).`,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>.${it}.${Sd()}).`})),b!==null&&k===void 0&&r.push(Fn(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Fn(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var _6=[{id:zR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Qp=s(e=>e,"asDecision"),nF={[WR]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),te("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},tF={role:"user-action",effect:"side-effect",outcomes:_6,progressDefaults:nF,progressEvents:Dn(nF),notificationEvents:s(e=>Do.notificationEvents(Qp(e)),"notificationEvents"),inputs:s(()=>[{id:Qt,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Eo.map(e=>({value:e,label:S_[e]}))}],"inputs"),actions:s(e=>[...Do.actions(Qp(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Qg,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Do.optionalActionKinds,workItemTemplates:s(e=>Do.workItemTemplates(Qp(e)).map(n=>n.key===vd?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Qg]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Fb(Qp(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!cf.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?.[Qt],a=A_(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Qt}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Eo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Eo.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)&&wr(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Jf)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${se(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 ${se(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 ${se(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 ${se(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 rF=["awaitingAnswer","answered"];async function iF(e,n){return(await Il(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(iF,"externalRequestState");var aF=[{id:Ps,label:{de:"Bezahlt",en:"Paid"}}],m$e=new Set(aF.map(e=>e.id));var N6=Ps,oF=[{id:N6,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],C6={id:Ey,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:er,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"}}},D6={id:Ey,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:er,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 Wb(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Wb,"literalOf");function ua(e){let n=Wb(e,Ht);return xf(n)?n:null}s(ua,"settlementOrNull");function F6(e){let n=Wb(e,Ni);return typeof n=="string"&&n.length>0?n:null}s(F6,"articleKeyOrNull");function L6(e){let n=Wb(e,Jt);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(L6,"payeeKeyOrNull");var M6={id:Ni,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},q6={id:Ht,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},K6={id:Ci,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},j6={id:Jt,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function B6(e){return[M6,q6,...ua(e)==="online"?[j6]:[],K6]}s(B6,"collectPaymentInputs");var U6=["amount","currency","settlement"];function V6(e,n){if(ua(e)!=="online")return[];let t=L6(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${Jt}`,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] Abrechnung \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 \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "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 "separate".`})]:[]}s(V6,"payeeIssues");var sF={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:en(te("Zahlung offen","Payment due"),"amber",te("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),te("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},lF={outputs:s(()=>[{name:PI,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>B6(e),"inputs"),outcomes:aF,progressDefaults:sF,progressEvents:Dn(sF),notificationEvents:s(e=>ua(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=ua(e);return n==="online"?[...oF,D6]:n==="separate"?[C6]:[]},"actions"),states:rF,currentState:s((e,n)=>iF(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:Cb}),"currentState"),workItemTemplates:s(e=>{let n=e;return ua(n)!=="online"?[]:[{key:Cb,recipient:"external",title:n.label,unlocks:oF.map(t=>t.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 U6)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});r.push(...V6(e,t)),ua(e)===null&&i(`inputs.${Ht}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Os.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Ht])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Os.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Ht])}.`});let o=e.inputs?.[Ci];if(o?.kind==="literal"){let d=vf(o.value);d!==null&&i(`inputs.${Ci}`,{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=F6(e);if(a===null)return i(`inputs.${Ni}`,{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.${Ni}`;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 ${Ty.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Ty.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")};var qt="traeger",dF={de:"Tr\xE4ger",en:"Provider"};function Zp(e){let n=e.inputs?.[qt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(Zp,"traegerKeyOfNode");var Xp={name:"input.traeger.name",address:"input.traeger.anschrift"},y$e=Object.values(Xp);var cF="governedDocument",Fo="prepareDocument",Ad="prepareDocument:revision",Br="releaseApproval",Lo="documentResponse",Ur="responseCheck",em="returnSigned";var uF="requestApproval";var fF="issueDocument",pF="correctInPlace",mF="rescindAndReissue",nm="requestChange";var fa="releaseArtifact",ft="signingRecovery",Mo="resendESignature",qo="switchToPaper";var Yb=new Set([Fo,Ad]),hF=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],tm=["upload","resolver","template","none"],Ko=1,jo=366,ui="responseDueInDays";function Hb(e){let n=e.inputs?.[ui];return n?.kind==="literal"&&Ed(n.value)?n.value:void 0}s(Hb,"responseDueInDaysForVocabulary");function Ed(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Ko&&e<=jo}s(Ed,"isValidResponseDueInDays");var rm=["generatedAt","responseDueInDays","countersignature"],Bo=["release","none"],im=["confirm","signedUpload","signedUploadChecked","eSignature"];function gF(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(gF,"localeFieldMissingText");var Jb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),yF=/^[a-z][a-z0-9_]*$/;function wF(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"||!yF.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(!_i(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 (${Is.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 (${Is.join(", ")}).`}});continue}if(Jb.has(a.type)||t.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${n}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...Jb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a letter only prints ${[...Jb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!yF.test(String(d.value)))&&t.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${n}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${n}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&t.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${n}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${n}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${n}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${n}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?t.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Brief aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a letter from a template is not countersigned.`}}):a.processSource!==void 0&&!rm.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${rm.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${rm.join(", ")}.`}})}return t.push(...G6(e,n)),t}s(wF,"templateParameterIssues");function G6(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:gF(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=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${n}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${n}" ${r.en}.`}}]}s(G6,"localeFieldIssues");function kF(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(kF,"applyTemplateStamp");var Qb=50;async function om(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(Qb+1);return t.length>Qb&&F(`signing_returns: Vorgang ${n} has more than ${Qb} returns`),t}s(om,"returnsOf");var Zb=50;async function Xb(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(Zb+1);return t.length>Zb&&F(`signing_returns: return ${n} has more than ${Zb} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(Xb,"returnDocumentsOf");async function bF(e,n){let t=await Xb(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(bF,"soleReturnDocumentOf");var sm=200,M$e=sm*20;async function z6(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(z6,"processRedacted");async function ev(e,n){await z6(e,n)&&le("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(ev,"assertProcessReadable");function W6(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(W6,"rowOf");async function vF(e,n,t){await ev(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(sm+1);return r.length>sm&&F(`[process] application ${n} has more than ${sm} results of ${t.scope}.${t.owner}.${t.key}`),r.map(W6)}s(vF,"storeHistory");async function Y6(e,n,t){if(t.key===it){await ev(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 vF(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(Y6,"nodeResultAt");async function am(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return H6(await Y6(e,n.applicationId,t),t,n.applicationId)}s(am,"readOwnResult");function H6(e,n,t){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${se(n)} of application ${t} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(H6,"refOf");var nv={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},J6=Object.keys(nv),Q6=J6.filter(e=>nv[e]==="open"),W$e=Q6.filter(e=>e!=="pending");function xF(e){return nv[e]==="terminal"}s(xF,"isTerminalSigningStatus");var Bi=["docusign","insign"];var Td={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var X6=xF;function AF(e){return!X6(e.status)&&e.voidRequestedAt===void 0}s(AF,"holdsContract");async function EF(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(EF,"traegerLegalEntityOfParty");async function e4(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(e4,"isOrganizationParty");async function TF(e,n){return await EF(e,n)!==null?"traeger":await e4(e,n)?"organization":"person"}s(TF,"signerKindOf");async function $F(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await n4(e,t.partyId)==="family")return"family";return"traeger"}s($F,"signingSideOf");async function n4(e,n){return await TF(e,n)==="traeger"?"traeger":"family"}s(n4,"sideOfParty");var TRe=16*1024;var $Re=15*6e4;var RRe=10*6e4;var tv={contractSnapshotId:Yn.restrict(w.id("contract_snapshots")),storageId:Yn.restrict(w.id("_storage")),sha256:w.string(),filename:w.string(),uploadedAt:w.number(),signers:w.array(w.object({partyId:Yn.history(w.id("parties")),role:w.string()}))},GRe=Jr({tenantId:Yn.tenant(w.id("tenants")),signingRequestDocumentId:Yn.belongsTo(w.id("signing_request_documents")),...tv}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var JRe=w.object(tv);var rv=200;async function r4(e,n,t,r){n.length>rv&&F(`${r} is carried by more than ${rv} 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(r4,"requestsOfMembers");async function RF(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(rv+1);return await r4(e,r,t,`revision ${n}`)}s(RF,"requestsOfSnapshot");var IF=100;async function i4(e,n){let t=await RF(e,n);t.length>IF&&F(`requestsBySideOf: revision ${n} has more than ${IF} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await $F(e,i.signers)].push(i);return r}s(i4,"requestsBySideOf");async function iv(e,n){return(await i4(e,n)).family}s(iv,"familyRequestsOf");var ov=100;async function o4(e,n){let t=await e;return t.length>ov&&F(`contractChain: more than ${ov} ${n}`),t}s(o4,"bounded");async function s4(e,n,t){let r=await am(e,{applicationId:n,nodeId:t,key:Es});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Es} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(s4,"nodeContractRef");async function OF(e,n){return await o4(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",t=>t.eq("contractId",n)).take(ov+1),`revisions on contract ${n}`)}s(OF,"snapshotsAsc");async function sv(e,n){let t=(await iv(e,n)).filter(AF);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(sv,"openFamilyRequest");async function a4(e,n){for(let t of await OF(e,n))if((await iv(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(a4,"familyRoute");async function PF(e,n){for(let t of n)if(await a4(e,t)==="paper")return"paper";return"provider"}s(PF,"familyRouteOf");async function l4(e,n){let t=await bF(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(l4,"toReturn");function lm(e){async function n(a,l){return await s4(a,l,e.id)}s(n,"contractOrNull");async function t(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),f=u===null?null:await a.db.get(u),m=await n(a,l);return(f===null||m===null||f.contractId!==m)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${m??"(none yet)"} \u2014 corrupt arc`),f}s(t,"snapshotOf");async function r(a,l){let d=await n(a,l);return d===null?null:(await OF(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 sv(a,c._id);if(u===null)return null;let f=(await om(a,u._id)).filter(m=>m.review.status==="pending"&&m._id!==d.rejected);return f.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${f.length} returns pending \u2014 one is checked at a time`),f[0]===void 0?null:await l4(a,f[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(lm,"contractNodeReads");function dm(e){return e.addedParts??[]}s(dm,"addedPartsOf");var av=50;async function d4(e,n){let t=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",n)).take(av+1);return t.length>av&&F(`groupRunsOf: generation group ${n} has more than ${av} runs`),t.length===0&&F(`groupRunsOf: generation group ${n} has no run`),t.sort((r,i)=>r._creationTime-i._creationTime)}s(d4,"groupRunsOf");async function _F(e,n){let t=await d4(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_packageRevisionId_and_position",l=>l.eq("packageRevisionId",i.packageRevisionId)).take(51),a=[...o.map(l=>l.partKey),...dm(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(_F,"groupRunsInOrder");function NF(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(NF,"isCompleteGroup");var lv=200;function c4(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(c4,"groupPartKeys");async function u4(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(lv+1);return r.length>lv&&F(`groupChain: more than ${lv} generation runs on node ${t}`),r}s(u4,"nodeRuns");async function f4(e,n,t){let r=c4(t),i=new Set;for(let a of await u4(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 _F(e,a);if(!NF(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(dm(d).map(f=>f.partKey)),u=[];for(let f of l){!r.includes(f.partKey)&&!c.has(f.partKey)&&F(`groupChain: run ${f._id} renders part "${f.partKey}", which node "${t.id}"'s pin does not declare and nobody added`);let m=await e.db.get(f.contractSnapshotId);m===null&&F(`groupChain: run ${f._id} names revision ${f.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:f,snapshot:m})}o.push({packageRunId:a,startedAt:Math.min(...l.map(f=>f._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(f4,"groupRevisionRows");async function dv(e,n,t){let r=await am(e,{applicationId:n,nodeId:t,key:Ts});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${Ts} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(dv,"nodeGroupContracts");async function p4(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await sv(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(p4,"openGroupRequest");async function m4(e,n){let t=[];for(let i of await Xb(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(m4,"toGroupReturn");function CF(e){async function n(i,o,a,l){let d=(await f4(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 p4(i,l);if(d===null)return null;let c=(await om(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 m4(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await dv(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(CF,"groupNodeReads");var h4={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},DF={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},FF={...DF,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},g4={...FF,kind:"eSignature",issuesBy:"provider"},fi={confirm:h4,signedUpload:DF,signedUploadChecked:FF,eSignature:g4};function Ui(e){let n=e.responseStrategy;if(typeof n=="string"&&n in fi)return fi[n];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(Ui,"responseStrategyOf");function LF(e){if(e.type!==cF||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in fi?fi[n].acceptEvent==="contractEvent":!1}s(LF,"isFamilySignedContractNode");function $d(e){return e.label}s($d,"governedDocTitle");function cv(e){return e.approval==="release"?uF:fF}s(cv,"submitActionId");function MF(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[cv(e)],gatesNode:!0,advancesNode:!0}}s(MF,"producerTemplate");function y4(e){return e.titles?.respond??e.label}s(y4,"responseTitle");var pa={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function uv(e){let n=Ui(e),t=[];if(e.production!=="none"&&t.push(MF(e,Fo,e.titles?.prepare??pa),MF(e,Ad,e.titles?.revise??pa)),e.approval==="release"&&t.push({key:Br,recipient:"internal",title:e.titles?.approve??pa,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Lo,recipient:"external",title:y4(e),unlocks:n.producesResponseArtifact?[n.checksReturn?em:n.acceptOutcomeId,n.declineOutcomeId,nm]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...Hb(e)!==void 0?{dueInDays:Hb(e)}:{}}),n.checksReturn&&t.push({key:Ur,recipient:"internal",title:e.titles?.check??pa,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=$d(e);t.push({key:ft,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Mo,qo],gatesNode:!1,advancesNode:!1})}return t}s(uv,"governedDocIntrinsicTemplates");function w4(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(w4,"governedDocSlot");function cm(e){return w4(e).key}s(cm,"governedDocSlotKey");async function k4(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 Qw(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(k4,"toRevision");async function b4(e,n){let t=await k4(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(b4,"toReturn");function qF(e){let n=cm(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;le("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(f=>f._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 b4(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(qF,"artifactNodeReads");function um(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(um,"documentChainKind");function KF(e){switch(um(e)){case"contract":return lm(e).reads;case"group":return CF(e).reads;case"artifact":return qF(e).reads}}s(KF,"documentReadsFor");var v4={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Rd(e){let n=e.responseStrategy;return typeof n=="string"&&n in fi?fi[n].producesResponseArtifact:!1}s(Rd,"returnsSignedCopy");function x4(e){return Rd(e)&&e.confirmContractTerms!==!1}s(x4,"asksContractTerms");function jF(e){return x4(e)?{title:e.contractTermsQuestionText??v4,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(jF,"contractTermsConfirm");async function S4(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:Hy(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Ur||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${Ur} row`),a}s(S4,"rejectedReturnOfAsk");async function BF(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await S4(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(BF,"returnedCopyOfAsk");var fv=new Set([...Yb,Br,Lo,Ur,ft]),zF={id:Kn,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},WF={id:ho,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function A4(e){let n=[],t=[{slot:zF,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:WF,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(Re(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(Re(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=kl(a.value,{type:r.type});d!==null&&n.push(Re(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return n}s(A4,"referenceInputIssues");var E4={id:ui,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},T4={id:qt,type:"legalEntity",label:dF,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function $4(e,n){let t=`inputs.${qt}`,r=e.inputs?.[qt];if(r!==void 0&&r.kind==="binding")return[Re(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=Zp(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(Re(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(Re(e,t,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Xp.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 (${Xp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s($4,"traegerIssues");function pm(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}}:(Ti(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(pm,"generatorFields");function R4(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(R4,"deferredToCockpit");function I4(e){return _i(e.type)?e.type:void 0}s(I4,"resolverSlotType");function O4(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=$d(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(O4,"issueConfirmation");function Re(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Re,"issue");function fm(e){return tm.includes(e.production)&&Bo.includes(e.approval)&&im.includes(e.responseStrategy)}s(fm,"hasValidModes");async function pv(e,n){let t=await Il(e,{applicationId:n.applicationId,nodeId:n.node.id});if(t.length===0)return"pending";let r=t.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&Yb.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Br);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===ft))return"signatureStalled";let a=r.find(l=>l.templateKey===Lo);if(a!==void 0){if(Ui(n.node).issuesBy==="provider"){let d=um(n.node)==="group"?(await dv(e,n.applicationId,n.node.id)).map(c=>c.contractId):[await lm(n.node).contractOrNull(e,n.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&F(`governedDocCurrentState: eSignature node "${n.node.id}" has an open ask but no contract`),await PF(e,d)==="provider")return"awaitingSignature"}return Ui(n.node).producesResponseArtifact?await BF(e,{chain:KF(n.node),applicationId:n.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${n.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Ur)?"responseInCheck":"done"}s(pv,"governedDocCurrentState");function UF(e){return e.production!=="none"&&um(e)!=="artifact"}s(UF,"keepsDocumentInContractDomain");function P4(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!pr(r.key))return[];let i=mo(r.key);if(n.type!==i.type)return[Re(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.key}" ist ${n.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${se(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${n.key}" is ${n.type}, the environment variable "${i.label.en}" (${se(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?[]:[Re(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(P4,"envCoverageIssues");function YF(e,n){let t=[];for(let r of pm(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...P4(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${we(a.address)?se(a.address):JSON.stringify(a.address)}`,en:`a binding to ${we(a.address)?se(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:R4(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(YF,"fieldSourceIssues");function _4(e){let n=mr(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=wF(e.templateStamp,n).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...YF(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(_4,"templateIssues");function N4(e,n){return(n?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(t=>{if(t.documentAnchors===null)return[Re(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?[]:[Re(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(N4,"eSignatureAnchorIssues");function C4(e,n){return n===void 0||n.sendable?[]:Ui(e).issuesBy!=="provider"?[]:[Re(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(C4,"eSignatureProviderIssues");var VF={key:"dokument",label:te("Dokument","Document"),scope:"node"},GF={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:VF,external:en(te("In Vorbereitung","In preparation"),"blue",te("Ihr Dokument wird vorbereitet","Your document is being prepared"),te("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:te("Dokument bereitgestellt","Document issued"),tone:"blue",phase:VF,external:en(te("Dokument bereit","Document ready"),"amber",te("Ihr Dokument liegt bereit","Your document is ready"),te("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),te("Dokument beantworten","Respond to the document"))}},HF={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Fo,"processHoldTemplate"),progressDefaults:GF,progressEvents:Dn(GF),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:"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(!fm(e))return[];let n=Ui(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=n.checksReturn?[...i,"responseInCheck"]:i;return e.production!=="none"&&(t.push({id:cv(e),kind:"internal",surface:fa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...O4(e)??{}}),t.push({id:pF,kind:"internal",surface:fa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:mF,kind:"internal",surface:fa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:em,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:i,external:{emphasis:"decline",event:"userTaskResolved"}}),n.producesResponseArtifact&&t.push({id:nm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Mo,kind:"internal",surface:fa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:qo,kind:"internal",surface:fa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:hF,currentState:pv,workItemTemplates:s(e=>{let n=e;return fm(n)?uv(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e;if(!fm(t)||t.production==="none")return[];let r=uv(t).find(i=>i.key===n);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:cm(t)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[zF,T4]:[],...e.production==="template"?[WF]:[],E4,...pm(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=I4(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"&&Ii(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:hl,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Lo||n===Ad||n===Ur||n===ft){let t=n===Lo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===Ur?{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===ft?{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: ${Fo}${e.approval==="release"?`, ${Br}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${Fo}${e.approval==="release"?`, ${Br}`:""}.`}}return n===Br&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Br}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Br}" 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(UF(n.node))return!1;let t=await pv(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&Ui(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=jF(n.node);if(t===null||UF(n.node))return null;let r=await pv(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!fm(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${tm.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Bo.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${im.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 {${tm.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Bo.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${im.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=fi[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Re(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(Re(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(Re(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 b of o)b.visibility!=="external"&&r.push(Re(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${b.key}" auf Knoten "${e.id}" hat visibility "${b.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${b.key}" on node "${e.id}" has visibility "${b.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(b=>b.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(b=>l.includes(b)))&&r.push(Re(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(b=>`"${b}"`).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(b=>`"${b}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(b=>{let A=c?.[b];return A===null||typeof A!="object"||!Object.values(A??{}).some($=>typeof $=="string"&&$.length>0)},"missingTitle"),f=[];e.production!=="none"&&f.push("prepare","revise"),e.approval==="release"&&f.push("approve"),i.checksReturn&&f.push("check");let m=f.filter(u);m.length>0&&r.push(Re(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${m.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 ${m.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"){let b=y.prepareDocument;(typeof b!="string"||b.length===0)&&r.push(Re(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`}))}if(e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Re(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(Re(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn){let b=y.responseCheck;(typeof b!="string"||b.length===0)&&r.push(Re(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(Re(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(Re(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(Re(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[b,A]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${b} \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 ${b} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let b=y.signingRecovery;(typeof b!="string"||b.length===0)&&r.push(Re(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`}))}else y.signingRecovery!==void 0&&r.push(Re(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`}));if(i.issuesBy==="provider"&&r.push(...N4(e,t),...C4(e,t?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Re(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(Re(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(Re(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.`})),Rd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Re(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[b,A]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${b} \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 ${b} \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[b,A]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${b} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${b} \u2014 without a production phase there is nothing to carry it.`}));for(let b of e.tasks??[])fv.has(b.key)&&r.push(Re(e,`tasks.${b.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${b.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...fv].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${b.key}" on node "${e.id}" collides with an intrinsic template (${[...fv].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...$4(e,t)):e.inputs?.[qt]!==void 0&&r.push(Re(e,`inputs.${qt}`,{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(...A4(e)),e.production==="resolver"){let b=ei(e);if(b!==null){let A=qR(b);for(let $ of pm(e)){if(!_i($.type)){r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/unknownFieldType] Generator "${A}" typisiert das Feld "${$.key}" als "${String($.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Is.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${A}" types the field "${$.key}" as "${String($.type)}" \u2014 that is not part of the platform's value vocabulary (${Is.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if($.type==="personList"){r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${A}" deklariert das Feld "${$.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 "${A}" declares the field "${$.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}$.type==="party"&&($.key.endsWith("PartyId")||r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${$.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 "${$.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...YF(e,{de:`"${A}"`,en:`"${A}"`}))}}else e.generatorStamp!==void 0&&r.push(Re(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(..._4(e)):e.templateStamp!==void 0&&r.push(Re(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?.[ui],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!Ed(g)&&r.push(Re(e,`inputs.${ui}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${Ko} bis ${jo} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${Ko} to ${jo} days is allowed.`})),g===void 0&&pm(e).some(b=>b.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ui}`,{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 mm="countersign",mv="countersign",JF="countersigned",QF="countersigning",ZF="countersigned";var XF={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},Id=["scan","eSignature"],hm="service_provider:1",eL=["countersigning","awaitingSignature","signatureStalled","done"],nL={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function tL(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(tL,"traegerSignatoryMissingReason");function nr(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(nr,"issue");function oL(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&we(r)&&r.scope==="node"&&r.owner===n})}s(oL,"countersignersOf");function Od(e){return e.signing==="eSignature"}s(Od,"isElectronic");function D4(e,n){if(n===void 0||n.sendable||!Od(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[nr(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(D4,"countersignProviderIssues");function F4(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return LF(r)||i.push("sourceNotCheckedContract"),oL(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(F4,"countersignContractRefusals");function rL(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(rL,"validDueInDays");function L4(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!Id.includes(o))return[nr(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[ft];if(!Od(e))return a===void 0?[]:[nr(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(nr(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...M4(e,n,t),...q4(e,n,t),...D4(e,t?.signingProvider)),l}s(L4,"signingIssues");function sL(e,n){let t=e.contract;if(!(!we(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(sL,"contractNodeOf");function M4(e,n,t){let r=sL(e,n),i=r===void 0?null:Zp(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[nr(e,"signing",tL(o.name))]}s(M4,"traegerSignatoryIssues");function q4(e,n,t){let r=sL(e,n);if(r===void 0)return[];let i=t?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(nr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(hm)||l.push(nr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${hm}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${hm}/ \u2014 the provider would find no signature field for the school.`}));return l}s(q4,"traegerAnchorIssues");var hv=100;async function K4(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(hv+1);t.length>hv&&F(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${hv} rows`);let r=t.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===ft)?"signatureStalled":r.some(o=>i(o)===mm)?"countersigning":Od(n.node)?"awaitingSignature":"done"}s(K4,"countersignCurrentState");var iL={[QF]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:en(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},aL={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:JF,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:iL,progressEvents:Dn(iL),notificationEvents:s(()=>[{id:ZF,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:mv,kind:"internal",label:XF,surface:er,availableIn:["countersigning"]},...Od(e)?[{id:Mo,kind:"internal",surface:er,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:qo,kind:"internal",surface:er,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:mm,recipient:"internal",title:e.titles?.countersign??pa,unlocks:[mv],advancesNode:!0,...rL(e)!==void 0?{dueInDays:rL(e)}:{}},...Od(e)?[{key:ft,recipient:"internal",title:nL,unlocks:[Mo,qo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:eL,currentState:K4,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[mm];(typeof a!="string"||a.length===0)&&r.push(nr(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Ti(e.titles?.countersign)||r.push(nr(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(nr(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...L4(e,n,t));let d=e.contract;if(!we(d))return r;let c=F4(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(f=>d.scope==="node"&&f.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(nr(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let f=oL(n,u.id).filter(m=>m.id!==e.id);r.push(nr(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${f.map(m=>`"${m.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${f.map(m=>`"${m.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};var lL={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 Kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Kt,"isRecord");var gv=["field","join","literal","address","payment","contract"],j4=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),B4=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function tr(e){return typeof e=="string"&&e.trim().length>0}s(tr,"nonEmptyString");function gm(e,n,t,r,i="value"){if(!Kt(e)||!Kt(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=gv.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${gv.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${gv.join(" | ")}).`}});return}let[l]=a;l==="field"&&!tr(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(tr))&&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)||tr(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"&&pr(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&&!j4.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&&!(tr(e.lookup)&&Kt(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"||Kt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Kt(d)&&B4.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(gm,"checkMapping");function Vi(e,n,t,r,i){if(!Kt(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=lL[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))gm(l,`${n}.${a}`,r,i)}s(Vi,"checkBody");function dL(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(!Kt(o)||!tr(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),gm(o.value,`${l}.value`,t,r),o.unless!==void 0&&gm(o.unless,`${l}.unless`,t,r,"condition")})}s(dL,"checkAif");function yv(e){let n=[];if(!Kt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Kt(e.lookups)?e.lookups:{};Kt(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))(!Kt(i)||!Object.values(i).every(tr))&&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(tr(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Vi(e.pupil,"engage.pupil","addPupil",t,n),Vi(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&Vi(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&Vi(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&Vi(e.medical,"engage.medical","addMedical",t,n),dL(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(!Kt(i)||!tr(i.key)||!tr(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),Vi(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&Vi(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,f)=>Vi(u,`${a}.${l}[${f}]`,d,t,n))}}dL(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&gm(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Kt(r)||!tr(r.repeated)||!tr(r.field)||!tr(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(yv,"engagePushConfigIssues");function*wv(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(wv,"mappingsOf");function cL(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of wv(e))for(let i of U4(t.from))n.add(V4(i,r));return[...n]}s(cL,"configFieldKeys");function U4(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(U4,"formFieldsOf");function V4(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s(V4,"resolveFieldKey");function uL(e,n){for(let{mapping:t}of wv(e))if(n in t.from)return!0;return!1}s(uL,"configReadsSource");function fL(e){let n=new Set;for(let{mapping:t}of wv(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(fL,"configEnvLeaves");var pL="done",mL=["sandbox","production"];var ym="engagePush",rPe=660*1e3;function Gi(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(Gi,"issue");function kv(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(kv,"literal");function hL(e){return yv(e.engage).length===0?e.engage:null}s(hL,"validConfig");function G4(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(G4,"bypassingPath");var gL={role:"system-action",effect:"side-effect",outcomes:[{id:pL,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=hL(e);return n===null?[]:fL(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=kv(e,"target");mL.includes(a)||o.push(Gi(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=kv(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Gi(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[ym];(typeof d!="string"||d.length===0)&&o.push(Gi(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${ym}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${ym}\` names the team.`}));for(let g of yv(e.engage))o.push(Gi(e,g.path,{de:`[engagePush/config] \u201E${r}": ${g.message.de}`,en:`[engagePush/config] "${i}": ${g.message.en}`}));let c=n.nodes.filter(g=>g.id!==e.id&&g.type==="engagePush"&&kv(g,"target")===a);c.length>0&&o.push(Gi(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(g=>`"${g.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(g=>`"${g.id}"`).join(", ")} already transfers to the same target.`})),G4(n,e.id)&&o.push(Gi(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let u=hL(e),f=e;for(let[g,b,A,$]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!uL(u,g)||f[b]!==void 0||o.push(Gi(e,b,{de:Ns("address/missing",{where:`\u201E${r}\u201C \u203A ${A}`},"de"),en:Ns("address/missing",{where:`"${i}" \u203A ${$}`},"en")}));let m=f.form,y=we(m)&&m.scope==="node"?m.owner:void 0,k=y===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(y);if(u!==null&&k!==void 0){let g=new Set(k.keys()),b=cL(u).filter(A=>!g.has(A)&&!/\[\d+\]\./.test(A));if(b.length>0){let A=n.nodes.find($=>$.id===y);o.push(Gi(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${A?.label?.de??y}" nicht \u2014 sie werden nicht \xFCbertragen: ${b.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${A?.label?.en||y}" does not know these fields \u2014 they are not transferred: ${b.join(", ")}.`},"warning"))}}return o},"validate")};var Uo={join:$D,end:EO,roleAssign:ID,eventTrigger:OD,waitlist:zD,completenessCheck:eF,form:LD,setFlag:MD,if:qD,decision:Do,review:tF,collectPayment:lF,governedDocument:HF,countersign:aL,engagePush:gL};TI(Uo);function yL(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(yL,"graphOf");function wL(e){let n=new Map;for(let t of e.nodes)for(let r of Dr(e,t))n.set(se(r.address),r.nodeId);return n}s(wL,"producedOf");function kL(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(bo(e,t).map(r=>se(r.address))));return n}s(kL,"readsOf");function bL(e,n){let t=yL(e,"bundle"),r=yL(n.graph,"live head"),i=wL(t),o=wL(r),a={added:[],removed:[],moved:[]};for(let[u,f]of i){let m=o.get(u);m===void 0?a.added.push({address:u,nodeId:f}):m!==f&&a.moved.push({address:u,from:m,to:f})}for(let[u,f]of o)i.has(u)||a.removed.push({address:u,nodeId:f});let l=kL(t),d=kL(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let f=l.get(u)??new Set,m=d.get(u)??new Set,y=[...f].filter(g=>!m.has(g)),k=[...m].filter(g=>!f.has(g));(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(bL,"planAddresses");function vL(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(vL,"addressPlanRows");function xL(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(xL,"changed");async function SL(e,n,t){if(n.index.module!==Pb.name)throw new Error(`offer: unknown module "${n.index.module}"`);return K_(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return Pb.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(SL,"applyOffer");async function AL(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(AL,"exportOffer");async function bv(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 g=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=g?.def?xL(k,{label:g.def.label,...g.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=xL(k&&{graph:ks(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:ks(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=bL(n.workflow.graph,y))}}let c=t.program?.stages,u=c===void 0?[]:i?await Ob(e,t.tenant,t.slugs.manifest,c):Up(null,[],c),f=await Yp(e,t.tenant,i?t.slugs.manifest:null,t),m=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:f,publishPending:m?.draftDiffersFromExternal??null,draftRevision:m?.draftRevision??null,externalHeadRevision:m?.externalHeadRevision??null}}s(bv,"diffOffer");function wm(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(wm,"contractProductionModeOf");function EL(e){return wm(e)==="resolver"}s(EL,"isResolverCarrierNode");function km(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=ei(t);return!EL(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(km,"authoredPins");var TL={type:"address",dataType:"composite"};var $L={type:"boolean",dataType:"boolean"};var RL={type:"consent",dataType:"boolean"};var IL={type:"date",dataType:"date"};var OL={type:"docRef",dataType:"file"};var PL={type:"email",dataType:"text"};var _L={type:"enum",dataType:"option"};var NL={type:"string",dataType:"text"};var CL={type:"tel",dataType:"text"};var bm={address:TL.dataType,boolean:$L.dataType,consent:RL.dataType,date:IL.dataType,docRef:OL.dataType,email:PL.dataType,enum:_L.dataType,string:NL.dataType,tel:CL.dataType};function vv(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(vv,"shapeOf");function DL(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,vv(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,vv(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}`,vv(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(DL,"fieldMapScopes");function z4(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(z4,"computedKeysOf");function FL(e){let n=[],t=z4(e);for(let r of DL(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(FL,"validateFieldMapSources");function LL(e){let n=[],t=new Set;for(let o of DL(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(LL,"validateFieldPersistence");var W4="$";function Y4(e){return typeof e=="string"&&e.startsWith(W4)}s(Y4,"isRef");function vm(e){return e.slice(1)}s(vm,"stripRef");function*H4(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(H4,"refSlots");function J4(e){let n=new Set;for(let t of H4(e))Y4(t)&&n.add(vm(t));return[...n]}s(J4,"collectRefs");function Q4(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 J4(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=vm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&vm(l.target)===a||l.kind==="shareValue"&&vm(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(Q4,"buildAdjacency");function ML(e){let{refsOf:n}=Q4(e),r=Yf(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(ML,"detectCycle");function qL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(qL,"escapeRegExp");function zi(e){return new RegExp(`^${qL(e)}\\[(\\d+)\\]\\.(.+)$`)}s(zi,"repeatedRowKeyPattern");function xv(e,n){let t=zi(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(xv,"countRepeatedRows");function KL(e,n,t){let r=zi(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(KL,"repeatedRowHasData");function jL(e){return e.endsWith(".count")?e.slice(0,-6):e}s(jL,"readKeyOf");function Sv(e){return{sections:e,fields:[]}}s(Sv,"hiddenSectionsOnly");function BL(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??[])BL(r,n,t)}s(BL,"collectKeys");function UL(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;BL(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(zi)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(UL,"restrictedSectionsOf");function VL(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(VL,"matchesKey");function Z4(e,n){return n.find(t=>VL(e,t))??null}s(Z4,"hiddenSectionOfKey");function X4(e,n){for(let t=e;;){if(VL(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(X4,"fieldOwnsKey");function e5(e,n){return n.find(t=>X4(e,t))??null}s(e5,"restrictedFieldOfKey");function n5(e,n){let t=Z4(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=e5(e,n.fields);return r===null?null:{kind:"field",field:r}}s(n5,"hiddenOwnerOfKey");function xm(e,n){return n5(e,n)!==null}s(xm,"isKeyHidden");function t5(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(t5,"visibleToListIssues");function GL(e,n,t){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...t5(c.id,m,`${u}.visibleTo`,f,t));let y=f||m!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(g=>g.fields),...(c.repeated??[]).flatMap(g=>g.itemTemplate)];for(let g of k)g.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${g.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${g.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,g)=>i(k,`${u}.subsections[${g}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=UL(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Sv(f);for(let y of bn(c)){let k=jL(y);(xm(y,m)||xm(k,m))&&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,f)=>{a(c.visibleIf,`${u}.visibleIf`,f),a(c.requiredIf,`${u}.requiredIf`,f),a(c.disabledIf,`${u}.disabledIf`,f),a(c.defaultValue,`${u}.defaultValue`,f),c.sameAs!==void 0&&xm(c.sameAs.source,Sv(f))&&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,f)=>{let m=c.visibleTo!==void 0?c.id:f,y=o.filter(k=>k.sectionId!==m);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,g)=>l(k,`${u}.fields[${g}]`,y)),c.groups?.forEach((k,g)=>{a(k.visibleIf,`${u}.groups[${g}].visibleIf`,y),k.fields.forEach((b,A)=>l(b,`${u}.groups[${g}].fields[${A}]`,y))}),c.repeated?.forEach((k,g)=>{a(k.itemVisibleIf,`${u}.repeated[${g}].itemVisibleIf`,y),k.itemTemplate.forEach((b,A)=>l(b,`${u}.repeated[${g}].itemTemplate[${A}]`,y))}),c.computed?.forEach((k,g)=>a(k.expression,`${u}.computed[${g}]`,y)),c.subsections?.forEach((k,g)=>d(k,`${u}.subsections[${g}]`,m))},"visitCompiled");return n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(GL,"sectionVisibilityIssues");var Vr="#";var zL=s(e=>{let n=Hw.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),br={firstName:zL("persons.firstName"),lastName:zL("persons.lastName")};function WL(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===br.firstName?t.firstName.push(o):a===br.lastName&&t.lastName.push(o);return t}s(WL,"personNameKeys");function YL(e){return[...e.firstName,...e.lastName]}s(YL,"personNameKeyList");function HL(e){return e.firstName.length>0||e.lastName.length>0}s(HL,"hasPersonName");function ma(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 ma(i.subsections??[],a,i.id))r.push(l)}),r}s(ma,"walkSections");function r5(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(r5,"findFieldInSection");function JL(e,n){for(let t of ma(e.sections)){let r=r5(t.section,n);if(r)return{section:t.section,field:r}}return null}s(JL,"findField");var i5=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],o5=["blue","rose","amber","violet","teal","emerald","slate"];function QL(e){return i5.includes(e)}s(QL,"isBucketIconName");function ZL(e){return o5.includes(e)}s(ZL,"isBucketColorName");var s5="__clear__";function XL(e){return e===""?"empty":e===s5?"reserved":null}s(XL,"selectOptionValueDefect");var nNe=Object.freeze({});function a5(e,n){return Object.freeze(Uf(Zr,e,n))}s(a5,"formContextEntries");function e0(e){return e.env??[]}s(e0,"declaredContextKeys");function n0(e,n){return e0(e).every(t=>t0(t,n?.[t]))}s(n0,"scenarioContextComplete");function t0(e,n){return iP(Zr,e,n)}s(t0,"contextValueComplete");function r0(e,n){return a5(n??{},e0(e))}s(r0,"scenarioContextEntries");function Ev(e){return _l(e)}s(Ev,"isContextIdentifier");function l5(e,n,t){let r=Bf(Zr,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(l5,"contextIdentifierIssue");var Av=nf("stage.key");function d5(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===Av,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),n}s(d5,"stageKeyLiterals");function i0(e,n,t){return n===void 0?[]:d5(e).filter(r=>!n.has(r)).map(r=>s0(r,n,t))}s(i0,"stageKeyAstIssues");function o0(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(s0(i.key,n,`scenario:${r.id}/env`))}return t}s(o0,"scenarioStageKeyIssues");function s0(e,n,t){let r=[...n].sort();return{severity:"error",path:t,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${Av}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${Av}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(s0,"unknownStageKeyIssue");function a0(e,n,t){let r=[];for(let i of bn(e)){if(!Ev(i))continue;let o=l5(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Zy(e,Xu))r.push({severity:"error",path:t,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(a0,"contextAstIssues");function l0(e,n){let t=[...c5(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!ws(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ys.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ys.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>ws(a)&&!t0(a,i.env?.[a]));o.length>0&&t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))ws(a)?r.has(a)||t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return t}s(l0,"formContextIssues");function c5(e){let n=[];Object.hasOwn(e,"context")&&n.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return n}s(c5,"retiredContextFields");var Tv=UN.docRef.allowedMime;function m0(e,n={}){let t=Js(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 f(P,_){if(i.has(P))return;i.add(P);let q=o.get(P.id);q&&q!==P?r.push({severity:"error",path:`sections[${_.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${P.id}' ist mehrfach deklariert.`,en:`Section id '${P.id}' is declared more than once.`}}):o.set(P.id,P);let C=`sections[${_.join(".")}]`;P.fields.forEach((G,ae)=>{ha(a,G.key,`${C}.fields[${ae}]`,"duplicate.field-key",r),l.add(G.key),u.set(G.key,G),c.set(G.key,Rv(G)),G.externalFlag&&(G.type!=="boolean"&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${G.key}' muss den Typ 'boolean' haben (ist '${G.type}').`,en:`External flag '${G.key}' must be type 'boolean' (got '${G.type}').`}}),G.reviewRequired!==void 0&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"review.on-flag",message:{de:`Externes Flag '${G.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 '${G.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),G.notice!==void 0&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${G.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${G.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),G.defaultValue==null&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"flag.missing-default",message:{de:`Externes Flag '${G.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${G.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...c0(G,`${C}.fields[${ae}]`)),r.push(...d0(G,`${C}.fields[${ae}]`))}),P.groups?.forEach((G,ae)=>{G.fields.forEach((de,Ne)=>{ha(a,de.key,`${C}.groups[${ae}].fields[${Ne}]`,"duplicate.field-key",r),l.add(de.key),u.set(de.key,de),c.set(de.key,Rv(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.groups[${ae}].fields[${Ne}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${de.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${de.key}' must be a direct section field, not a group field.`}}),r.push(...c0(de,`${C}.groups[${ae}].fields[${Ne}]`)),r.push(...d0(de,`${C}.groups[${ae}].fields[${Ne}]`))})}),P.repeated?.forEach((G,ae)=>{G.itemTemplate.forEach((de,Ne)=>{ha(a,de.key,`${C}.repeated[${ae}].itemTemplate[${Ne}]`,"duplicate.field-key",r),c.set(de.key,Rv(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${de.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${de.key}' must be a direct section field, not a repeated item field.`}}),de.export&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"export.in-repeated",message:{de:`Feld '${de.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${de.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),de.sameAs&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${de.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${de.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),de.reviewRequired!==void 0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"review.in-repeated",message:{de:`Feld '${de.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 '${de.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.`}}),de.notice!==void 0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.notice-in-repeated",message:{de:`Feld '${de.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 '${de.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),de.type==="docRef"&&de.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${de.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${de.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),P.computed?.forEach(G=>{d.add(G.key),ha(a,G.key,`${C}.computed[${G.key}]`,"duplicate.field-key",r),G.exportType==="consent"&&r.push({severity:"error",path:`${C}.computed[${G.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${G.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${G.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),G.export===!0&&G.exportType===void 0&&r.push({severity:"error",path:`${C}.computed[${G.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${G.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${G.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),P.subsections?.forEach((G,ae)=>f(G,[..._,ae]))}s(f,"visitRawSection"),e.sections.forEach((P,_)=>f(P,[_]));let m=new Set;t.effects.forEach((P,_)=>{ha(m,P.id,`effects[${_}]`,"duplicate.effect-id",r)});let y=new Set;t.outcomes.forEach((P,_)=>{ha(y,P.id,`outcomes[${_}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((P,_)=>{P.output.effectRefs?.forEach((q,C)=>{m.has(q.effect)||r.push({severity:"error",path:`outcomes[${_}].output.effectRefs[${C}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${P.id}' verweist auf den unbekannten Effekt '${q.effect}'.`,en:`Outcome '${P.id}' references unknown effect '${q.effect}'.`}})})}),t.outcomes.forEach((P,_)=>{P.output.fields?.forEach((q,C)=>{JL(t,q.path)||r.push({severity:"error",path:`outcomes[${_}].output.fields[${C}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${P.id}' verweist auf das unbekannte Feld '${q.path}'.`,en:`Outcome '${P.id}' references unknown field '${q.path}'.`}})})});let k=new Set;for(let P of ma(t.sections))for(let _ of P.section.repeated??[])k.add(`${_.key}.count`);for(let P of k)(a.has(P)||d.has(P))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${P}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${P}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:n.stageKeys};r.push(...l0(e)),r.push(...GL(e,t,n.visibleToKeys)),r.push(...o0(e,n.stageKeys));for(let P of ma(t.sections)){let _=P.section,q=`sections[${P.path.join(".")}]`;_.visibleIf&&(vr(_.visibleIf,`${q}.visibleIf`,g,!1,r),ga(_.visibleIf,`${q}.visibleIf`,c,r)),_.fields.forEach((C,G)=>$v(C,`${q}.fields[${G}]`,g,!1,c,r)),_.groups?.forEach((C,G)=>{C.visibleIf&&(vr(C.visibleIf,`${q}.groups[${G}].visibleIf`,g,!1,r),ga(C.visibleIf,`${q}.groups[${G}].visibleIf`,c,r)),C.fields.forEach((ae,de)=>$v(ae,`${q}.groups[${G}].fields[${de}]`,g,!1,c,r))}),_.repeated?.forEach((C,G)=>{C.itemVisibleIf&&(vr(C.itemVisibleIf,`${q}.repeated[${G}].itemVisibleIf`,g,!0,r),ga(C.itemVisibleIf,`${q}.repeated[${G}].itemVisibleIf`,c,r)),C.itemTemplate.forEach((ae,de)=>$v(ae,`${q}.repeated[${G}].itemTemplate[${de}]`,g,!0,c,r)),C.effects?.forEach((ae,de)=>{ae.when&&vr(ae.when,`${q}.repeated[${G}].effects[${de}].when`,g,!0,r)})}),_.computed?.forEach((C,G)=>vr(C.expression,`${q}.computed[${G}].expression`,g,!1,r))}t.effects.forEach((P,_)=>{P.when&&vr(P.when,`effects[${_}].when`,g,!1,r)}),t.outcomes.forEach((P,_)=>{vr(P.when,`outcomes[${_}].when`,g,!1,r)});let b=new Set(t.outcomes.map(P=>P.id));function A(P,_){P.requiredFor&&P.requiredFor.forEach((q,C)=>{b.has(q)||r.push({severity:"error",path:`${_}.requiredFor[${C}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${P.key}": requiredFor verweist auf das unbekannte Ergebnis "${q}"`,en:`field "${P.key}": requiredFor references unknown outcome "${q}"`}})})}s(A,"checkRequiredFor");for(let P of ma(t.sections)){let _=P.section,q=`sections[${P.path.join(".")}]`;_.fields.forEach((C,G)=>A(C,`${q}.fields[${G}]`)),_.groups?.forEach((C,G)=>{C.fields.forEach((ae,de)=>A(ae,`${q}.groups[${G}].fields[${de}]`))}),_.repeated?.forEach((C,G)=>{C.itemTemplate.forEach((ae,de)=>A(ae,`${q}.repeated[${G}].itemTemplate[${de}]`))})}function $(P,_){let q=s((C,G)=>{let ae=(C.type==="docRef"?C.docRefConstraints?.mimeType??[]:[]).filter(Ae=>!Tv.includes(Ae));ae.length>0&&r.push({severity:"error",path:G,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${C.key}' erlaubt ${ae.map(Ae=>`'${Ae}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Tv.join(", ")}).`,en:`Field '${C.key}' allows ${ae.map(Ae=>`'${Ae}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Tv.join(", ")}).`}});let de=C.type==="docRef"?C.docRefConstraints?.minFiles:void 0;if(de!==void 0){let Ae=C.docRefConstraints?.multiple===!0,pn=typeof de=="number"&&Number.isInteger(de)&&de>=2;(!Ae||!pn)&&r.push({severity:"error",path:G,code:"config.docref-min-files",message:Ae?{de:`Feld '${C.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(de)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${C.key}' sets docRefConstraints.minFiles to ${JSON.stringify(de)} \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:G,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:G,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:G,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(...f5(C,G)),typeof C.minSelections=="number"&&typeof C.maxSelections=="number"&&C.minSelections>C.maxSelections&&r.push({severity:"error",path:G,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}).`}});let Ne=C.enumRef;Ne!==void 0&&r.push({severity:"error",path:`${G}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${C.key}' nennt den entfernten Options-Katalog (enumRef '${String(Ne)}'). 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(Ne)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(C.enumOptions??[]).forEach((Ae,pn)=>{let Je=XL(Ae);Je!==null&&r.push({severity:"error",path:`${G}.enumOptions[${pn}]`,code:"config.enum-option-value",message:{de:Je==="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 '${Ae}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Je==="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 '${Ae}', which the single select reserves for its clear row. Rename the option.`}})}),(C.attachments??[]).forEach((Ae,pn)=>{if("storageId"in Ae){r.push({severity:"error",path:`${G}.attachments[${pn}]`,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 Je=Ae.fileKey!==void 0&&Ae.fileKey!=="",xn=Ae.url!==void 0&&Ae.url!=="";Je===xn&&r.push({severity:"error",path:`${G}.attachments[${pn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Je&&xn?"beide":"keines"}).`,en:`Field '${C.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Je&&xn?"both":"neither"}).`}}),Ae.renderAs==="inlineLink"&&Ae.label===void 0&&r.push({severity:"error",path:`${G}.attachments[${pn}]`,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");P.fields.forEach((C,G)=>q(C,`${_}.fields[${G}]`)),P.groups?.forEach((C,G)=>{C.fields.forEach((ae,de)=>q(ae,`${_}.groups[${G}].fields[${de}]`))}),P.repeated?.forEach((C,G)=>{C.itemTemplate.forEach((ae,de)=>{let Ne=`${_}.repeated[${G}].itemTemplate[${de}]`;q(ae,Ne),ae.type==="consent"&&r.push({severity:"error",path:Ne,code:"config.consent-in-repeated",message:{de:`Feld '${ae.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${ae.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),P.subsections?.forEach((C,G)=>$(C,`${_}.subsections[${G}]`))}s($,"visitFieldConfig"),e.sections.forEach((P,_)=>$(P,`sections[${_}]`)),e.effects.forEach((P,_)=>{if(P.kind==="person"){r.push(...p0(P,e.effects,`effects[${_}]`,q=>l.has(q)));return}P.kind==="organization"&&P.nameFrom?.forEach((q,C)=>{l.has(q)||r.push({severity:"error",path:`effects[${_}].nameFrom[${C}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${P.id}': nameFrom verweist auf das unbekannte Feld '${q}'.`,en:`Effect '${P.id}' nameFrom references unknown field '${q}'.`}})})});let O=s((P,_)=>{if(P.kind!=="person"&&P.kind!=="organization")return;let q=P.display;if(!q){r.push({severity:"error",path:`${_}.display`,code:"display.missing",message:{de:`Effekt '${P.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${P.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}QL(q.icon)||r.push({severity:"error",path:`${_}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${P.id}': display.icon '${q.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${P.id}' display.icon '${q.icon}' is not a known bucket icon.`}}),ZL(q.color)||r.push({severity:"error",path:`${_}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${P.id}': display.color '${q.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${P.id}' display.color '${q.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((P,_)=>O(P,`effects[${_}]`));let E=new Set,I=s(P=>{P.kind==="person"?E.add(P.bucket):P.kind==="organization"&&E.add(P.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(I);let v=new Set,R=s(P=>{for(let _ of P)_.repeated?.forEach(q=>q.effects?.forEach(C=>I(C))),R(_.subsections??[])},"collectRepeatedBuckets");R(e.sections);let K=s((P,_)=>{E.size!==0&&P.forEach((q,C)=>{q.bucket===void 0||E.has(q.bucket)||r.push({severity:"error",path:`${_}[${C}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${q.key}' geh\xF6rt zum Bucket '${q.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${q.key}' belongs to bucket '${q.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),N=s((P,_)=>{if(v.has(P))return;v.add(P);let q=`sections[${_.join(".")}]`;K(P.fields,`${q}.fields`),P.groups?.forEach((C,G)=>K(C.fields,`${q}.groups[${G}].fields`)),P.repeated?.forEach((C,G)=>K(C.itemTemplate,`${q}.repeated[${G}].itemTemplate`)),P.subsections?.forEach((C,G)=>N(C,[..._,G]))},"visitBucketSection");e.sections.forEach((P,_)=>N(P,[_]));let Y=e.effects.flatMap((P,_)=>P.kind==="person"&&P.subject===!0?[{e:P,i:_}]:[]);Y.length>1&&Y.slice(1).forEach(({e:P,i:_})=>{r.push({severity:"error",path:`effects[${_}].subject`,code:"subject.duplicate",message:{de:`Effekt '${P.id}' deklariert subject:true, aber '${Y[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${P.id}' declares subject:true, but '${Y[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((P,_)=>{if(!(P.kind!=="person"||P.nationalityFrom===void 0)){if(P.subject!==!0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${P.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 '${P.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(P.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${P.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${P.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}P.nationalityFrom.forEach((q,C)=>{l.has(q)||r.push({severity:"error",path:`effects[${_}].nationalityFrom[${C}]`,code:"nationality.unknown-field",message:{de:`Effekt '${P.id}': nationalityFrom verweist auf das unbekannte Feld '${q}'.`,en:`Effect '${P.id}' nationalityFrom references unknown field '${q}'.`}})})}});let H=e.effects.flatMap((P,_)=>P.kind==="person"&&P.contractParty!==void 0?[{e:P,i:_,decl:P.contractParty}]:[]);if(H.length>0){let P=new Map;H.forEach(({e:q,i:C})=>{let G=P.get(q.bucket);if(G===void 0){P.set(q.bucket,q.id);return}r.push({severity:"error",path:`effects[${C}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${q.id}' deklariert eine Vertragspartei auf Bucket '${q.bucket}', aber '${G}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${q.id}' declares a contract party on bucket '${q.bucket}', but '${G}' already does. A bucket is at most one contract party.`}})});let _=H.filter(({decl:q})=>q.role==="beneficiary");_.slice(1).forEach(({e:q,i:C})=>{r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${q.id}' deklariert contractParty.role 'beneficiary', aber '${_[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${q.id}' declares contractParty.role 'beneficiary', but '${_[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),_.forEach(({e:q,i:C})=>{q.subject!==!0&&r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${q.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 '${q.id}' setzen.`,en:`Effect '${q.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 '${q.id}'.`}})}),Y.forEach(({e:q,i:C})=>{let G=q.contractParty?.role;G!==void 0&&G!=="beneficiary"&&r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${q.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${G}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${q.id}' is the application subject but declares contractParty.role '${G}'. The application subject is the contract beneficiary.`}})}),H.some(({decl:q})=>q.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((P,_)=>{P.kind==="fieldMap"&&P.mappings.forEach((q,C)=>{a.has(q.from)||r.push({severity:"error",path:`effects[${_}].mappings[${C}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${P.id}': fieldMap from '${q.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${P.id}' fieldMap from '${q.from}' references unknown field.`}})})});for(let[P,_]of u){if(!_.sameAs)continue;let q=`fields[${P}].sameAs`,C=u.get(_.sameAs.source);C===void 0||_.sameAs.source===P?r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:_.sameAs.source===P?`Feld '${P}': sameAs.source verweist auf sich selbst.`:`Feld '${P}': sameAs.source verweist auf das unbekannte Feld '${_.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:_.sameAs.source===P?`Field '${P}' sameAs.source references itself.`:`Field '${P}' sameAs.source references unknown field '${_.sameAs.source}' (must be a top-level or group field).`}}):C.type!==_.type?r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}' (${_.type}): sameAs.source '${_.sameAs.source}' hat einen anderen Typ (${C.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${P}' (${_.type}) sameAs.source '${_.sameAs.source}' has a different type (${C.type}) \u2014 the mirror must be shape-identical.`}}):C.sameAs&&r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}': sameAs.source '${_.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${P}' sameAs.source '${_.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let G=u.get(_.sameAs.toggle);(G===void 0||G.type!=="boolean")&&r.push({severity:"error",path:`${q}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:G===void 0?`Feld '${P}': sameAs.toggle verweist auf das unbekannte Feld '${_.sameAs.toggle}'.`:`Feld '${P}': sameAs.toggle '${_.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${G.type}').`,en:G===void 0?`Field '${P}' sameAs.toggle references unknown field '${_.sameAs.toggle}'.`:`Field '${P}' sameAs.toggle '${_.sameAs.toggle}' must be type 'boolean' (got '${G.type}').`}}),_.required===!0&&r.push({severity:"error",path:`fields[${P}].required`,code:"config.sameas-static-required",message:{de:`Feld '${P}' 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: "${_.sameAs.toggle} != true" verwenden.`,en:`Field '${P}' 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: "${_.sameAs.toggle} != true".`}})}{let P=new Map;e.effects.forEach(_=>P.set(_.id,_.kind)),e.effects.forEach((_,q)=>{if(_.kind!=="shareValue")return;[["from",_.from],["to",_.to]].forEach(([ae,de])=>{let Ne=P.get(de.slice(1));Ne!==void 0&&Ne!=="person"&&Ne!=="organization"&&r.push({severity:"error",path:`effects[${q}].${ae}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${_.id}': shareValue ${ae} '${de}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${Ne}').`,en:`Effect '${_.id}' shareValue ${ae} '${de}' must reference a person/organization effect (got '${Ne}').`}})});let C=_.from.slice(1);e.effects.some(ae=>ae.kind==="fieldMap"&&ae.target.slice(1)===C&&ae.mappings.some(de=>de.to===_.field)||ae.kind==="shareValue"&&ae.id!==_.id&&ae.to.slice(1)===C&&ae.field===_.field)||r.push({severity:"error",path:`effects[${q}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${_.id}' teilt das Feld '${_.field}' aus '${_.from}', aber kein fieldMap mit Ziel '${_.from}' bildet auf '${_.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${_.id}' shares field '${_.field}' from '${_.from}', but no fieldMap targeting '${_.from}' maps to '${_.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((P,_)=>{P.kind==="person"&&P.bucket.includes(Vr)&&r.push({severity:"error",path:`effects[${_}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': bucket '${P.bucket}' darf '${Vr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' bucket '${P.bucket}' must not contain '${Vr}' (reserved for the per-row namespace).`}}),P.kind==="organization"&&P.orgKind.includes(Vr)&&r.push({severity:"error",path:`effects[${_}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': orgKind '${P.orgKind}' darf '${Vr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' orgKind '${P.orgKind}' must not contain '${Vr}' (reserved for the per-row namespace).`}})});let ue=new Set;function Q(P,_){P.repeated?.forEach((q,C)=>{let G=q.effects??[];if(G.length>0){let ae=`${_}.repeated[${C}]`,de=new Set(G.map(ie=>ie.id)),Ne=new Set(q.itemTemplate.map(ie=>ie.key)),Ae=(q.uniqueBy?.length??0)>0,pn=s(ie=>ie.startsWith("$item.")?Ne.has(ie.slice(6)):l.has(ie),"resolvesName"),Je=s(ie=>ie.startsWith("$item.")?Ne.has(ie.slice(6)):a.has(ie),"resolvesFrom"),xn=s(ie=>{let Ln=ie.slice(1);return de.has(Ln)||m.has(Ln)},"resolvesRef");G.forEach((ie,Ln)=>{let mn=`${ae}.effects[${Ln}]`;if(m.has(ie.id)||ue.has(ie.id)?r.push({severity:"error",path:mn,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${ie.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${ie.id}' is declared more than once.`}}):ue.add(ie.id),ie.kind==="person"||ie.kind==="organization"){O(ie,mn),ie.kind==="person"&&ie.subject===!0&&r.push({severity:"error",path:`${mn}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${ie.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 '${ie.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.`}}),ie.kind==="person"&&ie.nationalityFrom!==void 0&&r.push({severity:"error",path:`${mn}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${ie.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${ie.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),ie.kind==="person"&&ie.contractParty!==void 0&&r.push({severity:"error",path:`${mn}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${ie.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 '${ie.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ae||r.push({severity:"error",path:ae,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${q.key}' hat einen Parteien erzeugenden Effekt '${ie.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${q.key}' has a party-creating effect '${ie.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Ce=ie.kind==="person"?ie.bucket:ie.orgKind;Ce.includes(Vr)&&r.push({severity:"error",path:`${mn}.${ie.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${ie.id}' der Wiederholung: ${ie.kind==="person"?"bucket":"orgKind"} '${Ce}' darf '${Vr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ce}' must not contain '${Vr}'.`}}),ie.kind==="person"&&r.push(...p0(ie,G,mn,pn)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ve,Ot)=>{pn(Ve)||r.push({severity:"error",path:`${mn}.nameFrom[${Ot}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${ie.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Ve}'.`,en:`Repeated effect '${ie.id}' nameFrom references unknown field '${Ve}'.`}})}),ie.identity?.strategy==="keyed"&&ie.identity.keyFrom.forEach((Ve,Ot)=>{Je(Ve)||r.push({severity:"error",path:`${mn}.identity.keyFrom[${Ot}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${ie.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Ve}'.`,en:`Repeated effect '${ie.id}' identity.keyFrom references unknown field '${Ve}'.`}})})}else if(ie.kind==="relationship"){if([["from",ie.from],["to",ie.to]].forEach(([Ce,Ve])=>{xn(Ve)||r.push({severity:"error",path:`${mn}.${Ce}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: ${Ce} verweist auf den unbekannten Effekt '${Ve}'.`,en:`Repeated relationship '${ie.id}' ${Ce} references unknown effect '${Ve}'.`}})}),ie.meta)for(let[Ce,Ve]of Object.entries(ie.meta))typeof Ve=="string"&&Ve.startsWith("$")&&!xn(Ve)&&r.push({severity:"error",path:`${mn}.meta.${Ce}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: meta.${Ce} verweist auf den unbekannten Effekt '${Ve}'.`,en:`Repeated relationship '${ie.id}' meta.${Ce} references unknown effect '${Ve}'.`}})}else ie.kind==="fieldMap"?(xn(ie.target)||r.push({severity:"error",path:`${mn}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${ie.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${ie.target}'.`,en:`Repeated fieldMap '${ie.id}' target references unknown effect '${ie.target}'.`}}),ie.mappings.forEach((Ce,Ve)=>{Je(Ce.from)||r.push({severity:"error",path:`${mn}.mappings[${Ve}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${ie.id}' der Wiederholung: from '${Ce.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${ie.id}' from '${Ce.from}' references unknown field.`}})})):ie.kind==="shareValue"&&r.push({severity:"error",path:mn,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${ie.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${ie.id}': shareValue is not supported inside repeated row effects.`}})})}}),P.subsections?.forEach((q,C)=>Q(q,`${_}.subsections[${C}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((P,_)=>Q(P,`sections[${_}]`));let oe=ML(t.effects);return oe.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${oe.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${oe.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...u5(e)),r}s(m0,"validateForm");function u5(e){let n={...e,effects:e.effects.map(h0),sections:e.sections.map(g0),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return Zf(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:sw(t)}))}s(u5,"missingTranslationIssues");function h0(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(h0,"withoutSubjectFlag");function g0(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(h0)})),subsections:e.subsections?.map(g0)}}s(g0,"withoutRowSubjectFlags");function d0(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(d0,"reviewRequiredShapeIssues");function c0(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(c0,"exportGateIssues");function ha(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${u0(r,"de")} '${n}'`,en:`Duplicate ${u0(r,"en")}: '${n}'`}}):e.add(n)}s(ha,"reportIfDup");function u0(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(u0,"labelForCode");function $v(e,n,t,r,i,o){e.visibleIf&&(vr(e.visibleIf,`${n}.visibleIf`,t,r,o),ga(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(vr(e.requiredIf,`${n}.requiredIf`,t,r,o),ga(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(vr(e.disabledIf,`${n}.disabledIf`,t,r,o),ga(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&vr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s($v,"checkFieldAsts");function Rv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Rv,"gatingMeta");function ga(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(f0(o.left,o.right,o.op,n,t,r),f0(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(ga,"checkGatingExpr");function f0(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(f0,"inspectEqualityOperand");function vr(e,n,t,r,i){i.push(...a0(e,t.declaredContext,n)),i.push(...i0(e,t.stageKeys,n));for(let o of bn(e))t.known.has(o)||Ev(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(vr,"checkAst");function p0(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 ${br.firstName} / ${br.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${br.firstName} / ${br.lastName}. Remove nameFrom.`}});let o=WL(e.id,n);HL(o)||i.push({severity:"error",path:t,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${br.firstName} oder ${br.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${br.firstName} or ${br.lastName} \u2014 the person would get no name.`}});for(let a of YL(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(p0,"personNameIssues");function f5(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(f5,"consentConfigIssues");var p5="blocked";function y0(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=yn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(m5(i))return r.id===p5?null:r.id}return null}s(y0,"resolveActiveOutcome");function m5(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(m5,"truthy");function w0(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(w0,"isScalar");function h5(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(w0(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))w0(a)&&(n[`${r}.${o}`]=a)}g5(e,n,t)}s(h5,"mergeRecord");function g5(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);zi(a).test(i)&&r.add(a)}for(let i of r){let o=xv(e,i),a=0;for(let l=0;l<o;l++)KL(e,i,l)&&a++;n[`${i}.count`]=a}}s(g5,"mergeRepeatedCounts");function k0(e,n,t){let r={...t};return h5(e,r,n),r}s(k0,"flattenValues");function Iv(e,n,t){return{code:e,fieldKey:n,text:t}}s(Iv,"submitIssue");function b0(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(b0,"truthyEval");function v0(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(v0,"isEmptyValue");function y5(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=b0(yn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(y5,"fieldIsLiveRequired");function w5(e,n,t){return x0(e,n,t).evalCtx}s(w5,"buildSubmitEvalContext");function x0(e,n,t){let r=k5(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=S0(e,l,t),c=new Set,u=new Set;E0(e,d,y=>c.add(y.key),y=>u.add(y.key));let f=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(f.size===o.size&&[...f].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 m=[...f].sort().join("\0");if(a.has(m)){let y=i.filter(k=>f.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(m),o=f}}s(x0,"splitWithContext");function k5(e){let n=new Map,t=[];for(let r of Am(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:zi(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(k5,"fieldOwnership");function S0(e,n,t){let r=[];for(let o of Am(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=k0(n,r,t);for(let o of Am(e.sections))for(let a of o.computed??[])try{i[a.key]=yn(a.expression,{values:i})}catch{}return i}s(S0,"rawEvalContext");function A0(e,n,t){let{values:r,defaulted:i}=b5(e,n,t),o=x0(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(A0,"splitDraftValues");function b5(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of Am(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??=S0(e,n,t);let c;try{c=yn(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(b5,"applyFieldDefaults");function Am(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(Am,"walkSectionsDeep");function v5(e,n,t,r=!1){if(v0(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(v5,"fieldFormatIssue");function x5(e,n){return v0(n)||e.type==="consent"&&n!==!0}s(x5,"isUnanswered");function Sm(e,n){if(!e)return!0;try{return b0(yn(e,{values:n}))}catch{return!1}}s(Sm,"isVisibleUnder");function E0(e,n,t,r){let i=s(o=>{if(Sm(o.visibleIf,n)){for(let a of o.fields)Sm(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(Sm(a.visibleIf,n))for(let l of a.fields)Sm(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(E0,"forEachVisibleField");function T0(e,n,t,r={}){let i=w5(e,n,t),o=[],a=y0(e,i);a===null&&r.requireOutcome!==!1&&o.push(Iv("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 E0(e,i,d=>{let c=n[d.key];if(x5(d,c)){!l.has(d.type)&&y5(d,i,a)&&o.push(Iv("required",d.key,ol([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=v5(d,c,r.registry,r.testMode===!0);u!==null&&o.push(Iv("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(T0,"checkSubmittable");function $0(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=Js(e),r=[];for(let i of n){let o=i.prefill??{};if(!n0(e,i.env))continue;let a=r0(e,i.env),{visible:l}=A0(t,o,a),d=T0(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:ol([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s($0,"validateScenarios");function Em(e){return e.filter(n=>(n.severity??"error")==="error")}s(Em,"blockingIssues");function Tm(e,n={}){return[...m0(e,n),...$0(e)]}s(Tm,"runFormValidators");function $m(e){return Em(e)}s($m,"blockingFormErrors");function R0(e,n,t){return h_(e,n,t)}s(R0,"runWorkflowValidators");function I0(e){return Em(e)}s(I0,"blockingWorkflowErrors");var S5=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],O0={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"]},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"]}},pt={id:w.string(),label:sa,artifacts:w.optional(w.any()),assign:w.optional(w.any()),inputs:w.optional(w.any()),library:w.optional(w.any()),next:w.optional(w.any()),notifications:w.optional(w.any()),optionalActions:w.optional(w.any()),outcomes:w.optional(w.any()),outputLabels:w.optional(w.any()),sublabel:w.optional(w.any()),tasks:w.optional(w.any())},A5=w.object({...pt,type:w.literal("join")}),E5=w.object({...pt,type:w.literal("end")}),T5=w.object({...pt,type:w.literal("eventTrigger")}),$5=w.object({...pt,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),R5=w.object({...pt,type:w.literal("roleAssign")}),I5=w.object({...pt,type:w.literal("setFlag")}),O5=w.object({...pt,type:w.literal("if"),condition:w.optional(w.any())}),P5=w.object({...pt,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),_5=w.object({...pt,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),N5=w.object({...pt,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),C5=w.object({...pt,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),form:w.optional(w.any())}),D5=w.object({...pt,type:w.literal("waitlist")}),F5=w.object({...pt,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),L5=w.object({...pt,type:w.literal("collectPayment")}),M5=w.object({...pt,type:w.literal("governedDocument"),approval:w.optional(w.any()),confirmBeforeIssue:w.optional(w.any()),confirmContractTerms:w.optional(w.any()),contractTermsQuestionText:w.optional(w.any()),form:w.optional(w.any()),generatorStamp:w.optional(w.any()),production:w.optional(w.any()),reads:w.optional(w.any()),responseLabels:w.optional(w.any()),responseStrategy:w.optional(w.any()),templateStamp:w.optional(w.any()),titles:w.optional(w.any())}),aCe=w.union(A5,E5,T5,$5,R5,I5,O5,P5,_5,N5,C5,D5,F5,L5,M5);function P0(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 O0)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=O0[a],d=new Set(["id","type","label",...S5,...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(P0,"workflowNodeEnvelopeIssues");function _0(e,n){return e.enumOptionLabels?.[n]??{de:n,en:n}}s(_0,"inlineEnumOptionLabel");var C0={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function D0(e){return C0[e]!==void 0}s(D0,"isExportableFieldType");function q5(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(q5,"leafForComputed");function N0(e){let n=C0[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:_0(e,t)}))}:{}}}s(N0,"leafFor");function Ov(e){let n=[],t=s(r=>{for(let i of r.fields)i.export===!0&&n.push(N0(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&n.push(N0(o));for(let i of r.computed??[])i.export===!0&&n.push(q5(i));for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(Ov,"exportedFormLeaves");var F0=s(e=>e,"asEffectId"),Wi=s(e=>e,"asOutcomeId"),ya=s(e=>e,"asSectionId"),ot=s(e=>e,"asFieldKey");var xr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Pd=["person","organization","relationship","fieldMap"],Yi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],wa=["fresh","keyed","manual"];function Vo(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 un(e,n,t,r)}s(Vo,"optionalLocalizedText");function Jn(e,n){if(!(e===void 0||e===""))try{Un(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(Jn,"assertExpression");function _d(e){return Object.keys(e.smartforms??{})}s(_d,"carriedFormSlugs");function Pv(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(Pv,"boundFormSlugs");function Rm(e,n){let t=_d(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(Rm,"resolveFormSlug");function Im(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(Im,"getForm");function jt(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(jt,"walkSections");function rr(e,n){return jt(e).find(t=>t.id===n)}s(rr,"findSection");function Go(e,n){for(let t of jt(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(Go,"findField");function zo(e){let n=new Set;for(let t of jt(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(zo,"allFieldKeys");function K5(e){let n=un(e.label,e.labelEn,"offer form add"),t={id:ya("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Wi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(K5,"buildSkeletonSmartForm");function Om(e,n){let{key:t,label:r}=n;if(_d(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=K5({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(Om,"addForm");function L0(e,n){if(!_d(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(Pv(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(L0,"removeForm");function M0(e,n){let t=Im(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");wn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(M0,"setForm");function q0(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(q0,"nodesOf");function K0(e,n,t){let r=q0(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(K0,"nodeOf");function j0(e){return e.flatMap(n=>{if(n.type!=="form"||vt(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s(j0,"creatingFormNodes");function B0(e){return $m(Tm(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(B0,"formErrors");function Pm(e){let n="offer workflow restamp-exports",t=q0(e,n),r=[];for(let{node:i,slug:o}of j0(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=B0(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
10816
+ `)}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}},Sb=class extends D{static{s(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=T.Usage({category:"Notifications",description:"Reword one or more blocks of a letter for this school (merge \u2014 untouched blocks stay as they are).",details:"A block whose text EQUALS the platform default is dropped rather than stored: what is kept is the deviation, never a copy, so a later improvement to an untouched block still reaches this school. An unknown block or an undeclared {{placeholder}} is refused by the backend with every finding named \u2014 nothing is written.",examples:[["One paragraph",'$0 --tenant test notifications letters set applicant.welcome --locale de --slot intro="Sch\xF6n, dass Sie da sind."'],["The English letter",'$0 --tenant test notifications letters set applicant.welcome --locale en --slot intro="Lovely to have you."'],["From a file","$0 --tenant test notifications letters set applicant.tasksOpen --locale de --slot-file intro=./intro.txt"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"<blockKey>=<text> (repeatable)"});slotFile=p.Array("--slot-file",{description:"<blockKey>=<path> \u2014 read the text from a local file (repeatable)"});async execute(){let n=d6(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:$b(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}},Ab=class extends D{static{s(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=T.Usage({category:"Notifications",description:"Drop this school's deviations \u2014 named blocks, or the whole letter with --all.",details:"--all is required to drop a whole letter: dropping everything must be typed, never be what happens when a --slot is forgotten.",examples:[["One block back to the platform text","$0 --tenant test notifications letters reset applicant.welcome --locale de --slot intro"],["The whole letter","$0 --tenant test notifications letters reset applicant.welcome --locale en --all"]]});templateId=p.String({required:!0});locale=p.String("--locale",{description:`Letter language (${ze.join("|")}) \u2014 required; each language is worded on its own`});slot=p.Array("--slot",{description:"Block key to reset (repeatable)"});all=p.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:$b(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}},bd=s((e,n)=>e==null?n:e.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function jp(e,n,t){return["de","en"].map(r=>({field:`${e} (${r})`,school:n===null?"\u2014 (platform)":n[r]===""?"\u2014 (untranslated)":bd(n[r],""),...t===null?{}:{platform:bd(t[r],"")}}))}s(jp,"chromeTextRows");var Eb=class extends D{static{s(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=T.Usage({category:"Notifications",description:"The school's letter frame (greeting and sign-off per language, sender name) and the platform wording each falls back to."});async execute(){let n=await this.caller(),t=await n.query(x.notifications.getTenantChrome,{tenantSlug:this.requireTenant(n)});return this.print(t,r=>[...jp("greeting",r.greeting,r.defaults.greeting),...jp("closing",r.closing,r.defaults.closing),{field:"senderName",school:bd(r.senderName,"\u2014 (platform)"),platform:bd(r.defaults.senderName,"")}],["field","school","platform"]),0}},Tb=class extends D{static{s(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=T.Usage({category:"Notifications",description:"Set the school's letter frame. Greeting and sign-off are set in BOTH languages at once; both EMPTY clears that field back to the platform wording.",examples:[["Own sign-off",'$0 --tenant test notifications chrome set --closing-de="Herzliche Gr\xFC\xDFe, Ihr Grundschul-Team" --closing-en="Warm regards, your primary school team"'],["Back to the platform sign-off",'$0 --tenant test notifications chrome set --closing-de="" --closing-en=""']]});greetingDe=p.String("--greeting-de",{description:"Opening line, German"});greetingEn=p.String("--greeting-en",{description:"Opening line, English"});closingDe=p.String("--closing-de",{description:"Sign-off, German"});closingEn=p.String("--closing-en",{description:"Sign-off, English"});senderName=p.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=>[...jp("greeting",l.greeting,null),...jp("closing",l.closing,null),{field:"senderName",school:bd(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},bD=[gb,yb,wb,kb,bb,vb,xb,Sb,Ab,Eb,Tb];var u6="-stufe-",f6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Rb(e){return`${e}${u6}`}s(Rb,"stageKeyPrefix");function Ib(e,n){return`${Rb(e)}${n}`}s(Ib,"stageStorageKey");function xD(e,n){let t=Rb(e);return n.startsWith(t)&&n.length>t.length}s(xD,"isUnderProgram");function jr(e,n){let t=Rb(e);return xD(e,n)||le("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(jr,"bareStageKey");function Bp(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Rn(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"||!f6.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(Bp,"stageSpecIssues");function vD(e){return{de:e.de.trim(),en:e.en.trim()}}s(vD,"trimmedText");function p6(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(p6,"describeNameChange");function Up(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:vD(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:vD(a)},u=Ib(e,c.key);i.add(u);let f=d+1,m=r.get(u);if(m===void 0){o.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:f});return}let y={};hs(m.name,c.name)||(y.name=[m.name,c.name]);let k=m.gradeLevel??null,g=c.gradeLevel??null;k!==g&&(y.gradeLevel=[k,g]),m.sequence!==f&&(y.sequence=[m.sequence,f]),(Object.keys(y).length>0||m.archived)&&o.push({op:"update",key:c.key,stageId:m.stageId,name:c.name,changes:y,unarchive:m.archived})});for(let a of[...n].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||o.push({op:"archive",key:xD(e,a.key)?jr(e,a.key):a.key,stageId:a.stageId,name:a.name});return o}s(Up,"planStageReconcile");function Vp(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(p6(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(Vp,"describeStageStep");var m6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ci(e,n){return`${e}-${n}`}s(ci,"runStorageKey");function SD(e,n){typeof n!="string"&&le("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)&&le("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(SD,"bareRunKey");function Gp(e){let n=[],t=new Map;return e.forEach((r,i)=>{let o=Rn(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"||!m6.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(Gp,"runSpecIssues");var h6={capacity:null,isOpen:!1},g6={capacity:null,isOpen:!0};function y6(e){return e===null||e==="unlimited"||typeof e=="number"&&Number.isInteger(e)&&e>=0}s(y6,"isCapacity");function zp(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)||!y6(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(zp,"capacitySpecIssues");function ED(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(jr(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(f=>f.key===ci(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[f,m]of Object.entries(c.capacities)){let y=i.get(f);if(y===void 0&&!o.has(f))throw new Error(`offer[admission]: capacities of run "${c.key}" name stage "${f}", which the program does not have (have: ${[...i.keys()].join(", ")||"none"})`);let k={capacity:m.capacity,isOpen:m.isOpen},g=u!==void 0&&y!==void 0?l.get(`${u.runId}|${y}`):void 0,b=g!==void 0?{capacity:g.capacity,isOpen:g.isOpen}:u===void 0?h6:g6;b.capacity===k.capacity&&b.isOpen===k.isOpen||d.push({run:c.key,stageKey:f,from:b,to:k})}}return d}s(ED,"planRunCapacities");function AD(e){return`${e.capacity===null?"unconfigured":String(e.capacity)}/${e.isOpen?"open":"closed"}`}s(AD,"describeCell");function Wp(e){return`~cap ${e.run}\xD7${e.stageKey} ${AD(e.from)} \u2192 ${AD(e.to)}`}s(Wp,"describeCapacityStep");function TD(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(TD,"assertBackendHasStageKeys");async function Ob(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}));TD(i);let a=Up(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 f=c.get(u.stageId);if(f===void 0)throw new Error(`offer[admission]: no occupancy returned for stage ${u.stageId}`);return{...u,occupancy:{activeApplications:f.activeApplications,openLeads:f.openLeads}}})}s(Ob,"planStages");async function Yp(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});TD(o);let a=new Set(o.programKey===null?[]:o.stages.map(c=>jr(o.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=o.programKey;return ED(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===ci(d,c)))})}s(Yp,"planCapacities");async function w6(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===ci(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(w6,"assertNoArchivedRunKey");var Pb={name:"admission",async scaffold(e,n,t,r){let i=t.tenant,o=t.program?.stages,a=[...Bp(o??[]),...Gp(t.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(g=>g.message.de).join("; ")}`);let l=zp(t.program?.runs??[],o?.map(g=>g.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await w6(e,i,n,t);let d=await Yp(e,i,n,t),c=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),u=k6(t);if(!u)throw new Error("offer[admission]: no unit to link \u2014 set links.unitKey or program.unitKey in bundle.yaml");let f=c.units.find(g=>g.key===u);if(!f)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(g=>g.key===null?[]:[g.key]).join(", ")||"(none)"}`);let m=[];if(r.dryRun||(await e.mutation(x.programAdmin.ensurePedagogyUnit,{client:i,unitId:f.unitId}),await e.mutation(x.programAdmin.createProgramForAngebot,{client:i,offerKey:n,unitId:f.unitId,...t.program?.key!==void 0?{programKey:t.program.key}:{}})),m.push(`unit=${u}`),o!==void 0)if(r.dryRun){let g=await Ob(e,i,n,o);m.push(...g.map(Vp))}else{let g=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}:{}}))});m.push(...g.steps,...g.warnings.map(b=>`warning ${b}`))}let y=r.dryRun?c:await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n});for(let g of t.program?.runs??[]){let b=y.programKey===null?void 0:y.runs.find(A=>A.key===ci(y.programKey,g.key));if(b!==void 0){hs(b.name,g.name)||(r.dryRun||await e.mutation(x.programAdmin.updateProgramRun,{client:i,offerKey:n,runId:b.runId,name:g.name}),m.push(`~run ${g.key} ("${_e(b.name)}" \u2192 "${_e(g.name)}")`));continue}r.dryRun||await e.mutation(x.programAdmin.addProgramRun,{client:i,offerKey:n,key:g.key,name:g.name,isOpen:g.capacities!==void 0?!1:g.isOpen??!0,...g.startDate?{startDate:g.startDate}:{},...g.endDate?{endDate:g.endDate}:{}}),m.push(`+run ${g.key} (${_e(g.name)})`)}let k=r.dryRun?d:await Yp(e,i,n,t);if(!r.dryRun&&k.length>0){let g=await e.query(x.programAdmin.getAngebotConfig,{client:i,offerKey:n}),b=g.programKey;if(b===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let A of k){let $=g.runs.find(E=>E.key===ci(b,A.run))?.runId,O=g.stages.find(E=>jr(b,E.key)===A.stageKey)?.stageId;if($===void 0||O===void 0)throw new Error(`offer[admission]: cell ${A.run}\xD7${A.stageKey} vanished between plan and write`);await e.mutation(x.programAdmin.setRunStageCapacity,{client:i,offerKey:n,runId:$,stageId:O,capacity:A.to.capacity,isOpen:A.to.isOpen})}}return m.push(...k.map(Wp)),m.join(", ")}};function k6(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(k6,"bundleUnitKey");var $D={role:"control",effect:"pure",cardinality:"N-to-1"};var Hp=["add","remove","replace"];function RD(e,n){let t=e.inputs?.[n];if(!(!t||t.kind!=="literal"))return t.value!=null?String(t.value):void 0}s(RD,"roleAssignLiteral");var ID={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=RD(e,"roleKey")?.trim()??"",o=RD(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"}),Hp.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 ${Hp.join(" | ")}.`,en:`[roleAssign/unknownMode] roleAssign node "${e.id}" declares mode "${o}" \u2014 allowed are ${Hp.join(" | ")}.`},severity:"error"}),r},"validate")};var b6=["event","effect","outcomes"],_b=s((e,n,t)=>({layer:"GRAPH",kind:"nodeRule",path:e,reason:{de:n,en:t},severity:"error"}),"issue"),OD={outcomes:[{id:hr,label:{de:"Gestartet",en:"Started"}}],validate:s((e,n)=>{let t=[],r=e;for(let i of b6)i in r&&t.push(_b(`nodes.${e.id}.${i}`,`[graph/retiredField] Start-Knoten "${e.id}": \`${i}\` gibt es nicht mehr \u2014 der Knotentyp deklariert seinen einen Ausgang \u201E${hr}" selbst.`,`[graph/retiredField] Start node "${e.id}": \`${i}\` no longer exists \u2014 the node type declares its one outcome "${hr}" itself.`));return _t(n.nodes).some(i=>i.target===e.id)&&t.push(_b(`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?.[hr]===void 0&&t.push(_b(`nodes.${e.id}.next.${hr}`,`[eventTrigger/unroutedStart] Start-Knoten "${e.id}" leitet \u201E${hr}" nirgendwohin.`,`[eventTrigger/unroutedStart] Start node "${e.id}" routes "${hr}" nowhere.`)),t},"validate")};var v6="submit",PD=[{id:v6,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function _D(e){return e==="draft"}s(_D,"isWritableSmartFormState");var Nb=["draft","committed"],FEe=Nb.filter(e=>_D(e));async function ND(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(ND,"getSmartFormInstance");var CD="form:fill",Cb="request:collectPayment";var x6={key:CD,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},DD={key:"bearbeitung",label:te("In Bearbeitung","In progress"),scope:"node"},FD={[kR]:{label:te("In Bearbeitung","In progress"),tone:"neutral",phase:DD,external:en(te("Entwurf","Draft"),"neutral",te("Bewerbung fortsetzen","Continue application"),te("Sie haben die Bewerbung bereits begonnen. Schlie\xDFen Sie sie ab, um sie einzureichen.","You have already started the application. Complete it to submit it."),te("Bewerbung fortsetzen","Continue application"),"continue-form")},[Hu]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:DD,external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung ist eingereicht","Your application has been submitted"),te("Ihre Bewerbung ist bei uns eingegangen. Wir melden uns mit den n\xE4chsten Schritten.","We have received your application. We will be in touch with the next steps."))}},LD={role:"user-action",effect:"side-effect",progressDefaults:FD,progressEvents:Dn(FD),actions:s(()=>PD,"actions"),workItemTemplates:s(()=>[x6],"workItemTemplates"),states:Nb,currentState:s(async(e,n)=>{let t=await ND(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=>vt(e)?[]:[{id:Ju,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 MD={role:"system-action",effect:"side-effect",inputs:s(()=>[{id:In.target,label:{de:"Formular",en:"Form"},type:"admission",required:!0,inspector:"binding-only"},{id:In.flagKey,label:{de:"Merkmal im Formular",en:"Flag in the form"},type:"formFlag",required:!0,inspector:"literal-only",optionSource:"targetFormFlags"},{id:In.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:jI(e),args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:s(e=>{let n=[];e.inputs?.[In.flagKey]?.kind==="literal"&&wf(e)===null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${In.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?.[In.value];return r?.kind==="literal"&&typeof r.value!="boolean"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${In.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 S6="true",A6="false",Db=[{id:S6,label:{de:"Ja",en:"Yes"}},{id:A6,label:{de:"Nein",en:"No"}}];var qD={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Db,validate:s((e,n,t)=>E6(e,n,t),"validate")};function E6(e,n,t){let r=s(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.condition`,reason:{de:`[if/condition] Knoten "${e.id}": ${d.de}`,en:`[if/condition] Node "${e.id}": ${d.en}`},severity:"error"}),"issue"),i=Db.filter(d=>e.next?.[d.id]===void 0).map(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.next.${d.id}`,reason:{de:`[if/unroutedOutcome] Knoten "${e.id}": Ausgang \u201E${d.label.de}\u201C (${d.id}) f\xFChrt nirgendwohin.`,en:`[if/unroutedOutcome] Node "${e.id}": Outcome "${d.label.en}" (${d.id}) leads nowhere.`},severity:"error"}));if(typeof e.condition!="string"||e.condition.trim()==="")return[...i,r({de:"Bedingung fehlt.",en:"The condition is missing."})];let o=CR(n),a=zf(e.condition,o).filter(d=>d.severity==="error").map(d=>r(d.message)),l=[...i,...a];if(a.length>0||t?.liveEnvKeys===void 0)return l;for(let d of Qy(e.condition,o)){let c=kP(d.path,t.liveEnvKeys);c===null&&F(`[if/condition] no live-key universe for '${d.path}' \u2014 extend liveKeyUniverse`),c.has(d.value)||l.push(r({de:`$env.${d.path} == '${d.value}' nennt keinen Schl\xFCssel dieses Mandanten.`,en:`$env.${d.path} == '${d.value}' names no key of this school.`}))}return l}s(E6,"ifNodeIssues");var vd="decision",T6=new Set(["decision","review"]),lTe=new Set([...T6,"governedDocument"]);var jD=[{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"}],KD={released:{label:te("Freigegeben","Released"),tone:"green",phase:{key:"freigabe",label:te("Freigabe","Release"),scope:"node"},external:en(te("Freigegeben","Released"),"green",te("Ihre Bewerbung wurde freigegeben","Your application has been released"),te("Wir haben Ihre Bewerbung freigegeben und melden uns mit den n\xE4chsten Schritten.","We have released your application and will be in touch with the next steps."))}},Do={role:"user-action",effect:"side-effect",outcomes:jD,progressDefaults:KD,progressEvents:Dn(KD),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,...Ri(n.semantic)?{semantic:n.semantic}:{}})),...ZP(e)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:s(e=>[{key:vd,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===vd&&Array.isArray(e.reads)?e.reads.map(t=>({kind:"field",address:t})):[],"taskDocuments"),validate:Fb};function Fb(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(f=>typeof f=="string"&&f.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 ${bt.join(", ")}.`,en:`[decision/outcomeSemanticMissing] Outcome "${l.id}" of "${e.id}" does not say what it means \u2014 one of ${bt.join(", ")}.`},severity:"error"}):Ri(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: ${bt.join(", ")}.`,en:`[decision/outcomeSemanticUnknown] Outcome "${l.id}" of "${e.id}" has the meaning "${String(u)}" \u2014 allowed: ${bt.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(Fb,"validateDecisionNode");var Lb=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],BD=[{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 er="processFooter";var Mb="promoted";var UD="promote",VD="Nachr\xFCcken";var qb={key:"warteliste",label:te("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},GD={waitlisted:{label:te("Warteliste","Waitlisted"),tone:"amber",phase:qb,external:en(te("Warteliste","Waiting list"),"amber",te("Sie stehen auf der Warteliste","You are on the waiting list"),te("Ihre Bewerbung wurde auf die Warteliste gesetzt. Wir informieren Sie, sobald ein Platz frei wird.","Your application has been placed on the waiting list. We will let you know as soon as a place becomes available."))},promoted:{label:te("Nachger\xFCckt","Promoted"),tone:"green",phase:qb,external:en(te("Nachger\xFCckt","Moved up"),"green",te("Sie sind nachger\xFCckt","You have moved up"),te("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:te("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:qb,external:en(te("Warteliste geschlossen","Waiting list closed"),"red",te("Die Warteliste wurde geschlossen","The waiting list has been closed"),te("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))}},zD={outcomes:Lb,inputs:s(()=>[{id:"waitlistOrder",label:{de:"Reihenfolge der Warteliste",en:"Waiting list order"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Yt.map(e=>({value:e,label:VR[e]}))}],"inputs"),validate:s((e,n)=>{let t=Yg(e);if(t===null)return[];let r=n.nodes.filter(o=>o.type==="waitlist"&&o.id!==e.id),i=n.nodes.indexOf(e);for(let o of r){if(n.nodes.indexOf(o)>i)continue;let a=Yg(o);if(a!==null&&a.waitlistOrder!==t.waitlistOrder)return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs`,reason:{de:`[waitlist/policyConflict] Wartelisten "${o.id}" und "${e.id}" nennen verschiedene Reihenfolgen \u2014 eine Kohorte hat EINE Warteliste.`,en:`[waitlist/policyConflict] Waiting lists "${o.id}" and "${e.id}" state different orders \u2014 a cohort has ONE waiting list.`},severity:"error"}]}return[]},"validate"),pausesApplicationTasks:!0,progressDefaults:GD,progressEvents:Dn(GD),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:Lb).some(t=>t.id===Mb)?[{id:UD,kind:"advance",outcome:Mb,semantic:"other",label:{de:VD,en:"Promote from waitlist"},surface:er,superUserOnly:!0}]:[],"actions")};var Kb="complete",xd="acceptedIncomplete",Jp="rejected",$6="absage",WD="closeWithoutDocuments",YD="rejectAtCompleteness",HD="Ohne Nachreichung abschlie\xDFen",JD="Ablehnen",QD="awaitingDocuments",jb="documentsComplete",Bb="closedWithoutDocuments",Ub="rejected",Vb="withdrawn",ZD="requested",OTe={[Kb]:{event:jb,status:"complete",endsRole:!0},[xd]:{event:Bb,status:"acceptedIncomplete",endsRole:!1},[Jp]:{event:Ub,status:"rejected",endsRole:!0},[$6]:{event:Vb,status:"withdrawn",endsRole:!0}};var Sd=s(()=>yl[0],"beneficiary"),Gb=366;function R6(e){let n=e.reads,t=wl(e).flatMap(({address:r})=>dn(r)&&!yl.includes(r.path)?[r]:[]);return[...Array.isArray(n)?n.filter(dn):[],...t]}s(R6,"printedFields");function I6(e,n){let t=se(n);return e.nodes.filter(r=>r.type==="governedDocument"&&R6(r).some(i=>se(i)===t))}s(I6,"documentsPrinting");function O6(e,n){if(!dn(n)||n.path!==Sd())return!1;let t=e.nodes.find(r=>r.id===n.owner);return t!==void 0&&t.type==="form"&&!vt(t)}s(O6,"isCreatedFormBeneficiary");function Fn(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Fn,"issue");function P6(e,n,t){let r=new Map(e.nodes.map(l=>[l.id,l])),i=n.next??{},o=new Set,a=[Kb,xd].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)&&wr(d.form)&&d.form.owner===t)){if(d.type==="end"){if(xl(d)==="approved")return!0;continue}for(let c of Object.values(d.next??{}))a.push(c.to)}}return!1}s(P6,"reachesApprovedEndUnreviewed");var zb={key:"unterlagen",label:te("Unterlagen nachreichen","Outstanding documents"),scope:"node"},XD={[QD]:{label:te("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:zb,external:en(te("Unterlagen fehlen","Documents missing"),"amber",te("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),te("Uns fehlen noch einige Angaben oder Unterlagen. Sie finden die Liste und die Frist in Ihren Aufgaben.","Some details or documents are still missing. You will find the list and the deadline in your tasks."))},[jb]:{label:te("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:zb,external:en(te("Unterlagen vollst\xE4ndig","Documents complete"),"green",te("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),te("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},[Bb]:{label:te("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:zb,external:en(te("Abgeschlossen","Closed"),"neutral",te("Die Nachreichung ist abgeschlossen","The document request is closed"),te("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},[Ub]:{label:te("Abgelehnt","Rejected"),tone:"red",phase:SO,external:en(te("Abgelehnt","Rejected"),"red",te("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),te("Wir bedauern, Ihnen mitteilen zu m\xFCssen, dass wir Ihre Bewerbung nicht ber\xFCcksichtigen konnten.","We regret to inform you that we were unable to accept your application."))},[Vb]:{label:te("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:_f,external:en(te("Zur\xFCckgezogen","Withdrawn"),"red",te("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),te("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))}},eF={outcomes:BD,progressDefaults:XD,progressEvents:Dn(XD),notificationEvents:s(()=>[{id:ZD,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(xd)&&t.push({id:WD,kind:"advance",outcome:xd,semantic:"other",label:{de:HD,en:"Close without documents"},surface:er,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(Jp)&&t.push({id:YD,kind:"advance",outcome:Jp,semantic:"rejected",label:{de:JD,en:"Reject application"},surface:er,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(A=>Ue(n,A,"de"),"shown"),l=s(A=>Ue(n,A,"en"),"shownEn"),d=e.requires;if(!Array.isArray(d)||d.length===0)r.push(Fn(e,"requires",{de:`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/missingRequires] ${o} names no fields \u2014 \`requires\` must contain at least one field of a form ($node.<form>.admission.<field>).`}));else{let A=new Set;for(let $ of d){if(!we($))continue;let O=se($);if(A.has(O)){r.push(Fn(e,"requires",{de:`[completenessCheck/duplicateField] Feld ${a($)} steht doppelt in \`requires\`.`,en:`[completenessCheck/duplicateField] Field ${l($)} appears twice in \`requires\`.`}));continue}if(A.add(O),!dn($)){r.push(Fn(e,"requires",{de:`[completenessCheck/unknownField] ${a($)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`,en:`[completenessCheck/unknownField] ${l($)} is not a field of a form \u2014 \`requires\` names fields ($node.<form>.admission.<field>).`}));continue}let E=ii(t,$);if(E==null)continue;let I=Ds("requires",Cs(E));I==="computed"||I==="repeated"?r.push(Fn(e,"requires",{de:`[completenessCheck/fieldNotRequestable] Feld ${a($)} ist ${E.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`,en:`[completenessCheck/fieldNotRequestable] Field ${l($)} is ${E.kind==="computed"?"computed":"a field of a repeated group"} \u2014 the family cannot submit it later.`})):I==="untranslated"&&r.push(Fn(e,"requires",{de:`[completenessCheck/fieldNameUntranslated] Feld ${a($)} (\u201E${Di(E,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`,en:`[completenessCheck/fieldNameUntranslated] Field ${l($)} ("${Di(E,"de")}") has no English name (field or person/section) \u2014 the letter "Documents requested" names it in the family's language.`}))}}let c=e.deadline,u=typeof c=="object"&&c!==null?c:{},f="inDays"in u,m="until"in u;if(f===m)r.push(Fn(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(f){let A=u.inDays;(typeof A!="number"||!Number.isInteger(A)||A<0||A>Gb)&&r.push(Fn(e,"deadline.inDays",{de:`[completenessCheck/deadlineDays] Frist "${String(A)}" ist keine ganze Zahl von 0 bis ${Gb} Tagen.`,en:`[completenessCheck/deadlineDays] Deadline "${String(A)}" is not a whole number from 0 to ${Gb} days.`}))}else typeof u.until!="string"||Ly(u.until)===null?r.push(Fn(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<jO(Date.now())&&r.push({...Fn(e,"deadline.until",{de:`[completenessCheck/deadlinePassed] Frist "${u.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`,en:`[completenessCheck/deadlinePassed] Deadline "${u.until}" is in the past \u2014 every request would get the day of entry as its deadline. Update the date?`}),severity:"warning"});if(Array.isArray(d)){let A=new Map(d.filter(dn).map($=>[se($),$]));for(let $ of A.values())for(let O of I6(n,$))r.push(Fn(e,"requires",{de:`[completenessCheck/requiresConsumedUpstream] Feld ${a($)} flie\xDFt in das Dokument \u201E${O.label?.de??O.id}" (${O.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($)} flows into the document "${O.label?.en||O.id}" (${O.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 A=d.filter(dn).filter(E=>{let I=ii(t,E);return I!=null&&Jf(I)}),O=[...new Set(A.map(E=>E.owner))].filter(E=>P6(n,e,E));if(O.length>0){let E=A.filter(I=>O.includes(I.owner));r.push({...Fn(e,"next",{de:`[review/unreviewedAfterSupply] ${E.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] ${E.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,g=e.inputs?.person,b=g?.kind==="binding"?g.address:null;k!==void 0&&(typeof k!="string"||k.trim()===""?r.push(Fn(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(Fn(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(Fn(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(Fn(e,"inputs.person",{de:`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(k)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${it}.${Sd()}).`,en:`[completenessCheck/guestRoleNeedsPerson] ${o} assigns the role "${String(k)}", but the input "person" is not bound (e.g. to $node.<form>.${it}.${Sd()}).`}))),we(b)&&!O6(n,b)&&r.push(Fn(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>.${it}.${Sd()}).`,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>.${it}.${Sd()}).`})),b!==null&&k===void 0&&r.push(Fn(e,"inputs.person",{de:'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.',en:'[completenessCheck/personWithoutRole] The input "person" is bound, but no role is assigned \u2014 the binding has no effect.'}));for(let A of["complete","rejected"])e.next?.[A]===void 0&&r.push(Fn(e,`next.${A}`,{de:`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${e.id}" leitet den Ausgang "${A}" nirgendwohin.`,en:`[completenessCheck/unroutedOutcome] Completeness check "${e.id}" routes the outcome "${A}" nowhere.`}));return r},"validate")};var _6=[{id:zR,label:{de:"Gepr\xFCft",en:"Reviewed"},semantic:"other"}],Qp=s(e=>e,"asDecision"),nF={[WR]:{label:te("Eingereicht","Submitted"),tone:"blue",phase:{key:"pruefung",label:te("In Pr\xFCfung","In review"),scope:"node"},external:en(te("Eingereicht","Submitted"),"blue",te("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),te("Ihre Bewerbung ist bei uns eingegangen. Wir pr\xFCfen jetzt Ihre Unterlagen und melden uns, falls etwas fehlt.","We have received your application. We are now reviewing your documents and will get in touch if anything is missing."))}},tF={role:"user-action",effect:"side-effect",outcomes:_6,progressDefaults:nF,progressEvents:Dn(nF),notificationEvents:s(e=>Do.notificationEvents(Qp(e)),"notificationEvents"),inputs:s(()=>[{id:Qt,label:{de:"Wenn nichts zu pr\xFCfen ist",en:"When nothing is owed"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:Eo.map(e=>({value:e,label:S_[e]}))}],"inputs"),actions:s(e=>[...Do.actions(Qp(e)).map(n=>n.kind==="advance"&&(e.outcomes??[]).length===1?{...n,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:n),{id:Qg,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:Do.optionalActionKinds,workItemTemplates:s(e=>Do.workItemTemplates(Qp(e)).map(n=>n.key===vd?{...n,title:e.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...n.unlocks,Qg]}:n),"workItemTemplates"),taskDocuments:s(()=>[],"taskDocuments"),validate:s((e,n,t)=>{let r=Fb(Qp(e),n,t);for(let c of e.outcomes??[]){let u=c.semantic;typeof u!="string"||!cf.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?.[Qt],a=A_(e);o!==void 0&&a===null&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.inputs.${Qt}`,reason:{de:`[review/unknownMode] Pr\xFCf-Knoten ${i.de}: \u201EWenn nichts zu pr\xFCfen ist\u201C muss ${Eo.join(" oder ")} als fester Wert sein.`,en:`[review/unknownMode] Review node ${i.en}: "When nothing is owed" must be the literal ${Eo.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)&&wr(d)){let c=t?.readinessFormFieldsByFormNode?.get(d.owner);c!==void 0&&![...c.values()].some(Jf)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.form`,reason:l?{de:`[review/nothingDeclared] Pr\xFCf-Knoten ${i.de} pr\xFCft ${se(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 ${se(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 ${se(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 ${se(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 rF=["awaitingAnswer","answered"];async function iF(e,n){return(await Il(e,{applicationId:n.applicationId,nodeId:n.nodeId})).filter(r=>r.templateKey===n.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}s(iF,"externalRequestState");var aF=[{id:Ps,label:{de:"Bezahlt",en:"Paid"}}],m$e=new Set(aF.map(e=>e.id));var N6=Ps,oF=[{id:N6,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],C6={id:Ey,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:er,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"}}},D6={id:Ey,kind:"advance",outcome:Ps,semantic:"other",label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:er,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 Wb(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(Wb,"literalOf");function ua(e){let n=Wb(e,Ht);return xf(n)?n:null}s(ua,"settlementOrNull");function F6(e){let n=Wb(e,Ni);return typeof n=="string"&&n.length>0?n:null}s(F6,"articleKeyOrNull");function L6(e){let n=Wb(e,Jt);return typeof n=="string"&&n.length>0&&n===n.trim()?n:null}s(L6,"payeeKeyOrNull");var M6={id:Ni,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},q6={id:Ht,label:{de:"Abrechnung",en:"Settlement"},type:"enum",required:!0,inspector:"literal-only",optionSource:"declared",enumOptions:[{value:"separate",label:{de:"Separat (Schule)",en:"Separately (school)"}},{value:"online",label:{de:"Online (Stripe)",en:"Online (Stripe)"}}]},K6={id:Ci,label:{de:"Hinweis f\xFCr die Familie",en:"Note for the family"},type:"localizedText",required:!1,inspector:"literal-only"},j6={id:Jt,label:{de:"Zahlungsempf\xE4nger (Tr\xE4ger)",en:"Payee (legal entity)"},type:"legalEntity",required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function B6(e){return[M6,q6,...ua(e)==="online"?[j6]:[],K6]}s(B6,"collectPaymentInputs");var U6=["amount","currency","settlement"];function V6(e,n){if(ua(e)!=="online")return[];let t=L6(e);if(t===null)return[];let r=`nodes.${e.id}.inputs.${Jt}`,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] Abrechnung \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 \u201Eseparat" w\xE4hlen.`,en:`[collectPayment/onlineWithoutStripe] Settlement "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 "separate".`})]:[]}s(V6,"payeeIssues");var sF={awaitingPayment:{label:te("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:te("Zahlung","Payment"),scope:"node"},external:en(te("Zahlung offen","Payment due"),"amber",te("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),te("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))}},lF={outputs:s(()=>[{name:PI,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:s(e=>B6(e),"inputs"),outcomes:aF,progressDefaults:sF,progressEvents:Dn(sF),notificationEvents:s(e=>ua(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=ua(e);return n==="online"?[...oF,D6]:n==="separate"?[C6]:[]},"actions"),states:rF,currentState:s((e,n)=>iF(e,{applicationId:n.applicationId,nodeId:n.node.id,templateKey:Cb}),"currentState"),workItemTemplates:s(e=>{let n=e;return ua(n)!=="online"?[]:[{key:Cb,recipient:"external",title:n.label,unlocks:oF.map(t=>t.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 U6)d in e&&i(d,{de:`[collectPayment/retiredField] \u201E${d}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`,en:`[collectPayment/retiredField] "${d}" is no longer on the payment node \u2014 amount and currency come from the article (parameter "Article"), and settlement is the parameter "Settlement" (inputs.settlement).`});r.push(...V6(e,t)),ua(e)===null&&i(`inputs.${Ht}`,{de:`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Os.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(e.inputs?.[Ht])}.`,en:`[collectPayment/invalidSettlement] Settlement must be one of ${Os.join(", ")} (online = the family pays in the portal, separate = the school bills outside Plexus); received ${JSON.stringify(e.inputs?.[Ht])}.`});let o=e.inputs?.[Ci];if(o?.kind==="literal"){let d=vf(o.value);d!==null&&i(`inputs.${Ci}`,{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=F6(e);if(a===null)return i(`inputs.${Ni}`,{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.${Ni}`;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 ${Ty.join(", ")}.`,en:`[collectPayment/articleNotOneTime] Article "${a}" is not a one-time article \u2014 a fee only takes ${Ty.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")};var qt="traeger",dF={de:"Tr\xE4ger",en:"Provider"};function Zp(e){let n=e.inputs?.[qt];return n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0?n.value:null}s(Zp,"traegerKeyOfNode");var Xp={name:"input.traeger.name",address:"input.traeger.anschrift"},y$e=Object.values(Xp);var cF="governedDocument",Fo="prepareDocument",Ad="prepareDocument:revision",Br="releaseApproval",Lo="documentResponse",Ur="responseCheck",em="returnSigned";var uF="requestApproval";var fF="issueDocument",pF="correctInPlace",mF="rescindAndReissue",nm="requestChange";var fa="releaseArtifact",ft="signingRecovery",Mo="resendESignature",qo="switchToPaper";var Yb=new Set([Fo,Ad]),hF=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],tm=["upload","resolver","template","none"],Ko=1,jo=366,ui="responseDueInDays";function Hb(e){let n=e.inputs?.[ui];return n?.kind==="literal"&&Ed(n.value)?n.value:void 0}s(Hb,"responseDueInDaysForVocabulary");function Ed(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Ko&&e<=jo}s(Ed,"isValidResponseDueInDays");var rm=["generatedAt","responseDueInDays","countersignature"],Bo=["release","none"],im=["confirm","signedUpload","signedUploadChecked","eSignature"];function gF(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(gF,"localeFieldMissingText");var Jb=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),yF=/^[a-z][a-z0-9_]*$/;function wF(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"||!yF.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(!_i(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 (${Is.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 (${Is.join(", ")}).`}});continue}if(Jb.has(a.type)||t.push({path:l,reason:{de:`[governedDocument/templateFieldType] Feld "${a.key}" der Vorlage "${n}" hat den Typ "${a.type}" \u2014 ein Brief druckt nur ${[...Jb].join(", ")}.`,en:`[governedDocument/templateFieldType] Field "${a.key}" of the template "${n}" has the type "${a.type}" \u2014 a letter only prints ${[...Jb].join(", ")}.`}}),a.type==="enum"&&Array.isArray(a.options)&&a.options.some(d=>!yF.test(String(d.value)))&&t.push({path:l,reason:{de:`[governedDocument/templateFieldKey] Auswahlfeld "${a.key}" der Vorlage "${n}" hat Optionen, die kein Platzhalter adressieren kann (${a.options.map(d=>d.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${a.key}.<option>).`,en:`[governedDocument/templateFieldKey] Select field "${a.key}" of the template "${n}" has options no placeholder can address (${a.options.map(d=>d.value).join(", ")}) \u2014 option values are lower-case letters, digits and _ (printed as input.${a.key}.<option>).`}}),a.type==="enum"&&(!Array.isArray(a.options)||a.options.length===0)&&t.push({path:l,reason:{de:`[governedDocument/templateFieldOptions] Auswahlfeld "${a.key}" der Vorlage "${n}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${a.key}.<option>.`,en:`[governedDocument/templateFieldOptions] Select field "${a.key}" of the template "${n}" names no options \u2014 without them there are no sections input.${a.key}.<option>.`}}),a.type==="pricedItem"){let d=i.find(c=>c.key===a.priceDate);(d===void 0||d.type!=="date")&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Preisfeld "${a.key}" der Vorlage "${n}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(a.priceDate)}.`,en:`[governedDocument/templateFieldPriceDate] Price field "${a.key}" of the template "${n}" names no price date \u2014 priceDate must be a date field of the same template (which price version applies); named: ${JSON.stringify(a.priceDate)}.`}})}else a.priceDate!==void 0&&t.push({path:l,reason:{de:`[governedDocument/templateFieldPriceDate] Feld "${a.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`,en:`[governedDocument/templateFieldPriceDate] Field "${a.key}" sets priceDate but is not a price field (pricedItem).`}});a.processSource==="countersignature"?t.push({path:l,reason:{de:`[governedDocument/countersignatureInTemplate] Feld "${a.key}" wird bei einer Gegenzeichnung gesetzt \u2014 ein Brief aus einer Vorlage wird nicht gegengezeichnet.`,en:`[governedDocument/countersignatureInTemplate] Field "${a.key}" is set at a countersignature \u2014 a letter from a template is not countersigned.`}}):a.processSource!==void 0&&!rm.includes(a.processSource)&&t.push({path:l,reason:{de:`[governedDocument/unknownProcessSource] Feld "${a.key}" nennt die unbekannte Vorgangsquelle "${String(a.processSource)}" \u2014 bekannt sind ${rm.join(", ")}.`,en:`[governedDocument/unknownProcessSource] Field "${a.key}" names the unknown case source "${String(a.processSource)}" \u2014 known are ${rm.join(", ")}.`}})}return t.push(...G6(e,n)),t}s(wF,"templateParameterIssues");function G6(e,n){if(e.localeField===void 0)return[{path:"localeField",reason:gF(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=>!ze.includes(i.value))?{de:`hat Optionen, die keine Sprache sind (erlaubt: ${ze.join(", ")})`,en:`has options that are not a language (allowed: ${ze.join(", ")})`}:null;return r===null?[]:[{path:"localeField",reason:{de:`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${n}" ${r.de}.`,en:`[governedDocument/localeField] The language field "${e.localeField}" of the template "${n}" ${r.en}.`}}]}s(G6,"localeFieldIssues");function kF(e,n){if(n===null){delete e.templateStamp;return}e.templateStamp={fields:structuredClone(n.fields),...n.localeField===void 0?{}:{localeField:n.localeField}}}s(kF,"applyTemplateStamp");var Qb=50;async function om(e,n){let t=await e.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",n)).take(Qb+1);return t.length>Qb&&F(`signing_returns: Vorgang ${n} has more than ${Qb} returns`),t}s(om,"returnsOf");var Zb=50;async function Xb(e,n){let t=await e.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",n)).take(Zb+1);return t.length>Zb&&F(`signing_returns: return ${n} has more than ${Zb} files`),t.length===0&&F(`[signing/noDocument] return ${n} carries no file`),t}s(Xb,"returnDocumentsOf");async function bF(e,n){let t=await Xb(e,n);return t.length!==1&&F(`[signing/severalDocuments] return ${n} carries ${t.length} files; this reader handles one`),t[0]}s(bF,"soleReturnDocumentOf");var sm=200,M$e=sm*20;async function z6(e,n){let t=await e.db.get(n);return t===null&&F(`[process] application ${n} not found`),t.redactedAt!==void 0}s(z6,"processRedacted");async function ev(e,n){await z6(e,n)&&le("CONFLICT",{de:"Die Daten dieser Bewerbung wurden gel\xF6scht.",en:"The data of this application has been deleted."})}s(ev,"assertProcessReadable");function W6(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(W6,"rowOf");async function vF(e,n,t){await ev(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(sm+1);return r.length>sm&&F(`[process] application ${n} has more than ${sm} results of ${t.scope}.${t.owner}.${t.key}`),r.map(W6)}s(vF,"storeHistory");async function Y6(e,n,t){if(t.key===it){await ev(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 vF(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(Y6,"nodeResultAt");async function am(e,n){let t={scope:"node",owner:n.nodeId,key:n.key};return H6(await Y6(e,n.applicationId,t),t,n.applicationId)}s(am,"readOwnResult");function H6(e,n,t){return e.state!=="present"?{state:"pending"}:(e.result.kind!=="ref"&&F(`[process] ${se(n)} of application ${t} holds a value \u2014 this address holds a ref`),{state:"ref",ref:e.result.ref,row:e.row})}s(H6,"refOf");var nv={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},J6=Object.keys(nv),Q6=J6.filter(e=>nv[e]==="open"),W$e=Q6.filter(e=>e!=="pending");function xF(e){return nv[e]==="terminal"}s(xF,"isTerminalSigningStatus");var Bi=["docusign","insign"];var Td={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var X6=xF;function AF(e){return!X6(e.status)&&e.voidRequestedAt===void 0}s(AF,"holdsContract");async function EF(e,n){return await e.db.query("legal_entities").withIndex("by_partyId",t=>t.eq("partyId",n)).unique()}s(EF,"traegerLegalEntityOfParty");async function e4(e,n){return await e.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",n)).first()!==null}s(e4,"isOrganizationParty");async function TF(e,n){return await EF(e,n)!==null?"traeger":await e4(e,n)?"organization":"person"}s(TF,"signerKindOf");async function $F(e,n){n.length===0&&F("signingSideOf: a Vorgang without signers asks nobody");for(let t of n)if(await n4(e,t.partyId)==="family")return"family";return"traeger"}s($F,"signingSideOf");async function n4(e,n){return await TF(e,n)==="traeger"?"traeger":"family"}s(n4,"sideOfParty");var TRe=16*1024;var $Re=15*6e4;var RRe=10*6e4;var tv={contractSnapshotId:Yn.restrict(w.id("contract_snapshots")),storageId:Yn.restrict(w.id("_storage")),sha256:w.string(),filename:w.string(),uploadedAt:w.number(),signers:w.array(w.object({partyId:Yn.history(w.id("parties")),role:w.string()}))},GRe=Jr({tenantId:Yn.tenant(w.id("tenants")),signingRequestDocumentId:Yn.belongsTo(w.id("signing_request_documents")),...tv}).index("by_tenantId",["tenantId"]).index("by_signingRequestDocumentId",["signingRequestDocumentId"]).index("by_contractSnapshotId",["contractSnapshotId"]).index("by_storageId",["storageId"]);var JRe=w.object(tv);var rv=200;async function r4(e,n,t,r){n.length>rv&&F(`${r} is carried by more than ${rv} 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(r4,"requestsOfMembers");async function RF(e,n,t="asc"){let r=await e.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",n)).take(rv+1);return await r4(e,r,t,`revision ${n}`)}s(RF,"requestsOfSnapshot");var IF=100;async function i4(e,n){let t=await RF(e,n);t.length>IF&&F(`requestsBySideOf: revision ${n} has more than ${IF} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of t.sort((o,a)=>o._creationTime-a._creationTime))r[await $F(e,i.signers)].push(i);return r}s(i4,"requestsBySideOf");async function iv(e,n){return(await i4(e,n)).family}s(iv,"familyRequestsOf");var ov=100;async function o4(e,n){let t=await e;return t.length>ov&&F(`contractChain: more than ${ov} ${n}`),t}s(o4,"bounded");async function s4(e,n,t){let r=await am(e,{applicationId:n,nodeId:t,key:Es});return r.state==="pending"?null:(r.ref.kind!=="contract"&&F(`contractChain: $node.${t}.${Es} of application ${n} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}s(s4,"nodeContractRef");async function OF(e,n){return await o4(e.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",t=>t.eq("contractId",n)).take(ov+1),`revisions on contract ${n}`)}s(OF,"snapshotsAsc");async function sv(e,n){let t=(await iv(e,n)).filter(AF);return t.length>1&&F(`contractChain: revision ${n} has ${t.length} open family Vorg\xE4nge`),t[0]??null}s(sv,"openFamilyRequest");async function a4(e,n){for(let t of await OF(e,n))if((await iv(e,t._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}s(a4,"familyRoute");async function PF(e,n){for(let t of n)if(await a4(e,t)==="paper")return"paper";return"provider"}s(PF,"familyRouteOf");async function l4(e,n){let t=await bF(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(l4,"toReturn");function lm(e){async function n(a,l){return await s4(a,l,e.id)}s(n,"contractOrNull");async function t(a,l,d,c){let u=a.db.normalizeId("contract_snapshots",d),f=u===null?null:await a.db.get(u),m=await n(a,l);return(f===null||m===null||f.contractId!==m)&&F(`${c}: ${d} is no revision of node "${e.id}"'s contract ${m??"(none yet)"} \u2014 corrupt arc`),f}s(t,"snapshotOf");async function r(a,l){let d=await n(a,l);return d===null?null:(await OF(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 sv(a,c._id);if(u===null)return null;let f=(await om(a,u._id)).filter(m=>m.review.status==="pending"&&m._id!==d.rejected);return f.length>1&&F(`returned(${d.where}): Vorgang ${u._id} has ${f.length} returns pending \u2014 one is checked at a time`),f[0]===void 0?null:await l4(a,f[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(lm,"contractNodeReads");function dm(e){return e.addedParts??[]}s(dm,"addedPartsOf");var av=50;async function d4(e,n){let t=await e.db.query("contract_generation_runs").withIndex("by_packageRunId",r=>r.eq("packageRunId",n)).take(av+1);return t.length>av&&F(`groupRunsOf: generation group ${n} has more than ${av} runs`),t.length===0&&F(`groupRunsOf: generation group ${n} has no run`),t.sort((r,i)=>r._creationTime-i._creationTime)}s(d4,"groupRunsOf");async function _F(e,n){let t=await d4(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_packageRevisionId_and_position",l=>l.eq("packageRevisionId",i.packageRevisionId)).take(51),a=[...o.map(l=>l.partKey),...dm(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(_F,"groupRunsInOrder");function NF(e){return e.every(n=>n.status==="succeeded"&&n.contractId!==void 0&&n.contractSnapshotId!==void 0)}s(NF,"isCompleteGroup");var lv=200;function c4(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(c4,"groupPartKeys");async function u4(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(lv+1);return r.length>lv&&F(`groupChain: more than ${lv} generation runs on node ${t}`),r}s(u4,"nodeRuns");async function f4(e,n,t){let r=c4(t),i=new Set;for(let a of await u4(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 _F(e,a);if(!NF(l))continue;let d=await e.db.get(a);d===null&&F(`groupChain: generation group ${a} has no package run`);let c=new Set(dm(d).map(f=>f.partKey)),u=[];for(let f of l){!r.includes(f.partKey)&&!c.has(f.partKey)&&F(`groupChain: run ${f._id} renders part "${f.partKey}", which node "${t.id}"'s pin does not declare and nobody added`);let m=await e.db.get(f.contractSnapshotId);m===null&&F(`groupChain: run ${f._id} names revision ${f.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),u.push({run:f,snapshot:m})}o.push({packageRunId:a,startedAt:Math.min(...l.map(f=>f._creationTime)),members:u})}return o.sort((a,l)=>a.startedAt-l.startedAt)}s(f4,"groupRevisionRows");async function dv(e,n,t){let r=await am(e,{applicationId:n,nodeId:t,key:Ts});return r.state==="pending"?[]:(r.ref.kind!=="contracts"&&F(`groupChain: $node.${t}.${Ts} of application ${n} is a ${r.ref.kind} ref \u2014 the group chain writes a contracts ref`),[...r.ref.contracts])}s(dv,"nodeGroupContracts");async function p4(e,n){let t=new Map;for(let{snapshot:r}of n.members){let i=await sv(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(p4,"openGroupRequest");async function m4(e,n){let t=[];for(let i of await Xb(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(m4,"toGroupReturn");function CF(e){async function n(i,o,a,l){let d=(await f4(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 p4(i,l);if(d===null)return null;let c=(await om(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 m4(i,c[0])},pinOf(i){return i.contractSnapshotId},returnPinOf(i){return i.signingReturnId}},revisionRowOf:n,contractsOf:{async contractsOf(i,o){return(await dv(i,o,e.id)).map(a=>a.contractId)}}.contractsOf}}s(CF,"groupNodeReads");var h4={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",outcomeSemantics:{accept:"granted",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},DF={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",outcomeSemantics:{accept:"other",decline:"rejected"},acceptEvent:"userTaskResolved",producesResponseArtifact:!0,declineIsAnswer:!1,acceptStatus:"signed",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Unterschrieben zur\xFCcksenden",en:"Return signed"},decline:{de:"Ablehnen",en:"Decline"}}},FF={...DF,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},g4={...FF,kind:"eSignature",issuesBy:"provider"},fi={confirm:h4,signedUpload:DF,signedUploadChecked:FF,eSignature:g4};function Ui(e){let n=e.responseStrategy;if(typeof n=="string"&&n in fi)return fi[n];F(`governedDocument node "${e.id}" declares no valid responseStrategy (got ${JSON.stringify(n)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}s(Ui,"responseStrategyOf");function LF(e){if(e.type!==cF||e.production!=="resolver")return!1;let n=e.responseStrategy;return typeof n=="string"&&n in fi?fi[n].acceptEvent==="contractEvent":!1}s(LF,"isFamilySignedContractNode");function $d(e){return e.label}s($d,"governedDocTitle");function cv(e){return e.approval==="release"?uF:fF}s(cv,"submitActionId");function MF(e,n,t){return{key:n,recipient:"internal",title:t,unlocks:[cv(e)],gatesNode:!0,advancesNode:!0}}s(MF,"producerTemplate");function y4(e){return e.titles?.respond??e.label}s(y4,"responseTitle");var pa={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function uv(e){let n=Ui(e),t=[];if(e.production!=="none"&&t.push(MF(e,Fo,e.titles?.prepare??pa),MF(e,Ad,e.titles?.revise??pa)),e.approval==="release"&&t.push({key:Br,recipient:"internal",title:e.titles?.approve??pa,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),t.push({key:Lo,recipient:"external",title:y4(e),unlocks:n.producesResponseArtifact?[n.checksReturn?em:n.acceptOutcomeId,n.declineOutcomeId,nm]:[n.acceptOutcomeId,n.declineOutcomeId],advancesNode:!0,...Hb(e)!==void 0?{dueInDays:Hb(e)}:{}}),n.checksReturn&&t.push({key:Ur,recipient:"internal",title:e.titles?.check??pa,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),n.issuesBy==="provider"){let r=$d(e);t.push({key:ft,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Mo,qo],gatesNode:!1,advancesNode:!1})}return t}s(uv,"governedDocIntrinsicTemplates");function w4(e){e.production==="none"&&F(`governedDocSlot: node "${e.id}" has production 'none' \u2014 it governs no artifact slot`);let n=e.artifacts??[];n.length!==1&&F(`governedDocSlot: node "${e.id}" declares ${n.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let t=n[0];return(typeof t.key!="string"||t.key.length===0)&&F(`governedDocSlot: node "${e.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),t}s(w4,"governedDocSlot");function cm(e){return w4(e).key}s(cm,"governedDocSlotKey");async function k4(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 Qw(e,n.storageId),...n.filename!==void 0?{filename:n.filename}:{}}}s(k4,"toRevision");async function b4(e,n){let t=await k4(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(b4,"toReturn");function qF(e){let n=cm(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;le("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(f=>f._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 b4(o,c)},pinOf(o){return o.artifactVersionId},returnPinOf(o){return o.artifactVersionId}},contentRowsAsc:t,contractsOf:{async contractsOf(){return[]}}.contractsOf}}s(qF,"artifactNodeReads");function um(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(um,"documentChainKind");function KF(e){switch(um(e)){case"contract":return lm(e).reads;case"group":return CF(e).reads;case"artifact":return qF(e).reads}}s(KF,"documentReadsFor");var v4={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function Rd(e){let n=e.responseStrategy;return typeof n=="string"&&n in fi?fi[n].producesResponseArtifact:!1}s(Rd,"returnsSignedCopy");function x4(e){return Rd(e)&&e.confirmContractTerms!==!1}s(x4,"asksContractTerms");function jF(e){return x4(e)?{title:e.contractTermsQuestionText??v4,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(jF,"contractTermsConfirm");async function S4(e,n,t){if(t.revisesWorkItemId===void 0)return;let r=await e.db.get(t.revisesWorkItemId),i=r===null?null:Hy(r),o=i?.context,a=o?.kind==="admission"?n.returnPinOf(o):void 0;return(i===null||o===void 0||o.kind!=="admission"||i.templateKey!==Ur||i.status!=="done"||i.outcome!=="rejected"||a===void 0)&&F(`rejectedReturnOfAsk: ask ${t._id} revises ${t.revisesWorkItemId}, which is not a rejected, pinned ${Ur} row`),a}s(S4,"rejectedReturnOfAsk");async function BF(e,n){return await n.chain.returned(e,n.applicationId,{askedAbout:n.chain.pinOf(n.ask),rejected:await S4(e,n.chain,n.ask),onUnpinned:n.onUnpinned,where:n.where})}s(BF,"returnedCopyOfAsk");var fv=new Set([...Yb,Br,Lo,Ur,ft]),zF={id:Kn,type:"contractGenerator",label:{de:"Vertragsgenerator",en:"Contract generator"},required:!0,inspector:"literal-only",optionSource:"tenantGenerators"},WF={id:ho,type:"documentTemplate",label:{de:"Dokumentvorlage",en:"Document template"},required:!0,inspector:"literal-only",optionSource:"tenantDocumentTemplates"};function A4(e){let n=[],t=[{slot:zF,production:"resolver",de:{a:"einen",the:"der",it:"ihn"}},{slot:WF,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(Re(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(Re(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=kl(a.value,{type:r.type});d!==null&&n.push(Re(e,l,{de:`[governedDocument/referenceShape] Knoten "${e.id}": ${d}.`,en:`[governedDocument/referenceShape] Node "${e.id}": ${d}.`}))}return n}s(A4,"referenceInputIssues");var E4={id:ui,type:"number",label:{de:"Antwortfrist (Tage)",en:"Answer within (days)"},inspector:"literal-only"},T4={id:qt,type:"legalEntity",label:dF,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function $4(e,n){let t=`inputs.${qt}`,r=e.inputs?.[qt];if(r!==void 0&&r.kind==="binding")return[Re(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=Zp(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(Re(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(Re(e,t,{de:`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${e.id}" druckt die Anschrift des Tr\xE4gers (${Xp.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 (${Xp.address}), but "${l}" has none \u2014 add it in the school's configuration (foundation.legalEntities[].address).`}))}return a}s($4,"traegerIssues");function pm(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}}:(Ti(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(pm,"generatorFields");function R4(e,n){return e.inputs?.[n]?.kind==="cockpit"}s(R4,"deferredToCockpit");function I4(e){return _i(e.type)?e.type:void 0}s(I4,"resolverSlotType");function O4(e){if(e.confirmBeforeIssue!==!0||e.approval!=="none")return null;let n=$d(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(O4,"issueConfirmation");function Re(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(Re,"issue");function fm(e){return tm.includes(e.production)&&Bo.includes(e.approval)&&im.includes(e.responseStrategy)}s(fm,"hasValidModes");async function pv(e,n){let t=await Il(e,{applicationId:n.applicationId,nodeId:n.node.id});if(t.length===0)return"pending";let r=t.filter(l=>l.isOpen&&l.kind==="admission"),i=r.filter(l=>l.templateKey!==void 0&&Yb.has(l.templateKey));if(i.length>0)return i.every(l=>l.status==="blocked")?"producingHeld":"producing";let o=r.find(l=>l.templateKey===Br);if(o!==void 0)return o.status==="blocked"?"deferred":"awaitingApproval";if(r.some(l=>l.templateKey===ft))return"signatureStalled";let a=r.find(l=>l.templateKey===Lo);if(a!==void 0){if(Ui(n.node).issuesBy==="provider"){let d=um(n.node)==="group"?(await dv(e,n.applicationId,n.node.id)).map(c=>c.contractId):[await lm(n.node).contractOrNull(e,n.applicationId)].flatMap(c=>c===null?[]:[c]);if(d.length===0&&F(`governedDocCurrentState: eSignature node "${n.node.id}" has an open ask but no contract`),await PF(e,d)==="provider")return"awaitingSignature"}return Ui(n.node).producesResponseArtifact?await BF(e,{chain:KF(n.node),applicationId:n.applicationId,ask:a,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${n.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return r.some(l=>l.templateKey===Ur)?"responseInCheck":"done"}s(pv,"governedDocCurrentState");function UF(e){return e.production!=="none"&&um(e)!=="artifact"}s(UF,"keepsDocumentInContractDomain");function P4(e,n){let t=e.inputs?.[n.key];if(t?.kind!=="binding")return[];let r=t.address;if(!we(r)||r.scope!=="env"||!pr(r.key))return[];let i=mo(r.key);if(n.type!==i.type)return[Re(e,`inputs.${n.key}`,{de:`[governedDocument/envNotCovered] Feld "${n.key}" ist ${n.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${se(r)}) liefert ${i.type}.`,en:`[governedDocument/envNotCovered] Field "${n.key}" is ${n.type}, the environment variable "${i.label.en}" (${se(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?[]:[Re(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(P4,"envCoverageIssues");function YF(e,n){let t=[];for(let r of pm(e)){if(r.type==="party"||r.type==="personList")continue;if(t.push(...P4(e,r)),r.processSource!==void 0){let a=e.inputs?.[r.key],l=a?.kind==="binding"?{de:`eine Bindung an ${we(a.address)?se(a.address):JSON.stringify(a.address)}`,en:`a binding to ${we(a.address)?se(a.address):JSON.stringify(a.address)}`}:a?.kind==="literal"?{de:"ein fester Wert",en:"a fixed value"}:R4(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(YF,"fieldSourceIssues");function _4(e){let n=mr(e)??"\u2014";if(e.templateStamp===void 0)return[];let t=wF(e.templateStamp,n).map(({path:r,reason:i})=>Re(e,r===""?"templateStamp":`templateStamp.${r}`,i));return t.push(...YF(e,{de:`Vorlage "${n}"`,en:`template "${n}"`})),t}s(_4,"templateIssues");function N4(e,n){return(n?.resolverDocumentAnchors?.get(e.id)??[]).flatMap(t=>{if(t.documentAnchors===null)return[Re(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?[]:[Re(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(N4,"eSignatureAnchorIssues");function C4(e,n){return n===void 0||n.sendable?[]:Ui(e).issuesBy!=="provider"?[]:[Re(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(C4,"eSignatureProviderIssues");var VF={key:"dokument",label:te("Dokument","Document"),scope:"node"},GF={producing:{label:te("Dokument in Vorbereitung","Document in preparation"),tone:"blue",phase:VF,external:en(te("In Vorbereitung","In preparation"),"blue",te("Ihr Dokument wird vorbereitet","Your document is being prepared"),te("Die Schule erstellt Ihr Dokument. Sie erhalten es in K\xFCrze im Portal.","The school is preparing your document. You will receive it in the portal shortly."))},issued:{label:te("Dokument bereitgestellt","Document issued"),tone:"blue",phase:VF,external:en(te("Dokument bereit","Document ready"),"amber",te("Ihr Dokument liegt bereit","Your document is ready"),te("Bitte beantworten Sie das Dokument innerhalb der Frist. Sie finden es in Ihren Aufgaben.","Please respond to the document within the deadline. You will find it in your tasks."),te("Dokument beantworten","Respond to the document"))}},HF={role:"user-action",effect:"side-effect",processHoldTemplate:s(()=>Fo,"processHoldTemplate"),progressDefaults:GF,progressEvents:Dn(GF),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:"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(!fm(e))return[];let n=Ui(e),t=[],r=n.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=n.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,o=n.checksReturn?[...i,"responseInCheck"]:i;return e.production!=="none"&&(t.push({id:cv(e),kind:"internal",surface:fa,label:e.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...O4(e)??{}}),t.push({id:pF,kind:"internal",surface:fa,label:{de:"Korrigieren",en:"Correct"},availableIn:o,superUserOnly:!0},{id:mF,kind:"internal",surface:fa,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:o,superUserOnly:!0})),t.push(n.checksReturn?{id:em,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:i,external:{emphasis:"decline",event:"userTaskResolved"}}),n.producesResponseArtifact&&t.push({id:nm,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),n.issuesBy==="provider"&&t.push({id:Mo,kind:"internal",surface:fa,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:qo,kind:"internal",surface:fa,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),t},"actions"),states:hF,currentState:pv,workItemTemplates:s(e=>{let n=e;return fm(n)?uv(n):[]},"workItemTemplates"),taskDocuments:s((e,n)=>{let t=e;if(!fm(t)||t.production==="none")return[];let r=uv(t).find(i=>i.key===n);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:cm(t)}]},"taskDocuments"),inputs:s(e=>[...e.production==="resolver"?[zF,T4]:[],...e.production==="template"?[WF]:[],E4,...pm(e).filter(n=>n.type!=="party"&&n.type!=="personList").flatMap(n=>{let t=I4(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"&&Ii(n.defaultValue))?{defaultValue:n.defaultValue}:{},...n.options!==void 0?{enumOptions:n.options}:{}}))],"inputs"),outputs:s(e=>e.production==="none"?[]:[{name:hl,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:s((e,n)=>{if(n===Lo||n===Ad||n===Ur||n===ft){let t=n===Lo?{de:"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger",en:"the response task belongs to the recipient"}:n===Ur?{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===ft?{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: ${Fo}${e.approval==="release"?`, ${Br}`:""}.`,en:`[governedDocument/blocksTarget] 'blocks' on "${n}" (node "${e.id}") is not allowed \u2014 ${t.en}; allowed intrinsic targets: ${Fo}${e.approval==="release"?`, ${Br}`:""}.`}}return n===Br&&e.approval==="none"?{de:`[governedDocument/blocksTarget] 'blocks' auf "${Br}" auf Knoten "${e.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`,en:`[governedDocument/blocksTarget] 'blocks' on "${Br}" 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(UF(n.node))return!1;let t=await pv(e,n),r=(t==="awaitingResponse"||t==="responseReturned")&&Ui(n.node).producesResponseArtifact;return n.actor==="recipient"?r:t==="producing"&&n.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:s(async(e,n)=>{let t=jF(n.node);if(t===null||UF(n.node))return null;let r=await pv(e,n);return r==="awaitingResponse"||r==="responseReturned"?t:null},"userUploadConfirmation"),validate:s((e,n,t)=>{let r=[];if(!fm(e))return r.push(Re(e,"modes",{de:`[governedDocument/unknownMode] Knoten "${e.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${tm.join(", ")}} (ist: ${JSON.stringify(e.production)}), approval \u2208 {${Bo.join(", ")}} (ist: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${im.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 {${tm.join(", ")}} (is: ${JSON.stringify(e.production)}), approval \u2208 {${Bo.join(", ")}} (is: ${JSON.stringify(e.approval)}), responseStrategy \u2208 {${im.join(", ")}} (is: ${JSON.stringify(e.responseStrategy)}). A mode is a declared decision, never derived from the wiring.`})),r;let i=fi[e.responseStrategy];e.production==="none"&&(e.approval!=="none"||e.responseStrategy!=="confirm")&&r.push(Re(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(Re(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(Re(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 b of o)b.visibility!=="external"&&r.push(Re(e,"artifacts",{de:`[governedDocument/slotContract] Slot "${b.key}" auf Knoten "${e.id}" hat visibility "${b.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`,en:`[governedDocument/slotContract] Slot "${b.key}" on node "${e.id}" has visibility "${b.visibility}" \u2014 the managed document MUST be 'external', otherwise the applicant can never see it on /e.`}))}let a=e.outcomes??[],l=a.map(b=>b.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(b=>l.includes(b)))&&r.push(Re(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(b=>`"${b}"`).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(b=>`"${b}"`).join(", "):"none"}). Both are required: the node owns the answer, not only the release.`}));let c=e.titles,u=s(b=>{let A=c?.[b];return A===null||typeof A!="object"||!Object.values(A??{}).some($=>typeof $=="string"&&$.length>0)},"missingTitle"),f=[];e.production!=="none"&&f.push("prepare","revise"),e.approval==="release"&&f.push("approve"),i.checksReturn&&f.push("check");let m=f.filter(u);m.length>0&&r.push(Re(e,"titles",{de:`[governedDocument/missingTitles] Knoten "${e.id}" fehlen die Aufgaben-Titel ${m.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 ${m.join(", ")} \u2014 the node type is document-agnostic, titling is required configuration of its mode.`}));let y=e.assign??{};if(e.production!=="none"){let b=y.prepareDocument;(typeof b!="string"||b.length===0)&&r.push(Re(e,"assign.prepareDocument",{de:`[governedDocument/productionAssign] Knoten "${e.id}" (production '${e.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`,en:`[governedDocument/productionAssign] Node "${e.id}" (production '${e.production}') wires no producer team (assign.prepareDocument) \u2014 without a producer task there would be the submit action without an enabling work item.`}))}if(e.approval==="none"&&(y.releaseApproval!==void 0&&r.push(Re(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(Re(e,"titles.approve",{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`,en:`[governedDocument/deadWiring] Node "${e.id}" has approval 'none' but declares titles.approve \u2014 there is no release task that would carry this title.`}))),i.checksReturn){let b=y.responseCheck;(typeof b!="string"||b.length===0)&&r.push(Re(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(Re(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(Re(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(Re(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[b,A]of[["assign.responseCheck",y.responseCheck!==void 0],["titles.check",c?.check!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${b} \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 ${b} \u2014 a check of the returned copy only exists with responseStrategy 'signedUploadChecked' or 'eSignature'.`}))}if(i.issuesBy==="provider"){let b=y.signingRecovery;(typeof b!="string"||b.length===0)&&r.push(Re(e,"assign.signingRecovery",{de:`[governedDocument/recoveryAssign] Knoten "${e.id}" l\xE4sst elektronisch unterschreiben, verdrahtet aber kein Team f\xFCr die Kl\xE4rung einer Unterschrift, die nicht zustande kommt (assign.signingRecovery) \u2014 \u201EErneut senden" und \u201EAuf Papier umstellen" l\xE4gen bei niemandem.`,en:`[governedDocument/recoveryAssign] Node "${e.id}" is signed electronically but wires no team for resolving a signature that does not come about (assign.signingRecovery) \u2014 "Send again" and "Switch to paper" would lie with nobody.`}))}else y.signingRecovery!==void 0&&r.push(Re(e,"assign.signingRecovery",{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`,en:`[governedDocument/deadWiring] Node "${e.id}" (responseStrategy '${e.responseStrategy}') declares assign.signingRecovery \u2014 resolving an electronic signature only exists with responseStrategy 'eSignature'.`}));if(i.issuesBy==="provider"&&r.push(...N4(e,t),...C4(e,t?.signingProvider)),e.confirmBeforeIssue!==void 0&&typeof e.confirmBeforeIssue!="boolean"?r.push(Re(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(Re(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(Re(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.`})),Rd(e))e.confirmContractTerms===!1&&e.contractTermsQuestionText!==void 0&&r.push(Re(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[b,A]of[["confirmContractTerms",e.confirmContractTerms!==void 0],["contractTermsQuestionText",e.contractTermsQuestionText!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') deklariert ${b} \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 ${b} \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[b,A]of[["confirmBeforeIssue",e.confirmBeforeIssue===!0],["assign.prepareDocument",y.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0]])A&&r.push(Re(e,b,{de:`[governedDocument/deadWiring] Knoten "${e.id}" hat production 'none', deklariert aber ${b} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`,en:`[governedDocument/deadWiring] Node "${e.id}" has production 'none' but declares ${b} \u2014 without a production phase there is nothing to carry it.`}));for(let b of e.tasks??[])fv.has(b.key)&&r.push(Re(e,`tasks.${b.key}`,{de:`[governedDocument/keyShadowsIntrinsic] Task-Key "${b.key}" auf Knoten "${e.id}" kollidiert mit einem intrinsischen Template (${[...fv].join(", ")}) \u2014 anderen Key w\xE4hlen.`,en:`[governedDocument/keyShadowsIntrinsic] Task key "${b.key}" on node "${e.id}" collides with an intrinsic template (${[...fv].join(", ")}) \u2014 choose another key.`}));if(e.production==="resolver"?r.push(...$4(e,t)):e.inputs?.[qt]!==void 0&&r.push(Re(e,`inputs.${qt}`,{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(...A4(e)),e.production==="resolver"){let b=ei(e);if(b!==null){let A=qR(b);for(let $ of pm(e)){if(!_i($.type)){r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/unknownFieldType] Generator "${A}" typisiert das Feld "${$.key}" als "${String($.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${Is.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`,en:`[governedDocument/unknownFieldType] Generator "${A}" types the field "${$.key}" as "${String($.type)}" \u2014 that is not part of the platform's value vocabulary (${Is.join(", ")}). The pinned revision comes from an older version and must be sealed again.`}));continue}if($.type==="personList"){r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/partyListUnsupported] Generator "${A}" deklariert das Feld "${$.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 "${A}" declares the field "${$.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}$.type==="party"&&($.key.endsWith("PartyId")||r.push(Re(e,`generatorStamp.inputSchema.${$.key}`,{de:`[governedDocument/partyFieldKey] Party-Feld "${$.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 "${$.key}" does not end in "PartyId" \u2014 the placeholder prefix in the document is derived from this suffix (emergencyContactPartyId \u2192 emergency_contact).`})))}r.push(...YF(e,{de:`"${A}"`,en:`"${A}"`}))}}else e.generatorStamp!==void 0&&r.push(Re(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(..._4(e)):e.templateStamp!==void 0&&r.push(Re(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?.[ui],g=k===void 0||k.kind==="unset"?void 0:k.kind==="literal"?k.value:k;return g!==void 0&&!Ed(g)&&r.push(Re(e,`inputs.${ui}`,{de:`[governedDocument/dueInDays] Knoten "${e.id}" setzt responseDueInDays auf ${JSON.stringify(g)} \u2014 erlaubt ist eine ganze Zahl von ${Ko} bis ${jo} Tagen.`,en:`[governedDocument/dueInDays] Node "${e.id}" sets responseDueInDays to ${JSON.stringify(g)} \u2014 a whole number from ${Ko} to ${jo} days is allowed.`})),g===void 0&&pm(e).some(b=>b.processSource==="responseDueInDays")&&r.push(Re(e,`inputs.${ui}`,{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 mm="countersign",mv="countersign",JF="countersigned",QF="countersigning",ZF="countersigned";var XF={de:"Vertrag gegenzeichnen",en:"Countersign the contract"},Id=["scan","eSignature"],hm="service_provider:1",eL=["countersigning","awaitingSignature","signatureStalled","done"],nL={de:"Elektronische Gegenzeichnung kl\xE4ren",en:"Resolve the electronic countersignature"};function tL(e){return{de:`[countersign/traegerSignatoryMissing] Die Schule zeichnet elektronisch gegen, aber f\xFCr ${e} ist keine Unterschriftsperson hinterlegt, die unterschreiben kann (Rechtstr\xE4ger \u2192 signatoryUserKey, aktives Personal der Schule).`,en:`[countersign/traegerSignatoryMissing] The school countersigns electronically, but no signatory who can sign is on file for ${e} (legal entity \u2192 signatoryUserKey, active staff of the school).`}}s(tL,"traegerSignatoryMissingReason");function nr(e,n,t){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:"error"}}s(nr,"issue");function oL(e,n){return e.nodes.filter(t=>{let r=t.contract;return t.type==="countersign"&&we(r)&&r.scope==="node"&&r.owner===n})}s(oL,"countersignersOf");function Od(e){return e.signing==="eSignature"}s(Od,"isElectronic");function D4(e,n){if(n===void 0||n.sendable||!Od(e))return[];let t=e.label?.de??e.id,r=e.label?.en||e.id;return[nr(e,"signing",{de:`[countersign/eSignatureNeedsProvider] \u201E${t}\u201C zeichnet elektronisch gegen, aber die Schule kann nicht senden: ${n.reason.de}`,en:`[countersign/eSignatureNeedsProvider] "${r}" countersigns electronically, but the school cannot send: ${n.reason.en}`})]}s(D4,"countersignProviderIssues");function F4(e,n,t){if(t.scope!=="node")return[];let r=e.nodes.find(o=>o.id===t.owner);if(r===void 0)return[];let i=[];return LF(r)||i.push("sourceNotCheckedContract"),oL(e,r.id).some(o=>o.id!==n)&&i.push("twice"),i}s(F4,"countersignContractRefusals");function rL(e){let n=e.inputs?.dueInDays;return n?.kind==="literal"&&typeof n.value=="number"&&Number.isInteger(n.value)&&n.value>=1?n.value:void 0}s(rL,"validDueInDays");function L4(e,n,t){let r=e.label?.de??e.id,i=e.label?.en||e.id,o=e.signing;if(o!==void 0&&!Id.includes(o))return[nr(e,"signing",{de:`[countersign/unknownSigning] \u201E${r}\u201C: signing ist scan oder eSignature (gefunden: ${JSON.stringify(o)}).`,en:`[countersign/unknownSigning] "${i}": signing is scan or eSignature (found: ${JSON.stringify(o)}).`})];let a=e.assign?.[ft];if(!Od(e))return a===void 0?[]:[nr(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet auf Papier gegen \u2014 \`assign.signingRecovery\` h\xE4lt keine Aufgabe und geh\xF6rt entfernt.`,en:`[countersign/recoveryAssign] "${i}" countersigns on paper \u2014 \`assign.signingRecovery\` holds no task and must be removed.`})];let l=[];return(typeof a!="string"||a.length===0)&&l.push(nr(e,"assign",{de:`[countersign/recoveryAssign] \u201E${r}\u201C zeichnet elektronisch gegen \u2014 wer eine gescheiterte Gegenzeichnung kl\xE4rt, fehlt: \`assign.signingRecovery\` nennt das Team.`,en:`[countersign/recoveryAssign] "${i}" countersigns electronically \u2014 who resolves a failed countersignature is missing: \`assign.signingRecovery\` names the team.`})),l.push(...M4(e,n,t),...q4(e,n,t),...D4(e,t?.signingProvider)),l}s(L4,"signingIssues");function sL(e,n){let t=e.contract;if(!(!we(t)||t.scope!=="node"))return n.nodes.find(r=>r.id===t.owner)}s(sL,"contractNodeOf");function M4(e,n,t){let r=sL(e,n),i=r===void 0?null:Zp(r),o=i===null?void 0:t?.traeger?.get(i);return o===void 0||o.hasSignatory?[]:[nr(e,"signing",tL(o.name))]}s(M4,"traegerSignatoryIssues");function q4(e,n,t){let r=sL(e,n);if(r===void 0)return[];let i=t?.resolverDocumentAnchors?.get(r.id);if(i===void 0)return[];let o=e.label?.de??e.id,a=e.label?.en||e.id,l=[];for(let d of i)d.documentAnchors===null?l.push(nr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage des Generators \u201E${d.pin}\u201C wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of generator "${d.pin}" was never read for signature anchors \u2014 upload the template again and seal the generator again.`})):d.documentAnchors.has(hm)||l.push(nr(e,"signing",{de:`[countersign/eSignatureAnchorMissing] \u201E${o}\u201C zeichnet elektronisch gegen, aber die Vorlage von \u201E${d.pin}\u201C tr\xE4gt keinen Anker /unterschrift:${hm}/ \u2014 der Anbieter f\xE4nde f\xFCr die Schule kein Unterschriftsfeld.`,en:`[countersign/eSignatureAnchorMissing] "${a}" countersigns electronically, but the template of "${d.pin}" carries no anchor /unterschrift:${hm}/ \u2014 the provider would find no signature field for the school.`}));return l}s(q4,"traegerAnchorIssues");var hv=100;async function K4(e,n){let t=await e.db.query("work_items").withIndex("by_applicationId_and_nodeId",o=>o.eq("context.applicationId",n.applicationId).eq("context.anchor.nodeId",n.node.id)).take(hv+1);t.length>hv&&F(`countersign node "${n.node.id}" of ${n.applicationId} holds more than ${hv} rows`);let r=t.filter(o=>o.isOpen),i=s(o=>{if(o.context.kind!=="admission")return;let a=o.context.anchor;return"templateKey"in a?a.templateKey:void 0},"templateKeyOf");return r.some(o=>i(o)===ft)?"signatureStalled":r.some(o=>i(o)===mm)?"countersigning":Od(n.node)?"awaitingSignature":"done"}s(K4,"countersignCurrentState");var iL={[QF]:{label:te("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:te("Gegenzeichnung","Countersignature"),scope:"node"},external:en(te("Vertrag unterschrieben","Contract signed"),"blue",te("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),te("Vielen Dank f\xFCr Ihre Unterschrift. Sobald die Schule gegengezeichnet hat, finden Sie Ihr Exemplar hier.","Thank you for signing. As soon as the school has countersigned, you will find your copy here."))}},aL={inputs:s(()=>[{id:"dueInDays",label:{de:"Frist der Aufgabe (Tage)",en:"Task due in (days)"},type:"number",inspector:"literal-only"}],"inputs"),role:"user-action",effect:"side-effect",outcomes:[{id:JF,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressDefaults:iL,progressEvents:Dn(iL),notificationEvents:s(()=>[{id:ZF,label:{de:"Vertrag gegengezeichnet",en:"Contract countersigned"},audience:"external",required:!0,args:[{key:"applicationId",type:"string",required:!0},{key:"documentTitle",type:"localizedText",required:!0}]}],"notificationEvents"),actions:s(e=>[{id:mv,kind:"internal",label:XF,surface:er,availableIn:["countersigning"]},...Od(e)?[{id:Mo,kind:"internal",surface:er,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:qo,kind:"internal",surface:er,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}]:[]],"actions"),workItemTemplates:s(e=>[{key:mm,recipient:"internal",title:e.titles?.countersign??pa,unlocks:[mv],advancesNode:!0,...rL(e)!==void 0?{dueInDays:rL(e)}:{}},...Od(e)?[{key:ft,recipient:"internal",title:nL,unlocks:[Mo,qo],gatesNode:!1,advancesNode:!1}]:[]],"workItemTemplates"),states:eL,currentState:K4,validate:s((e,n,t)=>{let r=[],i=e.label?.de??e.id,o=e.label?.en||e.id,a=e.assign?.[mm];(typeof a!="string"||a.length===0)&&r.push(nr(e,"assign",{de:`[countersign/assign] \u201E${i}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`,en:`[countersign/assign] "${o}": who countersigns is missing \u2014 \`assign.countersign\` names the team.`})),Ti(e.titles?.countersign)||r.push(nr(e,"titles",{de:`[countersign/missingTitle] \u201E${i}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`,en:`[countersign/missingTitle] "${o}": the task title is missing \u2014 \`titles.countersign\` in German and English.`}));let l=e.inputs?.dueInDays;l!==void 0&&l.kind!=="unset"&&!(l.kind==="literal"&&typeof l.value=="number"&&Number.isInteger(l.value)&&l.value>=1)&&r.push(nr(e,"inputs.dueInDays",{de:`[countersign/dueInDays] \u201E${i}": dueInDays ist eine ganze Zahl \u2265 1.`,en:`[countersign/dueInDays] "${o}": dueInDays is a whole number \u2265 1.`})),r.push(...L4(e,n,t));let d=e.contract;if(!we(d))return r;let c=F4(n,e.id,d);if(c.length===0)return r;let u=n.nodes.find(f=>d.scope==="node"&&f.id===d.owner);if(c.includes("sourceNotCheckedContract")&&r.push(nr(e,"contract",{de:`[countersign/sourceNotCheckedContract] \u201E${i}" zeichnet das Dokument von \u201E${u.label?.de??u.id}" (${u.id}) gegen \u2014 gegenzeichnen l\xE4sst sich nur ein erzeugter Vertrag, den die Familie mit verbuchten Unterschriften unterschreibt (governedDocument mit production: resolver und responseStrategy: signedUploadChecked oder eSignature).`,en:`[countersign/sourceNotCheckedContract] "${o}" countersigns the document of "${u.label?.en||u.id}" (${u.id}) \u2014 only a generated contract that the family signs with booked signatures can be countersigned (governedDocument with production: resolver and responseStrategy: signedUploadChecked or eSignature).`})),c.includes("twice")){let f=oL(n,u.id).filter(m=>m.id!==e.id);r.push(nr(e,"contract",{de:`[countersign/twice] \u201E${i}": \u201E${u.label?.de??u.id}" (${u.id}) wird schon von ${f.map(m=>`"${m.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`,en:`[countersign/twice] "${o}": "${u.label?.en||u.id}" (${u.id}) is already countersigned by ${f.map(m=>`"${m.id}"`).join(", ")} \u2014 a contract has one countersignature.`}))}return r},"validate")};var lL={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 Kt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Kt,"isRecord");var gv=["field","join","literal","address","payment","contract"],j4=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),B4=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function tr(e){return typeof e=="string"&&e.trim().length>0}s(tr,"nonEmptyString");function gm(e,n,t,r,i="value"){if(!Kt(e)||!Kt(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=gv.filter(c=>c in o);if(a.length!==1){r.push({path:n,code:"mappingShape",message:{de:`${n}: \`from\` nennt genau eine Quelle (${gv.join(" | ")}).`,en:`${n}: \`from\` names exactly one source (${gv.join(" | ")}).`}});return}let[l]=a;l==="field"&&!tr(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(tr))&&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)||tr(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"&&pr(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&&!j4.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&&!(tr(e.lookup)&&Kt(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"||Kt(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||Kt(d)&&B4.has(String(d.address))||r.push({path:n,code:"mappingShape",message:{de:`${n}: unbekannte Auswahl \`pick\`.`,en:`${n}: unknown selection \`pick\`.`}}))}s(gm,"checkMapping");function Vi(e,n,t,r,i){if(!Kt(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=lL[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))gm(l,`${n}.${a}`,r,i)}s(Vi,"checkBody");function dL(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(!Kt(o)||!tr(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),gm(o.value,`${l}.value`,t,r),o.unless!==void 0&&gm(o.unless,`${l}.unless`,t,r,"condition")})}s(dL,"checkAif");function yv(e){let n=[];if(!Kt(e))return[{path:"engage",code:"missing",message:{de:"Die Engage-Zuordnung `engage` fehlt.",en:"The Engage mapping `engage` is missing."}}];let t=Kt(e.lookups)?e.lookups:{};Kt(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))(!Kt(i)||!Object.values(i).every(tr))&&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(tr(e.addressFormatId)||n.push({path:"engage.addressFormatId",code:"missing",message:{de:"`engage.addressFormatId` fehlt (GetAddressMappingInfo).",en:"`engage.addressFormatId` is missing (GetAddressMappingInfo)."}}),Vi(e.pupil,"engage.pupil","addPupil",t,n),Vi(e.admission,"engage.admission","addAdmissionDetails",t,n),e.nationality!==void 0&&Vi(e.nationality,"engage.nationality","addNationality",t,n),e.visa!==void 0&&Vi(e.visa,"engage.visa","addVisa",t,n),e.medical!==void 0&&Vi(e.medical,"engage.medical","addMedical",t,n),dL(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(!Kt(i)||!tr(i.key)||!tr(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),Vi(i.basic,`${a}.basic`,"addContact",t,n),i.address!==void 0&&Vi(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,f)=>Vi(u,`${a}.${l}[${f}]`,d,t,n))}}dL(i.aif,`${a}.aif`,t,n),i.linkAddressToPupilIf!==void 0&&gm(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,t,n,"condition")})}if(e.siblingsAttending!==void 0){let r=e.siblingsAttending;(!Kt(r)||!tr(r.repeated)||!tr(r.field)||!tr(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(yv,"engagePushConfigIssues");function*wv(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(wv,"mappingsOf");function cL(e){let n=new Set(e.contacts.map(t=>t.presentIf));for(let{mapping:t,contactKey:r}of wv(e))for(let i of U4(t.from))n.add(V4(i,r));return[...n]}s(cL,"configFieldKeys");function U4(e){return"field"in e?[e.field]:"join"in e?e.join:[]}s(U4,"formFieldsOf");function V4(e,n){return e.startsWith(".")?(n===void 0&&F(`[engagePush] relative field "${e}" outside a contact`),`${n}${e}`):e}s(V4,"resolveFieldKey");function uL(e,n){for(let{mapping:t}of wv(e))if(n in t.from)return!0;return!1}s(uL,"configReadsSource");function fL(e){let n=new Set;for(let{mapping:t}of wv(e))"address"in t.from&&n.add(t.from.address.key);return[...n]}s(fL,"configEnvLeaves");var pL="done",mL=["sandbox","production"];var ym="engagePush",rPe=660*1e3;function Gi(e,n,t,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.${n}`,reason:t,severity:r}}s(Gi,"issue");function kv(e,n){let t=e.inputs?.[n];return t?.kind==="literal"?t.value:void 0}s(kv,"literal");function hL(e){return yv(e.engage).length===0?e.engage:null}s(hL,"validConfig");function G4(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(G4,"bypassingPath");var gL={role:"system-action",effect:"side-effect",outcomes:[{id:pL,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:s(e=>{let n=hL(e);return n===null?[]:fL(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=kv(e,"target");mL.includes(a)||o.push(Gi(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=kv(e,"contractFields");l!==void 0&&l!=="off"&&l!=="on"&&o.push(Gi(e,"inputs.contractFields",{de:`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`,en:`[engagePush/contractFields] "${i}": contract fields are off or on.`}));let d=e.assign?.[ym];(typeof d!="string"||d.length===0)&&o.push(Gi(e,"assign",{de:`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${ym}\` nennt das Team.`,en:`[engagePush/assign] "${i}": nobody is set to check a stalled transfer \u2014 \`assign.${ym}\` names the team.`}));for(let g of yv(e.engage))o.push(Gi(e,g.path,{de:`[engagePush/config] \u201E${r}": ${g.message.de}`,en:`[engagePush/config] "${i}": ${g.message.en}`}));let c=n.nodes.filter(g=>g.id!==e.id&&g.type==="engagePush"&&kv(g,"target")===a);c.length>0&&o.push(Gi(e,"inputs.target",{de:`[engagePush/twice] \u201E${r}": ${c.map(g=>`"${g.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`,en:`[engagePush/twice] "${i}": ${c.map(g=>`"${g.id}"`).join(", ")} already transfers to the same target.`})),G4(n,e.id)&&o.push(Gi(e,"next",{de:`[engagePush/bypassed] \u201E${r}": ein Weg erreicht ein \u201Eangenommen"-Ende, ohne durch die Engage-\xDCbertragung zu laufen \u2014 was dort angenommen wird, k\xE4me nie in Engage an.`,en:`[engagePush/bypassed] "${i}": a path reaches an "accepted" end without passing through the Engage transfer \u2014 what is accepted there would never reach Engage.`}));let u=hL(e),f=e;for(let[g,b,A,$]of[["contract","contract","Vertrag","Contract"],["payment","payment","Zahlung","Payment"]])u===null||!uL(u,g)||f[b]!==void 0||o.push(Gi(e,b,{de:Ns("address/missing",{where:`\u201E${r}\u201C \u203A ${A}`},"de"),en:Ns("address/missing",{where:`"${i}" \u203A ${$}`},"en")}));let m=f.form,y=we(m)&&m.scope==="node"?m.owner:void 0,k=y===void 0?void 0:t?.readinessFormFieldsByFormNode?.get(y);if(u!==null&&k!==void 0){let g=new Set(k.keys()),b=cL(u).filter(A=>!g.has(A)&&!/\[\d+\]\./.test(A));if(b.length>0){let A=n.nodes.find($=>$.id===y);o.push(Gi(e,"engage",{de:`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${A?.label?.de??y}" nicht \u2014 sie werden nicht \xFCbertragen: ${b.join(", ")}.`,en:`[engagePush/unmappedField] "${i}": the form "${A?.label?.en||y}" does not know these fields \u2014 they are not transferred: ${b.join(", ")}.`},"warning"))}}return o},"validate")};var Uo={join:$D,end:EO,roleAssign:ID,eventTrigger:OD,waitlist:zD,completenessCheck:eF,form:LD,setFlag:MD,if:qD,decision:Do,review:tF,collectPayment:lF,governedDocument:HF,countersign:aL,engagePush:gL};TI(Uo);function yL(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(yL,"graphOf");function wL(e){let n=new Map;for(let t of e.nodes)for(let r of Dr(e,t))n.set(se(r.address),r.nodeId);return n}s(wL,"producedOf");function kL(e){let n=new Map;for(let t of e.nodes)n.set(t.id,new Set(bo(e,t).map(r=>se(r.address))));return n}s(kL,"readsOf");function bL(e,n){let t=yL(e,"bundle"),r=yL(n.graph,"live head"),i=wL(t),o=wL(r),a={added:[],removed:[],moved:[]};for(let[u,f]of i){let m=o.get(u);m===void 0?a.added.push({address:u,nodeId:f}):m!==f&&a.moved.push({address:u,from:m,to:f})}for(let[u,f]of o)i.has(u)||a.removed.push({address:u,nodeId:f});let l=kL(t),d=kL(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let f=l.get(u)??new Set,m=d.get(u)??new Set,y=[...f].filter(g=>!m.has(g)),k=[...m].filter(g=>!f.has(g));(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(bL,"planAddresses");function vL(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(vL,"addressPlanRows");function xL(e,n){return n==null?!0:Pe(e)!==Pe(n)}s(xL,"changed");async function SL(e,n,t){if(n.index.module!==Pb.name)throw new Error(`offer: unknown module "${n.index.module}"`);return K_(e,n,t,{afterManifestPublish:s(async()=>{if(n.index.links?.unitKey||n.index.program)return Pb.scaffold(e,n.index.slugs.manifest,n.index,{dryRun:t.dryRun??!1})},"afterManifestPublish")})}s(SL,"applyOffer");async function AL(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(AL,"exportOffer");async function bv(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 g=i?await e.query(x.forms.getSmartFormBySlug,{client:t.tenant,offerVersionId:i.offerVersionId,slug:y}):null;a[y]=g?.def?xL(k,{label:g.def.label,...g.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=xL(k&&{graph:ks(n.workflow.graph),progressLayout:n.workflow.progressLayout??k.progressLayout,progressWiring:n.workflow.progressWiring??k.progressWiring},k&&{graph:ks(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=bL(n.workflow.graph,y))}}let c=t.program?.stages,u=c===void 0?[]:i?await Ob(e,t.tenant,t.slugs.manifest,c):Up(null,[],c),f=await Yp(e,t.tenant,i?t.slugs.manifest:null,t),m=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:f,publishPending:m?.draftDiffersFromExternal??null,draftRevision:m?.draftRevision??null,externalHeadRevision:m?.externalHeadRevision??null}}s(bv,"diffOffer");function wm(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(wm,"contractProductionModeOf");function EL(e){return wm(e)==="resolver"}s(EL,"isResolverCarrierNode");function km(e){return(e.workflow?.graph?.nodes??[]).flatMap(t=>{let r=ei(t);return!EL(t)||r===null?[]:[{node:t,key:r.key,kind:r.kind,...r.revision===void 0?{}:{revision:r.revision}}]})}s(km,"authoredPins");var TL={type:"address",dataType:"composite"};var $L={type:"boolean",dataType:"boolean"};var RL={type:"consent",dataType:"boolean"};var IL={type:"date",dataType:"date"};var OL={type:"docRef",dataType:"file"};var PL={type:"email",dataType:"text"};var _L={type:"enum",dataType:"option"};var NL={type:"string",dataType:"text"};var CL={type:"tel",dataType:"text"};var bm={address:TL.dataType,boolean:$L.dataType,consent:RL.dataType,date:IL.dataType,docRef:OL.dataType,email:PL.dataType,enum:_L.dataType,string:NL.dataType,tel:CL.dataType};function vv(e){return{type:e.type,multiple:e.multiple===!0,enumListKey:e.enumListKey,enumOptions:e.enumOptions}}s(vv,"shapeOf");function DL(e){let n=new Map,t=[],r=s(o=>{o.fields.forEach(a=>n.set(a.key,vv(a))),o.groups?.forEach(a=>a.fields.forEach(l=>n.set(l.key,vv(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}`,vv(l))),i.push({pathPrefix:`repeated '${o.key}'.`,effects:o.effects,shapes:a})}return i}s(DL,"fieldMapScopes");function z4(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(z4,"computedKeysOf");function FL(e){let n=[],t=z4(e);for(let r of DL(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(FL,"validateFieldMapSources");function LL(e){let n=[],t=new Set;for(let o of DL(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(LL,"validateFieldPersistence");var W4="$";function Y4(e){return typeof e=="string"&&e.startsWith(W4)}s(Y4,"isRef");function vm(e){return e.slice(1)}s(vm,"stripRef");function*H4(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(H4,"refSlots");function J4(e){let n=new Set;for(let t of H4(e))Y4(t)&&n.add(vm(t));return[...n]}s(J4,"collectRefs");function Q4(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 J4(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=vm(o.from);for(let l of e)l.id===o.id||!(l.kind==="fieldMap"&&vm(l.target)===a||l.kind==="shareValue"&&vm(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(Q4,"buildAdjacency");function ML(e){let{refsOf:n}=Q4(e),r=Yf(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(ML,"detectCycle");function qL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(qL,"escapeRegExp");function zi(e){return new RegExp(`^${qL(e)}\\[(\\d+)\\]\\.(.+)$`)}s(zi,"repeatedRowKeyPattern");function xv(e,n){let t=zi(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(xv,"countRepeatedRows");function KL(e,n,t){let r=zi(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(KL,"repeatedRowHasData");function jL(e){return e.endsWith(".count")?e.slice(0,-6):e}s(jL,"readKeyOf");function Sv(e){return{sections:e,fields:[]}}s(Sv,"hiddenSectionsOnly");function BL(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??[])BL(r,n,t)}s(BL,"collectKeys");function UL(e){let n=[],t=s(r=>{if(r.visibleTo!==void 0){let i=new Set,o=new Set;BL(r,i,o),n.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:o,rowKeyPatterns:[...o].map(zi)});return}for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(UL,"restrictedSectionsOf");function VL(e,n){return n.fieldKeys.has(e)||n.repeatedKeys.has(e)?!0:n.rowKeyPatterns.some(t=>t.test(e))}s(VL,"matchesKey");function Z4(e,n){return n.find(t=>VL(e,t))??null}s(Z4,"hiddenSectionOfKey");function X4(e,n){for(let t=e;;){if(VL(t,n))return!0;let r=t.lastIndexOf(".");if(r===-1)return!1;t=t.slice(0,r)}}s(X4,"fieldOwnsKey");function e3(e,n){return n.find(t=>X4(e,t))??null}s(e3,"restrictedFieldOfKey");function n3(e,n){let t=Z4(e,n.sections);if(t!==null)return{kind:"section",section:t};let r=e3(e,n.fields);return r===null?null:{kind:"field",field:r}}s(n3,"hiddenOwnerOfKey");function xm(e,n){return n3(e,n)!==null}s(xm,"isKeyHidden");function t3(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(t3,"visibleToListIssues");function GL(e,n,t){let r=[],i=s((c,u,f)=>{let m=c.visibleTo;m!==void 0&&r.push(...t3(c.id,m,`${u}.visibleTo`,f,t));let y=f||m!==void 0;if(y){let k=[...c.fields,...(c.groups??[]).flatMap(g=>g.fields),...(c.repeated??[]).flatMap(g=>g.itemTemplate)];for(let g of k)g.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:{de:`Feld '${g.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`,en:`Field '${g.key}' is carried into the person record and therefore cannot sit in a section with restricted visibility (visibleTo).`}})}(c.subsections??[]).forEach((k,g)=>i(k,`${u}.subsections[${g}]`,y))},"visitRaw");e.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let o=UL(e);if(o.length===0)return r;let a=s((c,u,f)=>{if(c===void 0)return;let m=Sv(f);for(let y of bn(c)){let k=jL(y);(xm(y,m)||xm(k,m))&&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,f)=>{a(c.visibleIf,`${u}.visibleIf`,f),a(c.requiredIf,`${u}.requiredIf`,f),a(c.disabledIf,`${u}.disabledIf`,f),a(c.defaultValue,`${u}.defaultValue`,f),c.sameAs!==void 0&&xm(c.sameAs.source,Sv(f))&&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,f)=>{let m=c.visibleTo!==void 0?c.id:f,y=o.filter(k=>k.sectionId!==m);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?o:y),c.fields.forEach((k,g)=>l(k,`${u}.fields[${g}]`,y)),c.groups?.forEach((k,g)=>{a(k.visibleIf,`${u}.groups[${g}].visibleIf`,y),k.fields.forEach((b,A)=>l(b,`${u}.groups[${g}].fields[${A}]`,y))}),c.repeated?.forEach((k,g)=>{a(k.itemVisibleIf,`${u}.repeated[${g}].itemVisibleIf`,y),k.itemTemplate.forEach((b,A)=>l(b,`${u}.repeated[${g}].itemTemplate[${A}]`,y))}),c.computed?.forEach((k,g)=>a(k.expression,`${u}.computed[${g}]`,y)),c.subsections?.forEach((k,g)=>d(k,`${u}.subsections[${g}]`,m))},"visitCompiled");return n.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}s(GL,"sectionVisibilityIssues");var Vr="#";var zL=s(e=>{let n=Hw.find(t=>t.systemColumn===e);return n===void 0&&F(`[personName] no system field backs ${e}`),n.key},"keyOfColumn"),br={firstName:zL("persons.firstName"),lastName:zL("persons.lastName")};function WL(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===br.firstName?t.firstName.push(o):a===br.lastName&&t.lastName.push(o);return t}s(WL,"personNameKeys");function YL(e){return[...e.firstName,...e.lastName]}s(YL,"personNameKeyList");function HL(e){return e.firstName.length>0||e.lastName.length>0}s(HL,"hasPersonName");function ma(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 ma(i.subsections??[],a,i.id))r.push(l)}),r}s(ma,"walkSections");function r3(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(r3,"findFieldInSection");function JL(e,n){for(let t of ma(e.sections)){let r=r3(t.section,n);if(r)return{section:t.section,field:r}}return null}s(JL,"findField");var i3=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],o3=["blue","rose","amber","violet","teal","emerald","slate"];function QL(e){return i3.includes(e)}s(QL,"isBucketIconName");function ZL(e){return o3.includes(e)}s(ZL,"isBucketColorName");var s3="__clear__";function XL(e){return e===""?"empty":e===s3?"reserved":null}s(XL,"selectOptionValueDefect");var nNe=Object.freeze({});function a3(e,n){return Object.freeze(Uf(Zr,e,n))}s(a3,"formContextEntries");function e0(e){return e.env??[]}s(e0,"declaredContextKeys");function n0(e,n){return e0(e).every(t=>t0(t,n?.[t]))}s(n0,"scenarioContextComplete");function t0(e,n){return iP(Zr,e,n)}s(t0,"contextValueComplete");function r0(e,n){return a3(n??{},e0(e))}s(r0,"scenarioContextEntries");function Ev(e){return _l(e)}s(Ev,"isContextIdentifier");function l3(e,n,t){let r=Bf(Zr,e);if(r!==null)return{severity:"error",path:t,code:"env/unknownKey",message:r.message};let[,i=""]=e.split(".");return n.has(i)?null:{severity:"error",path:t,code:"env/undeclared",message:{de:`'${e}' liest den Umgebungsschl\xFCssel '${i}', den das Formular nicht in \`env\` deklariert.`,en:`'${e}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}}s(l3,"contextIdentifierIssue");var Av=nf("stage.key");function d3(e){let n=[],t=s(i=>i.kind==="ident"&&i.path===Av,"isStageKey"),r=s(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(t(i.left)&&i.right.kind==="str"&&n.push(i.right.value),t(i.right)&&i.left.kind==="str"&&n.push(i.left.value)),i.op==="in"&&t(i.left)&&i.right.kind==="arr")for(let o of i.right.items)o.kind==="str"&&n.push(o.value);r(i.left),r(i.right);return;case"unary":r(i.operand);return;case"if":r(i.cond),r(i.then),r(i.else);return;case"call":i.args.forEach(r);return;case"arr":i.items.forEach(r);return;default:return}},"walk");return r(e),n}s(d3,"stageKeyLiterals");function i0(e,n,t){return n===void 0?[]:d3(e).filter(r=>!n.has(r)).map(r=>s0(r,n,t))}s(i0,"stageKeyAstIssues");function o0(e,n){if(n===void 0)return[];let t=[];for(let r of e.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!n.has(i.key)&&t.push(s0(i.key,n,`scenario:${r.id}/env`))}return t}s(o0,"scenarioStageKeyIssues");function s0(e,n,t){let r=[...n].sort();return{severity:"error",path:t,code:"env/unknownStageKey",message:{de:`'${e}' ist kein Stufenschl\xFCssel des Programms dieses Angebots \u2014 `+(r.length>0?`bekannt: ${r.join(", ")}.`:"das Angebot hat kein Programm mit Stufen.")+` \`${Av}\` ist der Bundle-Schl\xFCssel (\`program.stages[].key\`), nie das gespeicherte \`<program>-stufe-<key>\`.`,en:`'${e}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${Av}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}}s(s0,"unknownStageKeyIssue");function a0(e,n,t){let r=[];for(let i of bn(e)){if(!Ev(i))continue;let o=l3(i,n,t);o!==null&&r.push(o)}if(r.length>0)return r;for(let{identifier:i,op:o}of Zy(e,Xu))r.push({severity:"error",path:t,code:"env/unguardedNullable",message:{de:`'${o}' \xFCber '${i}', das bei manchen Bewerbungen leer ist, braucht davor eine Absicherung '${i} != null &&' \u2014 lege fest, was ein leerer Wert bedeutet.`,en:`'${o}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`}});return r}s(a0,"contextAstIssues");function l0(e,n){let t=[...c3(e)],r=new Set(e.env??[]);for(let i of e.env??[]){if(!ws(i)){t.push({severity:"error",path:"env",code:"env/unknownKey",message:{de:`Der deklarierte Umgebungsschl\xFCssel '${i}' geh\xF6rt nicht zum Vokabular (${ys.join(", ")}).`,en:`Declared environment key '${i}' is not in the vocabulary (${ys.join(", ")}).`}});continue}n!==void 0&&!n.has(i)&&t.push({severity:"error",path:"env",code:"env/unsupplied",message:{de:`Das Formular deklariert den Umgebungsschl\xFCssel '${i}', aber sein Host liefert ihn nicht.`,en:`The form declares environment key '${i}', but its host does not supply it.`}})}for(let i of e.testScenarios??[]){let o=[...r].filter(a=>ws(a)&&!t0(a,i.env?.[a]));o.length>0&&t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:{de:`Szenario '${i.id}' belegt den deklarierten Umgebungsschl\xFCssel ${o.map(a=>`'${a}'`).join(", ")} nicht vollst\xE4ndig \u2014 eine echte Bewerbung tr\xE4gt immer jedes seiner Felder (ein leeres als null).`,en:`Scenario '${i.id}' does not sample the declared environment key(s) ${o.map(a=>`'${a}'`).join(", ")} completely \u2014 a real application always carries every field of them (an empty one as null).`}});for(let a of Object.keys(i.env??{}))ws(a)?r.has(a)||t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:{de:`Szenario '${i.id}' belegt den Umgebungsschl\xFCssel '${a}', den das Formular nicht deklariert.`,en:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}}):t.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:{de:`Szenario '${i.id}' belegt den unbekannten Umgebungsschl\xFCssel '${a}'.`,en:`Scenario '${i.id}' samples unknown environment key '${a}'.`}})}return t}s(l0,"formContextIssues");function c3(e){let n=[];Object.hasOwn(e,"context")&&n.push({severity:"error",path:"context",code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Formular deklariert die gelesene Umgebung als `env`.",en:"`context` is retired \u2014 a form declares the environment it reads as `env`."}});let t=e.testScenarios;for(let r of Array.isArray(t)?t:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&n.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:{de:"`context` ist abgeschafft \u2014 ein Szenario belegt die Umgebung als `env`.",en:"`context` is retired \u2014 a scenario samples the environment as `env`."}});return n}s(c3,"retiredContextFields");var Tv=UN.docRef.allowedMime;function m0(e,n={}){let t=Js(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 f(P,_){if(i.has(P))return;i.add(P);let q=o.get(P.id);q&&q!==P?r.push({severity:"error",path:`sections[${_.join(".")}]`,code:"duplicate.section-id",message:{de:`Abschnitts-ID '${P.id}' ist mehrfach deklariert.`,en:`Section id '${P.id}' is declared more than once.`}}):o.set(P.id,P);let C=`sections[${_.join(".")}]`;P.fields.forEach((G,ae)=>{ha(a,G.key,`${C}.fields[${ae}]`,"duplicate.field-key",r),l.add(G.key),u.set(G.key,G),c.set(G.key,Rv(G)),G.externalFlag&&(G.type!=="boolean"&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"flag.not-boolean",message:{de:`Externes Flag '${G.key}' muss den Typ 'boolean' haben (ist '${G.type}').`,en:`External flag '${G.key}' must be type 'boolean' (got '${G.type}').`}}),G.reviewRequired!==void 0&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"review.on-flag",message:{de:`Externes Flag '${G.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 '${G.key}' is marked as requiring review \u2014 the process sets a flag, the family hands in nothing anyone could review.`}}),G.notice!==void 0&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"config.notice-on-flag",message:{de:`Externes Flag '${G.key}' tr\xE4gt einen Hinweis (notice) \u2014 ein Flag wird der Familie nie angezeigt, also auch sein Hinweis nicht.`,en:`External flag '${G.key}' carries a notice \u2014 a flag is never shown to the family, so neither is its notice.`}}),G.defaultValue==null&&r.push({severity:"error",path:`${C}.fields[${ae}]`,code:"flag.missing-default",message:{de:`Externes Flag '${G.key}' muss einen defaultValue deklarieren (z. B. "false"), damit es standardm\xE4\xDFig verborgen ist.`,en:`External flag '${G.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`}})),r.push(...c0(G,`${C}.fields[${ae}]`)),r.push(...d0(G,`${C}.fields[${ae}]`))}),P.groups?.forEach((G,ae)=>{G.fields.forEach((de,Ne)=>{ha(a,de.key,`${C}.groups[${ae}].fields[${Ne}]`,"duplicate.field-key",r),l.add(de.key),u.set(de.key,de),c.set(de.key,Rv(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.groups[${ae}].fields[${Ne}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${de.key}' muss ein direktes Abschnittsfeld sein, kein Gruppenfeld.`,en:`External flag '${de.key}' must be a direct section field, not a group field.`}}),r.push(...c0(de,`${C}.groups[${ae}].fields[${Ne}]`)),r.push(...d0(de,`${C}.groups[${ae}].fields[${Ne}]`))})}),P.repeated?.forEach((G,ae)=>{G.itemTemplate.forEach((de,Ne)=>{ha(a,de.key,`${C}.repeated[${ae}].itemTemplate[${Ne}]`,"duplicate.field-key",r),c.set(de.key,Rv(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"flag.invalid-location",message:{de:`Externes Flag '${de.key}' muss ein direktes Abschnittsfeld sein, kein Feld einer Wiederholung.`,en:`External flag '${de.key}' must be a direct section field, not a repeated item field.`}}),de.export&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"export.in-repeated",message:{de:`Feld '${de.key}' deklariert export in einem itemTemplate einer Wiederholung \u2014 ein zusammengesetztes Blatt gilt je Bewerbung, ein Zeilenfeld je Zeile.`,en:`Field '${de.key}' declares export inside a repeated itemTemplate \u2014 a compound leaf is per-application, a row field is per-row.`}}),de.sameAs&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.sameas-in-repeated",message:{de:`Feld '${de.key}' deklariert sameAs in einem itemTemplate einer Wiederholung \u2014 nicht unterst\xFCtzt.`,en:`Field '${de.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}}),de.reviewRequired!==void 0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"review.in-repeated",message:{de:`Feld '${de.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 '${de.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.`}}),de.notice!==void 0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.notice-in-repeated",message:{de:`Feld '${de.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 '${de.key}' carries a notice inside a repeated itemTemplate \u2014 it is not shown there. Put the notice on the section.`}}),de.type==="docRef"&&de.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${C}.repeated[${ae}].itemTemplate[${Ne}]`,code:"config.docref-multiple-in-repeated",message:{de:`Feld '${de.key}' setzt docRefConstraints.multiple in einem itemTemplate einer Wiederholung \u2014 ein Mehrfach-Upload ist nur als Abschnitts- oder Gruppenfeld m\xF6glich.`,en:`Field '${de.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`}})})}),P.computed?.forEach(G=>{d.add(G.key),ha(a,G.key,`${C}.computed[${G.key}]`,"duplicate.field-key",r),G.exportType==="consent"&&r.push({severity:"error",path:`${C}.computed[${G.key}]`,code:"config.consent-computed",message:{de:`Berechnetes Feld '${G.key}' ist als Zustimmung (consent) typisiert \u2014 eine Zustimmung gibt die Person selbst, keine Berechnung. exportType 'boolean' verwenden.`,en:`Computed '${G.key}' is typed as a consent \u2014 a consent is given by the person, never computed. Use exportType 'boolean'.`}}),G.export===!0&&G.exportType===void 0&&r.push({severity:"error",path:`${C}.computed[${G.key}]`,code:"export.computed-untyped",message:{de:`Berechnetes Feld '${G.key}' wird ohne exportType exportiert \u2014 string | number | boolean | date angeben.`,en:`Computed '${G.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`}})}),P.subsections?.forEach((G,ae)=>f(G,[..._,ae]))}s(f,"visitRawSection"),e.sections.forEach((P,_)=>f(P,[_]));let m=new Set;t.effects.forEach((P,_)=>{ha(m,P.id,`effects[${_}]`,"duplicate.effect-id",r)});let y=new Set;t.outcomes.forEach((P,_)=>{ha(y,P.id,`outcomes[${_}]`,"duplicate.outcome-id",r)}),t.outcomes.forEach((P,_)=>{P.output.effectRefs?.forEach((q,C)=>{m.has(q.effect)||r.push({severity:"error",path:`outcomes[${_}].output.effectRefs[${C}]`,code:"ref.unknown-effect",message:{de:`Ergebnis '${P.id}' verweist auf den unbekannten Effekt '${q.effect}'.`,en:`Outcome '${P.id}' references unknown effect '${q.effect}'.`}})})}),t.outcomes.forEach((P,_)=>{P.output.fields?.forEach((q,C)=>{JL(t,q.path)||r.push({severity:"error",path:`outcomes[${_}].output.fields[${C}]`,code:"ref.unknown-field",message:{de:`Ergebnis '${P.id}' verweist auf das unbekannte Feld '${q.path}'.`,en:`Outcome '${P.id}' references unknown field '${q.path}'.`}})})});let k=new Set;for(let P of ma(t.sections))for(let _ of P.section.repeated??[])k.add(`${_.key}.count`);for(let P of k)(a.has(P)||d.has(P))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:{de:`'${P}' ist zugleich ein deklarierter Schl\xFCssel und die abgeleitete Zeilenzahl einer Wiederholung \u2014 der abgeleitete Wert w\xFCrde stillschweigend gewinnen.`,en:`'${P}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`}});let g={known:new Set([...a,...d,...k]),declaredContext:new Set(e.env??[]),stageKeys:n.stageKeys};r.push(...l0(e)),r.push(...GL(e,t,n.visibleToKeys)),r.push(...o0(e,n.stageKeys));for(let P of ma(t.sections)){let _=P.section,q=`sections[${P.path.join(".")}]`;_.visibleIf&&(vr(_.visibleIf,`${q}.visibleIf`,g,!1,r),ga(_.visibleIf,`${q}.visibleIf`,c,r)),_.fields.forEach((C,G)=>$v(C,`${q}.fields[${G}]`,g,!1,c,r)),_.groups?.forEach((C,G)=>{C.visibleIf&&(vr(C.visibleIf,`${q}.groups[${G}].visibleIf`,g,!1,r),ga(C.visibleIf,`${q}.groups[${G}].visibleIf`,c,r)),C.fields.forEach((ae,de)=>$v(ae,`${q}.groups[${G}].fields[${de}]`,g,!1,c,r))}),_.repeated?.forEach((C,G)=>{C.itemVisibleIf&&(vr(C.itemVisibleIf,`${q}.repeated[${G}].itemVisibleIf`,g,!0,r),ga(C.itemVisibleIf,`${q}.repeated[${G}].itemVisibleIf`,c,r)),C.itemTemplate.forEach((ae,de)=>$v(ae,`${q}.repeated[${G}].itemTemplate[${de}]`,g,!0,c,r)),C.effects?.forEach((ae,de)=>{ae.when&&vr(ae.when,`${q}.repeated[${G}].effects[${de}].when`,g,!0,r)})}),_.computed?.forEach((C,G)=>vr(C.expression,`${q}.computed[${G}].expression`,g,!1,r))}t.effects.forEach((P,_)=>{P.when&&vr(P.when,`effects[${_}].when`,g,!1,r)}),t.outcomes.forEach((P,_)=>{vr(P.when,`outcomes[${_}].when`,g,!1,r)});let b=new Set(t.outcomes.map(P=>P.id));function A(P,_){P.requiredFor&&P.requiredFor.forEach((q,C)=>{b.has(q)||r.push({severity:"error",path:`${_}.requiredFor[${C}]`,code:"ref.unknown-required-for-outcome",message:{de:`Feld "${P.key}": requiredFor verweist auf das unbekannte Ergebnis "${q}"`,en:`field "${P.key}": requiredFor references unknown outcome "${q}"`}})})}s(A,"checkRequiredFor");for(let P of ma(t.sections)){let _=P.section,q=`sections[${P.path.join(".")}]`;_.fields.forEach((C,G)=>A(C,`${q}.fields[${G}]`)),_.groups?.forEach((C,G)=>{C.fields.forEach((ae,de)=>A(ae,`${q}.groups[${G}].fields[${de}]`))}),_.repeated?.forEach((C,G)=>{C.itemTemplate.forEach((ae,de)=>A(ae,`${q}.repeated[${G}].itemTemplate[${de}]`))})}function $(P,_){let q=s((C,G)=>{let ae=(C.type==="docRef"?C.docRefConstraints?.mimeType??[]:[]).filter(Ae=>!Tv.includes(Ae));ae.length>0&&r.push({severity:"error",path:G,code:"config.docref-type-outside-ceiling",message:{de:`Feld '${C.key}' erlaubt ${ae.map(Ae=>`'${Ae}'`).join(", ")} \u2014 kein Dokument-Upload akzeptiert diesen Typ (erlaubt: ${Tv.join(", ")}).`,en:`Field '${C.key}' allows ${ae.map(Ae=>`'${Ae}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${Tv.join(", ")}).`}});let de=C.type==="docRef"?C.docRefConstraints?.minFiles:void 0;if(de!==void 0){let Ae=C.docRefConstraints?.multiple===!0,pn=typeof de=="number"&&Number.isInteger(de)&&de>=2;(!Ae||!pn)&&r.push({severity:"error",path:G,code:"config.docref-min-files",message:Ae?{de:`Feld '${C.key}' setzt docRefConstraints.minFiles auf ${JSON.stringify(de)} \u2014 erlaubt ist eine ganze Zahl ab 2.`,en:`Field '${C.key}' sets docRefConstraints.minFiles to ${JSON.stringify(de)} \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:G,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:G,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:G,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(...f3(C,G)),typeof C.minSelections=="number"&&typeof C.maxSelections=="number"&&C.minSelections>C.maxSelections&&r.push({severity:"error",path:G,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}).`}});let Ne=C.enumRef;Ne!==void 0&&r.push({severity:"error",path:`${G}.enumRef`,code:"config.enum-ref-retired",message:{de:`Feld '${C.key}' nennt den entfernten Options-Katalog (enumRef '${String(Ne)}'). 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(Ne)}'). Author the options in the form (enumOptions + enumOptionLabels) or bind a tenant list (enumListKey).`}}),(C.enumOptions??[]).forEach((Ae,pn)=>{let Je=XL(Ae);Je!==null&&r.push({severity:"error",path:`${G}.enumOptions[${pn}]`,code:"config.enum-option-value",message:{de:Je==="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 '${Ae}', den die Einzelauswahl f\xFCr ihre Zeile zum Leeren reserviert. Die Option umbenennen.`,en:Je==="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 '${Ae}', which the single select reserves for its clear row. Rename the option.`}})}),(C.attachments??[]).forEach((Ae,pn)=>{if("storageId"in Ae){r.push({severity:"error",path:`${G}.attachments[${pn}]`,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 Je=Ae.fileKey!==void 0&&Ae.fileKey!=="",xn=Ae.url!==void 0&&Ae.url!=="";Je===xn&&r.push({severity:"error",path:`${G}.attachments[${pn}]`,code:"config.attachment-source",message:{de:`Anhang des Felds '${C.key}' muss genau eines von 'fileKey' oder 'url' setzen (hat ${Je&&xn?"beide":"keines"}).`,en:`Field '${C.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${Je&&xn?"both":"neither"}).`}}),Ae.renderAs==="inlineLink"&&Ae.label===void 0&&r.push({severity:"error",path:`${G}.attachments[${pn}]`,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");P.fields.forEach((C,G)=>q(C,`${_}.fields[${G}]`)),P.groups?.forEach((C,G)=>{C.fields.forEach((ae,de)=>q(ae,`${_}.groups[${G}].fields[${de}]`))}),P.repeated?.forEach((C,G)=>{C.itemTemplate.forEach((ae,de)=>{let Ne=`${_}.repeated[${G}].itemTemplate[${de}]`;q(ae,Ne),ae.type==="consent"&&r.push({severity:"error",path:Ne,code:"config.consent-in-repeated",message:{de:`Feld '${ae.key}' ist eine Zustimmung in einem Wiederholungsblock \u2014 Zustimmungen stehen nur als Feld eines Abschnitts oder einer Gruppe.`,en:`Field '${ae.key}' is a consent inside a repeated block \u2014 a consent stands only as a field of a section or a group.`}})})}),P.subsections?.forEach((C,G)=>$(C,`${_}.subsections[${G}]`))}s($,"visitFieldConfig"),e.sections.forEach((P,_)=>$(P,`sections[${_}]`)),e.effects.forEach((P,_)=>{if(P.kind==="person"){r.push(...p0(P,e.effects,`effects[${_}]`,q=>l.has(q)));return}P.kind==="organization"&&P.nameFrom?.forEach((q,C)=>{l.has(q)||r.push({severity:"error",path:`effects[${_}].nameFrom[${C}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${P.id}': nameFrom verweist auf das unbekannte Feld '${q}'.`,en:`Effect '${P.id}' nameFrom references unknown field '${q}'.`}})})});let O=s((P,_)=>{if(P.kind!=="person"&&P.kind!=="organization")return;let q=P.display;if(!q){r.push({severity:"error",path:`${_}.display`,code:"display.missing",message:{de:`Effekt '${P.id}' deklariert einen Partei-Bucket, aber kein display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`,en:`Effect '${P.id}' declares a party bucket but no display \u2014 the party's title, icon and accent colour could not be resolved.`}});return}QL(q.icon)||r.push({severity:"error",path:`${_}.display.icon`,code:"display.unknown-icon",message:{de:`Effekt '${P.id}': display.icon '${q.icon}' ist kein bekanntes Bucket-Icon.`,en:`Effect '${P.id}' display.icon '${q.icon}' is not a known bucket icon.`}}),ZL(q.color)||r.push({severity:"error",path:`${_}.display.color`,code:"display.unknown-color",message:{de:`Effekt '${P.id}': display.color '${q.color}' ist keine bekannte Bucket-Farbe.`,en:`Effect '${P.id}' display.color '${q.color}' is not a known bucket colour.`}})},"checkBucketDisplay");e.effects.forEach((P,_)=>O(P,`effects[${_}]`));let E=new Set,I=s(P=>{P.kind==="person"?E.add(P.bucket):P.kind==="organization"&&E.add(P.id.replace(/^o\./,""))},"declareBucket");e.effects.forEach(I);let v=new Set,R=s(P=>{for(let _ of P)_.repeated?.forEach(q=>q.effects?.forEach(C=>I(C))),R(_.subsections??[])},"collectRepeatedBuckets");R(e.sections);let K=s((P,_)=>{E.size!==0&&P.forEach((q,C)=>{q.bucket===void 0||E.has(q.bucket)||r.push({severity:"error",path:`${_}[${C}].bucket`,code:"bucket.undeclared",message:{de:`Feld '${q.key}' geh\xF6rt zum Bucket '${q.bucket}', aber kein Person-/Organisations-Effekt deklariert ihn \u2014 das Feld geh\xF6rt zu keiner Partei.`,en:`Field '${q.key}' belongs to bucket '${q.bucket}', but no person/organization effect declares it \u2014 the field belongs to no party.`}})})},"checkFieldBuckets"),N=s((P,_)=>{if(v.has(P))return;v.add(P);let q=`sections[${_.join(".")}]`;K(P.fields,`${q}.fields`),P.groups?.forEach((C,G)=>K(C.fields,`${q}.groups[${G}].fields`)),P.repeated?.forEach((C,G)=>K(C.itemTemplate,`${q}.repeated[${G}].itemTemplate`)),P.subsections?.forEach((C,G)=>N(C,[..._,G]))},"visitBucketSection");e.sections.forEach((P,_)=>N(P,[_]));let Y=e.effects.flatMap((P,_)=>P.kind==="person"&&P.subject===!0?[{e:P,i:_}]:[]);Y.length>1&&Y.slice(1).forEach(({e:P,i:_})=>{r.push({severity:"error",path:`effects[${_}].subject`,code:"subject.duplicate",message:{de:`Effekt '${P.id}' deklariert subject:true, aber '${Y[0].e.id}' tut es bereits. Genau ein Bucket darf das Subjekt der Bewerbung sein.`,en:`Effect '${P.id}' declares subject:true, but '${Y[0].e.id}' already does. Exactly one bucket may be the application subject.`}})}),e.effects.forEach((P,_)=>{if(!(P.kind!=="person"||P.nationalityFrom===void 0)){if(P.subject!==!0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${P.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 '${P.id}' declares nationalityFrom but is not the application subject \u2014 nationality is read only for the application subject.`}});return}if(P.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.empty",message:{de:`Effekt '${P.id}' deklariert ein leeres nationalityFrom \u2014 weglassen oder mindestens ein Feld nennen.`,en:`Effect '${P.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`}});return}P.nationalityFrom.forEach((q,C)=>{l.has(q)||r.push({severity:"error",path:`effects[${_}].nationalityFrom[${C}]`,code:"nationality.unknown-field",message:{de:`Effekt '${P.id}': nationalityFrom verweist auf das unbekannte Feld '${q}'.`,en:`Effect '${P.id}' nationalityFrom references unknown field '${q}'.`}})})}});let H=e.effects.flatMap((P,_)=>P.kind==="person"&&P.contractParty!==void 0?[{e:P,i:_,decl:P.contractParty}]:[]);if(H.length>0){let P=new Map;H.forEach(({e:q,i:C})=>{let G=P.get(q.bucket);if(G===void 0){P.set(q.bucket,q.id);return}r.push({severity:"error",path:`effects[${C}].contractParty`,code:"contractParty.duplicate-bucket",message:{de:`Effekt '${q.id}' deklariert eine Vertragspartei auf Bucket '${q.bucket}', aber '${G}' tut es bereits. Ein Bucket ist h\xF6chstens eine Vertragspartei.`,en:`Effect '${q.id}' declares a contract party on bucket '${q.bucket}', but '${G}' already does. A bucket is at most one contract party.`}})});let _=H.filter(({decl:q})=>q.role==="beneficiary");_.slice(1).forEach(({e:q,i:C})=>{r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:{de:`Effekt '${q.id}' deklariert contractParty.role 'beneficiary', aber '${_[0].e.id}' tut es bereits. Genau ein Bucket darf Leistungsempf\xE4nger sein.`,en:`Effect '${q.id}' declares contractParty.role 'beneficiary', but '${_[0].e.id}' already does. Exactly one bucket may be the beneficiary.`}})}),_.forEach(({e:q,i:C})=>{q.subject!==!0&&r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:{de:`Effekt '${q.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 '${q.id}' setzen.`,en:`Effect '${q.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 '${q.id}'.`}})}),Y.forEach(({e:q,i:C})=>{let G=q.contractParty?.role;G!==void 0&&G!=="beneficiary"&&r.push({severity:"error",path:`effects[${C}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:{de:`Effekt '${q.id}' ist das Subjekt der Bewerbung, deklariert aber contractParty.role '${G}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`,en:`Effect '${q.id}' is the application subject but declares contractParty.role '${G}'. The application subject is the contract beneficiary.`}})}),H.some(({decl:q})=>q.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((P,_)=>{P.kind==="fieldMap"&&P.mappings.forEach((q,C)=>{a.has(q.from)||r.push({severity:"error",path:`effects[${_}].mappings[${C}].from`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${P.id}': fieldMap from '${q.from}' verweist auf ein unbekanntes Feld.`,en:`Effect '${P.id}' fieldMap from '${q.from}' references unknown field.`}})})});for(let[P,_]of u){if(!_.sameAs)continue;let q=`fields[${P}].sameAs`,C=u.get(_.sameAs.source);C===void 0||_.sameAs.source===P?r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:_.sameAs.source===P?`Feld '${P}': sameAs.source verweist auf sich selbst.`:`Feld '${P}': sameAs.source verweist auf das unbekannte Feld '${_.sameAs.source}' (muss ein Abschnitts- oder Gruppenfeld sein).`,en:_.sameAs.source===P?`Field '${P}' sameAs.source references itself.`:`Field '${P}' sameAs.source references unknown field '${_.sameAs.source}' (must be a top-level or group field).`}}):C.type!==_.type?r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}' (${_.type}): sameAs.source '${_.sameAs.source}' hat einen anderen Typ (${C.type}) \u2014 die Spiegelung muss formgleich sein.`,en:`Field '${P}' (${_.type}) sameAs.source '${_.sameAs.source}' has a different type (${C.type}) \u2014 the mirror must be shape-identical.`}}):C.sameAs&&r.push({severity:"error",path:`${q}.source`,code:"ref.unknown-sameas-source",message:{de:`Feld '${P}': sameAs.source '${_.sameAs.source}' deklariert selbst sameAs \u2014 Spiegelketten werden nicht unterst\xFCtzt.`,en:`Field '${P}' sameAs.source '${_.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`}});let G=u.get(_.sameAs.toggle);(G===void 0||G.type!=="boolean")&&r.push({severity:"error",path:`${q}.toggle`,code:"ref.unknown-sameas-toggle",message:{de:G===void 0?`Feld '${P}': sameAs.toggle verweist auf das unbekannte Feld '${_.sameAs.toggle}'.`:`Feld '${P}': sameAs.toggle '${_.sameAs.toggle}' muss den Typ 'boolean' haben (ist '${G.type}').`,en:G===void 0?`Field '${P}' sameAs.toggle references unknown field '${_.sameAs.toggle}'.`:`Field '${P}' sameAs.toggle '${_.sameAs.toggle}' must be type 'boolean' (got '${G.type}').`}}),_.required===!0&&r.push({severity:"error",path:`fields[${P}].required`,code:"config.sameas-static-required",message:{de:`Feld '${P}' 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: "${_.sameAs.toggle} != true" verwenden.`,en:`Field '${P}' 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: "${_.sameAs.toggle} != true".`}})}{let P=new Map;e.effects.forEach(_=>P.set(_.id,_.kind)),e.effects.forEach((_,q)=>{if(_.kind!=="shareValue")return;[["from",_.from],["to",_.to]].forEach(([ae,de])=>{let Ne=P.get(de.slice(1));Ne!==void 0&&Ne!=="person"&&Ne!=="organization"&&r.push({severity:"error",path:`effects[${q}].${ae}`,code:"ref.sharevalue-endpoint",message:{de:`Effekt '${_.id}': shareValue ${ae} '${de}' muss auf einen Person-/Organisations-Effekt verweisen (ist '${Ne}').`,en:`Effect '${_.id}' shareValue ${ae} '${de}' must reference a person/organization effect (got '${Ne}').`}})});let C=_.from.slice(1);e.effects.some(ae=>ae.kind==="fieldMap"&&ae.target.slice(1)===C&&ae.mappings.some(de=>de.to===_.field)||ae.kind==="shareValue"&&ae.id!==_.id&&ae.to.slice(1)===C&&ae.field===_.field)||r.push({severity:"error",path:`effects[${q}].field`,code:"config.sharevalue-missing-source-map",message:{de:`Effekt '${_.id}' teilt das Feld '${_.field}' aus '${_.from}', aber kein fieldMap mit Ziel '${_.from}' bildet auf '${_.field}' ab (und kein shareValue verkn\xFCpft es) \u2014 der Quellwert k\xF6nnte beim Commit nie existieren.`,en:`Effect '${_.id}' shares field '${_.field}' from '${_.from}', but no fieldMap targeting '${_.from}' maps to '${_.field}' (and no shareValue links it in) \u2014 the source value could never exist at commit time.`}})})}e.effects.forEach((P,_)=>{P.kind==="person"&&P.bucket.includes(Vr)&&r.push({severity:"error",path:`effects[${_}].bucket`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': bucket '${P.bucket}' darf '${Vr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' bucket '${P.bucket}' must not contain '${Vr}' (reserved for the per-row namespace).`}}),P.kind==="organization"&&P.orgKind.includes(Vr)&&r.push({severity:"error",path:`effects[${_}].orgKind`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${P.id}': orgKind '${P.orgKind}' darf '${Vr}' nicht enthalten (f\xFCr den Zeilen-Namensraum reserviert).`,en:`Effect '${P.id}' orgKind '${P.orgKind}' must not contain '${Vr}' (reserved for the per-row namespace).`}})});let ue=new Set;function Q(P,_){P.repeated?.forEach((q,C)=>{let G=q.effects??[];if(G.length>0){let ae=`${_}.repeated[${C}]`,de=new Set(G.map(ie=>ie.id)),Ne=new Set(q.itemTemplate.map(ie=>ie.key)),Ae=(q.uniqueBy?.length??0)>0,pn=s(ie=>ie.startsWith("$item.")?Ne.has(ie.slice(6)):l.has(ie),"resolvesName"),Je=s(ie=>ie.startsWith("$item.")?Ne.has(ie.slice(6)):a.has(ie),"resolvesFrom"),xn=s(ie=>{let Ln=ie.slice(1);return de.has(Ln)||m.has(Ln)},"resolvesRef");G.forEach((ie,Ln)=>{let mn=`${ae}.effects[${Ln}]`;if(m.has(ie.id)||ue.has(ie.id)?r.push({severity:"error",path:mn,code:"duplicate.repeated-effect-id",message:{de:`Der Effekt '${ie.id}' der Wiederholung ist mehrfach deklariert.`,en:`Repeated effect id '${ie.id}' is declared more than once.`}}):ue.add(ie.id),ie.kind==="person"||ie.kind==="organization"){O(ie,mn),ie.kind==="person"&&ie.subject===!0&&r.push({severity:"error",path:`${mn}.subject`,code:"subject.in-repeated",message:{de:`Effekt '${ie.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 '${ie.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.`}}),ie.kind==="person"&&ie.nationalityFrom!==void 0&&r.push({severity:"error",path:`${mn}.nationalityFrom`,code:"nationality.not-subject",message:{de:`Effekt '${ie.id}' der Wiederholung deklariert nationalityFrom \u2014 nur das Subjekt der Bewerbung (ein Effekt der obersten Ebene) tr\xE4gt es.`,en:`Repeated effect '${ie.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}}),ie.kind==="person"&&ie.contractParty!==void 0&&r.push({severity:"error",path:`${mn}.contractParty`,code:"contractParty.in-repeated",message:{de:`Effekt '${ie.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 '${ie.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}}),Ae||r.push({severity:"error",path:ae,code:"config.repeated-effect-requires-uniqueBy",message:{de:`Wiederholung '${q.key}' hat einen Parteien erzeugenden Effekt '${ie.id}', aber kein 'uniqueBy' \u2014 Parteien je Zeile brauchen einen stabilen Identit\xE4tsschl\xFCssel.`,en:`Repeated def '${q.key}' has a party-creating effect '${ie.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`}});let Ce=ie.kind==="person"?ie.bucket:ie.orgKind;Ce.includes(Vr)&&r.push({severity:"error",path:`${mn}.${ie.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:{de:`Effekt '${ie.id}' der Wiederholung: ${ie.kind==="person"?"bucket":"orgKind"} '${Ce}' darf '${Vr}' nicht enthalten.`,en:`Repeated effect '${ie.id}' ${ie.kind==="person"?"bucket":"orgKind"} '${Ce}' must not contain '${Vr}'.`}}),ie.kind==="person"&&r.push(...p0(ie,G,mn,pn)),ie.kind==="organization"&&ie.nameFrom?.forEach((Ve,Ot)=>{pn(Ve)||r.push({severity:"error",path:`${mn}.nameFrom[${Ot}]`,code:"ref.unknown-name-field",message:{de:`Effekt '${ie.id}' der Wiederholung: nameFrom verweist auf das unbekannte Feld '${Ve}'.`,en:`Repeated effect '${ie.id}' nameFrom references unknown field '${Ve}'.`}})}),ie.identity?.strategy==="keyed"&&ie.identity.keyFrom.forEach((Ve,Ot)=>{Je(Ve)||r.push({severity:"error",path:`${mn}.identity.keyFrom[${Ot}]`,code:"ref.unknown-fieldmap-from",message:{de:`Effekt '${ie.id}' der Wiederholung: identity.keyFrom verweist auf das unbekannte Feld '${Ve}'.`,en:`Repeated effect '${ie.id}' identity.keyFrom references unknown field '${Ve}'.`}})})}else if(ie.kind==="relationship"){if([["from",ie.from],["to",ie.to]].forEach(([Ce,Ve])=>{xn(Ve)||r.push({severity:"error",path:`${mn}.${Ce}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: ${Ce} verweist auf den unbekannten Effekt '${Ve}'.`,en:`Repeated relationship '${ie.id}' ${Ce} references unknown effect '${Ve}'.`}})}),ie.meta)for(let[Ce,Ve]of Object.entries(ie.meta))typeof Ve=="string"&&Ve.startsWith("$")&&!xn(Ve)&&r.push({severity:"error",path:`${mn}.meta.${Ce}`,code:"ref.unknown-repeated-effect",message:{de:`Beziehung '${ie.id}' der Wiederholung: meta.${Ce} verweist auf den unbekannten Effekt '${Ve}'.`,en:`Repeated relationship '${ie.id}' meta.${Ce} references unknown effect '${Ve}'.`}})}else ie.kind==="fieldMap"?(xn(ie.target)||r.push({severity:"error",path:`${mn}.target`,code:"ref.unknown-repeated-effect",message:{de:`fieldMap '${ie.id}' der Wiederholung: Ziel verweist auf den unbekannten Effekt '${ie.target}'.`,en:`Repeated fieldMap '${ie.id}' target references unknown effect '${ie.target}'.`}}),ie.mappings.forEach((Ce,Ve)=>{Je(Ce.from)||r.push({severity:"error",path:`${mn}.mappings[${Ve}].from`,code:"ref.unknown-fieldmap-from",message:{de:`fieldMap '${ie.id}' der Wiederholung: from '${Ce.from}' verweist auf ein unbekanntes Feld.`,en:`Repeated fieldMap '${ie.id}' from '${Ce.from}' references unknown field.`}})})):ie.kind==="shareValue"&&r.push({severity:"error",path:mn,code:"config.sharevalue-in-repeated",message:{de:`Effekt '${ie.id}' der Wiederholung: shareValue wird in Effekten von Wiederholungszeilen nicht unterst\xFCtzt.`,en:`Repeated effect '${ie.id}': shareValue is not supported inside repeated row effects.`}})})}}),P.subsections?.forEach((q,C)=>Q(q,`${_}.subsections[${C}]`))}s(Q,"visitRepeatedEffects"),e.sections.forEach((P,_)=>Q(P,`sections[${_}]`));let oe=ML(t.effects);return oe.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:{de:`Der Effektgraph enth\xE4lt einen Zyklus: ${oe.cycle?.join(" \u2192 ")??"?"}`,en:`Effect graph contains a cycle: ${oe.cycle?.join(" \u2192 ")??"?"}`}}),r.push(...u3(e)),r}s(m0,"validateForm");function u3(e){let n={...e,effects:e.effects.map(h0),sections:e.sections.map(g0),testScenarios:e.testScenarios?.map(t=>({id:t.id,label:t.label,description:t.description}))};return Zf(n,"form").map(t=>({severity:"error",path:t.path,code:"i18n.missing-translation",message:sw(t)}))}s(u3,"missingTranslationIssues");function h0(e){if(!("subject"in e))return e;let{subject:n,...t}=e;return t}s(h0,"withoutSubjectFlag");function g0(e){return{...e,repeated:e.repeated?.map(n=>({...n,effects:n.effects?.map(h0)})),subsections:e.subsections?.map(g0)}}s(g0,"withoutRowSubjectFlags");function d0(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(d0,"reviewRequiredShapeIssues");function c0(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(c0,"exportGateIssues");function ha(e,n,t,r,i){e.has(n)?i.push({severity:"error",path:t,code:r,message:{de:`Mehrfach vergeben: ${u0(r,"de")} '${n}'`,en:`Duplicate ${u0(r,"en")}: '${n}'`}}):e.add(n)}s(ha,"reportIfDup");function u0(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(u0,"labelForCode");function $v(e,n,t,r,i,o){e.visibleIf&&(vr(e.visibleIf,`${n}.visibleIf`,t,r,o),ga(e.visibleIf,`${n}.visibleIf`,i,o)),e.requiredIf&&(vr(e.requiredIf,`${n}.requiredIf`,t,r,o),ga(e.requiredIf,`${n}.requiredIf`,i,o)),e.disabledIf&&(vr(e.disabledIf,`${n}.disabledIf`,t,r,o),ga(e.disabledIf,`${n}.disabledIf`,i,o)),e.defaultValue&&vr(e.defaultValue,`${n}.defaultValue`,t,r,o)}s($v,"checkFieldAsts");function Rv(e){return{hasDefault:e.defaultValue!=null,isBoolean:e.type==="boolean",isYesNo:e.type==="boolean"&&e.presentation==="yesNo",isConsent:e.type==="consent"}}s(Rv,"gatingMeta");function ga(e,n,t,r){function i(o){switch(o.kind){case"binary":{(o.op==="=="||o.op==="!=")&&(f0(o.left,o.right,o.op,n,t,r),f0(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(ga,"checkGatingExpr");function f0(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(f0,"inspectEqualityOperand");function vr(e,n,t,r,i){i.push(...a0(e,t.declaredContext,n)),i.push(...i0(e,t.stageKeys,n));for(let o of bn(e))t.known.has(o)||Ev(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(vr,"checkAst");function p0(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 ${br.firstName} / ${br.lastName}. nameFrom entfernen.`,en:`Effect '${e.id}': a person has no nameFrom any more \u2014 its name is the fieldMap onto ${br.firstName} / ${br.lastName}. Remove nameFrom.`}});let o=WL(e.id,n);HL(o)||i.push({severity:"error",path:t,code:"person.without-name-mapping",message:{de:`Effekt '${e.id}': keine Feldzuordnung (fieldMap) auf ${br.firstName} oder ${br.lastName} \u2014 die Person bek\xE4me keinen Namen.`,en:`Effect '${e.id}': no fieldMap onto ${br.firstName} or ${br.lastName} \u2014 the person would get no name.`}});for(let a of YL(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(p0,"personNameIssues");function f3(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(f3,"consentConfigIssues");var p3="blocked";function y0(e,n){let t={values:n};for(let r of e.outcomes){let i;try{i=yn(r.when,t)}catch(o){F(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(m3(i))return r.id===p3?null:r.id}return null}s(y0,"resolveActiveOutcome");function m3(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(m3,"truthy");function w0(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}s(w0,"isScalar");function h3(e,n,t){for(let[r,i]of Object.entries(e))if(i!==void 0){if(w0(i)){n[r]=i;continue}if(Array.isArray(i)){n[r]=i;continue}for(let[o,a]of Object.entries(i))w0(a)&&(n[`${r}.${o}`]=a)}g3(e,n,t)}s(h3,"mergeRecord");function g3(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);zi(a).test(i)&&r.add(a)}for(let i of r){let o=xv(e,i),a=0;for(let l=0;l<o;l++)KL(e,i,l)&&a++;n[`${i}.count`]=a}}s(g3,"mergeRepeatedCounts");function k0(e,n,t){let r={...t};return h3(e,r,n),r}s(k0,"flattenValues");function Iv(e,n,t){return{code:e,fieldKey:n,text:t}}s(Iv,"submitIssue");function b0(e){return!(e==null||e===!1||e===0||e===""||Array.isArray(e)&&e.length===0)}s(b0,"truthyEval");function v0(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(v0,"isEmptyValue");function y3(e,n,t){let r=!!e.required;if(!r&&e.requiredIf)try{r=b0(yn(e.requiredIf,{values:n}))}catch{r=!1}return r?e.requiredFor?t===null?!1:e.requiredFor.includes(t):!0:!1}s(y3,"fieldIsLiveRequired");function w3(e,n,t){return x0(e,n,t).evalCtx}s(w3,"buildSubmitEvalContext");function x0(e,n,t){let r=k3(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=S0(e,l,t),c=new Set,u=new Set;E0(e,d,y=>c.add(y.key),y=>u.add(y.key));let f=new Set(i.filter(y=>{let k=r(y);return k.kind==="field"?c.has(y):u.has(k.repeatedKey)}));if(f.size===o.size&&[...f].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 m=[...f].sort().join("\0");if(a.has(m)){let y=i.filter(k=>f.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(m),o=f}}s(x0,"splitWithContext");function k3(e){let n=new Map,t=[];for(let r of Am(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:zi(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(k3,"fieldOwnership");function S0(e,n,t){let r=[];for(let o of Am(e.sections))for(let a of o.repeated??[])r.push(a.key);let i=k0(n,r,t);for(let o of Am(e.sections))for(let a of o.computed??[])try{i[a.key]=yn(a.expression,{values:i})}catch{}return i}s(S0,"rawEvalContext");function A0(e,n,t){let{values:r,defaulted:i}=b3(e,n,t),o=x0(e,r,t),a={};for(let[l,d]of Object.entries(o.hidden))i.has(l)||(a[l]=d);return{...o,hidden:a}}s(A0,"splitDraftValues");function b3(e,n,t,r){let i={...n},o=new Set,a=null;for(let l of Am(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??=S0(e,n,t);let c;try{c=yn(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(b3,"applyFieldDefaults");function Am(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(Am,"walkSectionsDeep");function v3(e,n,t,r=!1){if(v0(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(v3,"fieldFormatIssue");function x3(e,n){return v0(n)||e.type==="consent"&&n!==!0}s(x3,"isUnanswered");function Sm(e,n){if(!e)return!0;try{return b0(yn(e,{values:n}))}catch{return!1}}s(Sm,"isVisibleUnder");function E0(e,n,t,r){let i=s(o=>{if(Sm(o.visibleIf,n)){for(let a of o.fields)Sm(a.visibleIf,n)&&t(a);for(let a of o.groups??[])if(Sm(a.visibleIf,n))for(let l of a.fields)Sm(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(E0,"forEachVisibleField");function T0(e,n,t,r={}){let i=w3(e,n,t),o=[],a=y0(e,i);a===null&&r.requireOutcome!==!1&&o.push(Iv("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 E0(e,i,d=>{let c=n[d.key];if(x3(d,c)){!l.has(d.type)&&y3(d,i,a)&&o.push(Iv("required",d.key,ol([d.label],([f],m)=>m==="de"?`${f} ist ein Pflichtfeld.`:`${f} is a required field.`)));return}if(!r.registry)return;let u=v3(d,c,r.registry,r.testMode===!0);u!==null&&o.push(Iv("format",d.key,u))}),{issues:o,activeOutcome:a,evalCtx:i,submittable:o.length===0}}s(T0,"checkSubmittable");function $0(e){let n=e.testScenarios??[];if(n.length===0)return[];let{compiled:t}=Js(e),r=[];for(let i of n){let o=i.prefill??{};if(!n0(e,i.env))continue;let a=r0(e,i.env),{visible:l}=A0(t,o,a),d=T0(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:ol([i.label,c.text],([u,f],m)=>m==="de"?`Szenario "${u}": ${f}`:`Scenario "${u}": ${f}`)})}}return r}s($0,"validateScenarios");function Em(e){return e.filter(n=>(n.severity??"error")==="error")}s(Em,"blockingIssues");function Tm(e,n={}){return[...m0(e,n),...$0(e)]}s(Tm,"runFormValidators");function $m(e){return Em(e)}s($m,"blockingFormErrors");function R0(e,n,t){return h_(e,n,t)}s(R0,"runWorkflowValidators");function I0(e){return Em(e)}s(I0,"blockingWorkflowErrors");var S3=["artifacts","assign","inputs","library","next","notifications","optionalActions","outcomes","outputLabels","sublabel","tasks"],O0={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"]},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"]}},pt={id:w.string(),label:sa,artifacts:w.optional(w.any()),assign:w.optional(w.any()),inputs:w.optional(w.any()),library:w.optional(w.any()),next:w.optional(w.any()),notifications:w.optional(w.any()),optionalActions:w.optional(w.any()),outcomes:w.optional(w.any()),outputLabels:w.optional(w.any()),sublabel:w.optional(w.any()),tasks:w.optional(w.any())},A3=w.object({...pt,type:w.literal("join")}),E3=w.object({...pt,type:w.literal("end")}),T3=w.object({...pt,type:w.literal("eventTrigger")}),$3=w.object({...pt,type:w.literal("form"),adoptForm:w.optional(w.any()),formExports:w.optional(w.any())}),R3=w.object({...pt,type:w.literal("roleAssign")}),I3=w.object({...pt,type:w.literal("setFlag")}),O3=w.object({...pt,type:w.literal("if"),condition:w.optional(w.any())}),P3=w.object({...pt,type:w.literal("countersign"),contract:w.optional(w.any()),signing:w.optional(w.any()),titles:w.optional(w.any())}),_3=w.object({...pt,type:w.literal("engagePush"),contract:w.optional(w.any()),engage:w.optional(w.any()),form:w.optional(w.any()),payment:w.optional(w.any())}),N3=w.object({...pt,type:w.literal("decision"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),reads:w.optional(w.any()),requiresOneOf:w.optional(w.any())}),C3=w.object({...pt,type:w.literal("review"),commentRequired:w.optional(w.any()),decisionAsTask:w.optional(w.any()),form:w.optional(w.any())}),D3=w.object({...pt,type:w.literal("waitlist")}),F3=w.object({...pt,type:w.literal("completenessCheck"),deadline:w.optional(w.any()),requires:w.optional(w.any())}),L3=w.object({...pt,type:w.literal("collectPayment")}),M3=w.object({...pt,type:w.literal("governedDocument"),approval:w.optional(w.any()),confirmBeforeIssue:w.optional(w.any()),confirmContractTerms:w.optional(w.any()),contractTermsQuestionText:w.optional(w.any()),form:w.optional(w.any()),generatorStamp:w.optional(w.any()),production:w.optional(w.any()),reads:w.optional(w.any()),responseLabels:w.optional(w.any()),responseStrategy:w.optional(w.any()),templateStamp:w.optional(w.any()),titles:w.optional(w.any())}),aCe=w.union(A3,E3,T3,$3,R3,I3,O3,P3,_3,N3,C3,D3,F3,L3,M3);function P0(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 O0)){n.push(`${o}: unknown node type ${JSON.stringify(a)}`);return}let l=O0[a],d=new Set(["id","type","label",...S3,...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(P0,"workflowNodeEnvelopeIssues");function _0(e,n){return e.enumOptionLabels?.[n]??{de:n,en:n}}s(_0,"inlineEnumOptionLabel");var C0={string:"string",boolean:"boolean",consent:"boolean",date:"date",enum:"enum",email:"email",tel:"tel",address:"address"};function D0(e){return C0[e]!==void 0}s(D0,"isExportableFieldType");function q3(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(q3,"leafForComputed");function N0(e){let n=C0[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:_0(e,t)}))}:{}}}s(N0,"leafFor");function Ov(e){let n=[],t=s(r=>{for(let i of r.fields)i.export===!0&&n.push(N0(i));for(let i of r.groups??[])for(let o of i.fields)o.export===!0&&n.push(N0(o));for(let i of r.computed??[])i.export===!0&&n.push(q3(i));for(let i of r.subsections??[])t(i)},"visit");for(let r of e.sections)t(r);return n}s(Ov,"exportedFormLeaves");var F0=s(e=>e,"asEffectId"),Wi=s(e=>e,"asOutcomeId"),ya=s(e=>e,"asSectionId"),ot=s(e=>e,"asFieldKey");var xr=["string","boolean","consent","date","enum","email","tel","address","docRef"],Pd=["person","organization","relationship","fieldMap"],Yi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],wa=["fresh","keyed","manual"];function Vo(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 un(e,n,t,r)}s(Vo,"optionalLocalizedText");function Jn(e,n){if(!(e===void 0||e===""))try{Un(e)}catch(t){throw new Error(`offer form: ${n} is not a valid expression: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}s(Jn,"assertExpression");function _d(e){return Object.keys(e.smartforms??{})}s(_d,"carriedFormSlugs");function Pv(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(Pv,"boundFormSlugs");function Rm(e,n){let t=_d(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(Rm,"resolveFormSlug");function Im(e,n){let t=e.smartforms?.[n];if(!t)throw new Error(`offer form: smartform "${n}" not found in bundle`);return t}s(Im,"getForm");function jt(e){let n=[],t=s(r=>{n.push(r),r.subsections?.forEach(i=>t(i))},"visit");return e.sections.forEach(t),n}s(jt,"walkSections");function rr(e,n){return jt(e).find(t=>t.id===n)}s(rr,"findSection");function Go(e,n){for(let t of jt(e)){let r=t.fields.findIndex(i=>i.key===n);if(r>=0)return{section:t,field:t.fields[r],index:r}}}s(Go,"findField");function zo(e){let n=new Set;for(let t of jt(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(zo,"allFieldKeys");function K3(e){let n=un(e.label,e.labelEn,"offer form add"),t={id:ya("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},r={id:Wi("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{label:n,sections:[t],effects:[],outcomes:[r]}}s(K3,"buildSkeletonSmartForm");function Om(e,n){let{key:t,label:r}=n;if(_d(e).includes(t))throw new Error(`offer form add: smartform "${t}" already exists in this bundle`);let i=K3({key:t,label:r,...n.labelEn?{labelEn:n.labelEn}:{}});e.smartforms={...e.smartforms??{},[t]:i},e.index.smartforms={...e.index.smartforms??{},[t]:{}}}s(Om,"addForm");function L0(e,n){if(!_d(e).includes(n))throw new Error(`offer form rm: smartform "${n}" not found in bundle`);if(Pv(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(L0,"removeForm");function M0(e,n){let t=Im(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");wn(t,"label",{de:n.label,en:n.labelEn},"offer form set")}s(M0,"setForm");function q0(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(q0,"nodesOf");function K0(e,n,t){let r=q0(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(K0,"nodeOf");function j0(e){return e.flatMap(n=>{if(n.type!=="form"||vt(n))return[];let t=n.inputs?.smartForm;return t?.kind==="literal"&&typeof t.value=="string"&&t.value!==""?[{node:n,slug:t.value}]:[]})}s(j0,"creatingFormNodes");function B0(e){return $m(Tm(e)).map(n=>`[${n.code??"form"}] ${n.path?`${n.path}: `:""}${n.message.de}`)}s(B0,"formErrors");function Pm(e){let n="offer workflow restamp-exports",t=q0(e,n),r=[];for(let{node:i,slug:o}of j0(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=B0(l);if(d.length>0)throw new Error(`${n}: smartform "${o}" is refused by the publish gate \u2014 fix it first:
10812
10817
  ${d.join(`
10813
- `)}`);let c=Ov(l),u=Array.isArray(i.formExports)?i.formExports.map(m=>m.key):null,f=i.formExports===void 0||Pe(i.formExports)!==Pe(c);i.formExports=c,r.push({node:i.id,form:o,before:u,after:c.map(m=>m.key),changed:f})}for(let i of t)if(i.type==="form"&&vt(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(Pm,"restampFormExports");function U0(e){let n=e.workflow?.graph?.nodes??[];return j0(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 B0(o).length>0?[]:Pe(t.formExports)===Pe(Ov(o))?[]:[{node:t.id,form:r}]})}s(U0,"staleFormExports");var _v=["string","number","boolean","date"];function V0(e,n){let t="offer form field export";for(let r of jt(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&&!D0(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 (${_v.join("|")}); an expression has none to infer`);if(!_v.includes(d))throw new Error(`${t}: --type "${d}" is no computed export type (${_v.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(V0,"setFieldExport");function G0(e,n,t){let r="offer workflow node set-generator",i=K0(e,n,r);if(wm(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=ei(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??{},[Kn]:{kind:"literal",value:{kind:t.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(f=>f!==Kn&&f!==qt);return{before:l,after:{key:a,kind:t.kind},droppedStamp:c,keptParameterCells:u}}s(G0,"setGeneratorPin");function z0(e,n,t){let r="offer workflow node set-cockpit-fields",i=K0(e,n,r),o=wm(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"?ei(i)!==null:mr(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 u of t){if(l.has(u))throw new Error(`${r}: --fields names "${u}" twice`);l.add(u)}let d={...i.inputs??{}},c=Object.keys(d).filter(u=>d[u]?.kind==="cockpit");for(let u of t){let f=d[u]?.kind;if(f!==void 0&&f!=="cockpit"&&f!=="unset")throw new Error(`${r}: "${u}" holds a ${String(f)} \u2014 a parameter has one source; remove it first (offer workflow node set-input --clear)`)}for(let u of c)l.has(u)||delete d[u];for(let u of t)d[u]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...t]}}s(z0,"setCockpitFields");var j5=new Set(["graph","progressLayout","progressWiring"]);function W0(e){let{label:n,...t}=e;return t}s(W0,"definitionOf");function B5(e){let n=[];for(let o of Object.keys(e))j5.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(BR.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(...P0(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(B5,"workflowShapeIssues");function Y0(e){let n=e.nodes??[],t=new Map;for(let r of n){let i=DI(r);i!==void 0&&t.set(r.id,i)}return t}s(Y0,"formNodeSlugById");function U5(e,n){let t=e.smartforms??{},r=new Map;for(let[i,o]of Y0(n)){let a=t[o];if(a===void 0)return;r.set(i,W0(a))}return qP(r)}s(U5,"readinessContext");function V5(e){return[...Y0(e).values()]}s(V5,"formNodeSlugs");function _m(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(_m,"describe");function Rt(e){let n=[];for(let l of of(e.manifest))n.push({severity:"error",area:"manifest",message:l});let t=Rn(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 Bp(e.index.program?.stages??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of Gp(e.index.program?.runs??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of zp(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 b of B5(e.workflow))n.push({severity:"error",area:"workflow",message:b});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let b of jR(d))n.push({severity:"error",area:"workflow",message:b});let u=[];for(let{node:b,key:A,kind:$}of km(e))b.generatorStamp?.schemaDigest===void 0&&(u.push(b.id),n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${b.id}" pinnt ${$}:${A} 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 b of l.nodes)b.type!=="governedDocument"||b.production!=="template"||b.templateStamp!==void 0||n.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${b.id}" f\xFCllt die Vorlage ${mr(b)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:b,form:A}of U0(e))n.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${b}": der Stempel formExports passt nicht mehr zum Formular "${A}" \u2014 die Adresspr\xFCfung liest den alten Stand; \`offer workflow restamp-exports\` stempelt ihn neu (publish tut es ohnehin).`});let f=U5(e,l),m=s(b=>{let A=R0(b,{layout:d,wiring:c},f),$=new Set(I0(A));return{issues:A,isError:s(O=>$.has(O)||(O.severity??"error")==="error","isError")}},"blockingOf"),{issues:y,isError:k}=m(l),g=new Set;if(u.length>0){let b=structuredClone(l);for(let E of b.nodes)u.includes(E.id)&&(E.generatorStamp={...E.generatorStamp??{},parts:[{partKey:"?"}]});let A=m(b),$=new Set(A.issues.filter(A.isError).map(_m)),O=s(E=>u.some(I=>E.includes(`$node.${I}.contract`)),"namesOutput");for(let E of y){let I=_m(E);k(E)&&!$.has(I)&&O(I)&&g.add(I)}}for(let b of y){let A=_m(b);if(g.has(A)){n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${A}`});continue}n.push({severity:k(b)?"error":"warning",area:"workflow",message:A})}}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=Rn(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=W0(d);for(let k of UR(u,`smartforms/${l}.json`))n.push({severity:"error",area:"smartform",message:k.de});let f=u,m=Tm(f,{stageKeys:a}),y=new Set($m(m));for(let k of m)n.push({severity:y.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${_m(k)}`});for(let k of[...LL(f),...FL(f)])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(V5(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(Rt,"validateBundle");async function Nv(e,n,t){let r=km(t);if(r.length===0)return{rows:[],issues:[]};let i=[...new Map(r.map(({key:c,kind:u,revision:f})=>[`${u}:${c}:${f??"current"}`,{key:c,kind:u,...f===void 0?{}:{revision:f}}])).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:f,revision:m}of r){let y=a.get(`${f}:${u}:${m??"current"}`);if(y===void 0)throw new Error(`offer: the environment answered no stamp for ${f}:${u}`);if(y.stamp===null){if(y.refusal===null)throw new Error(`offer: the environment answered neither a stamp nor a refusal for ${f}:${u}`);d.push({severity:"error",area:"workflow",message:`[resolver/pinRefused] Knoten "${c.id}": ${y.refusal.de}`});continue}KR(c,structuredClone(y.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:y.stamp.parts===void 0?`${f}:${u} Dokument`:`${f}:${u} kombiniert (${y.stamp.parts.map(k=>k.partKey).join(", ")})`})}return{rows:l,issues:d}}s(Nv,"stampResolverPins");async function Cv(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=mr(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=mr(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(kF(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(Cv,"stampTemplatePins");async function H0(e,n,t){let r=je(t),i=await Nv(e,n,r),o=await Cv(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");Tt(r);let d=a.map(f=>f.target.slice(6)),c=s(f=>d.some(m=>f.includes(`nodes.${m}.`)||f.includes(`node.${m}.`)||f.includes(`"${m}"`)),"onStamped"),u=Rt(r).filter(f=>f.severity==="error"&&c(f.message));return{rows:a,refused:[],open:u}}s(H0,"restampPinsOnDisk");var G5=z.join("contract","resolver-setup.json"),pi="resolver setup",ka=s((e,n)=>_n(e,n,pi),"record"),Hi=s((e,n)=>Ge(e,n,pi),"text");function z5(e,n){let t=ka(e,"Datei"),r=ka(t.contractTemplate,"contractTemplate"),i=ka(t.resolver,"resolver");return{dir:n,contractTemplate:{key:Hi(r.key,"contractTemplate.key"),name:ut(r.name,"contractTemplate.name",pi,"Vorlagennamen"),file:Hi(r.file,"contractTemplate.file"),role:Hi(r.role,"contractTemplate.role")},revenueAccounts:cp(t.revenueAccounts,pi),billingItems:up(t.billingItems,pi),resolver:{key:Hi(i.key,"resolver.key"),name:ut(i.name,"resolver.name",pi,"Generatornamen"),description:i.description===void 0?null:ut(i.description,"resolver.description",pi,"Beschreibungen"),legalText:i.legalText??{},source:Hi(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Ct(i.feeGroups,"resolver.feeGroups",pi)).map((o,a)=>{let l=ka(o,`resolver.feeGroups[${a}]`);return{key:Hi(l.key,"feeGroup.key"),name:ut(l.name,"feeGroup.name",pi,"Geb\xFChrengruppen"),billingItemKeys:Dv(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:Dv(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:Dv(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:W5(i.scenarios??[]),config:ka(i.config,"resolver.config")}}}s(z5,"parseResolverSetup");function Dv(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(Dv,"stringList");function W5(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=ka(n,"scenario");if(!("input"in t)||!("expected"in t))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Hi(t.key,"scenario.key"),input:t.input,expected:t.expected}})}s(W5,"parseScenarios");function Nm(e){let n=z.resolve(e);return z5(JSON.parse(ye(n,"utf8")),z.dirname(n))}s(Nm,"readResolverSetup");function Y5(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(Y5,"configValue");function J0(e){let n=s(()=>Hi(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),t=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...Fv(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"?Y5(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(J0,"billingSetupPayload");function Q0(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(Q0,"billingItemRef");function Fv(e){if(Array.isArray(e))return e.flatMap(Fv);if(typeof e!="object"||e===null)return[];let n=Q0(e);return n!==void 0?[n]:Object.values(e).flatMap(Fv)}s(Fv,"billingItemRefs");function Lv(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=Q0(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(Lv,"renderResolverConfig");function H5(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(H5,"assertPlaceholderParity");function J5(e,n){let t=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.revisionNumber-r.revisionNumber)[0];if(t!==void 0)return 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(J5,"matchingSealedRevision");async function Nd(e,n,t){if(t.resolver.source===null)throw new Error("generator setup requires a self-contained source file.");let r=ye(z.join(t.dir,t.resolver.source),"utf8"),i=await ql(z.join(t.dir,t.contractTemplate.file));H5(t.resolver.config,i);let o=await e.query(x.contractSetup.planBillingSetup,{client:n,...J0(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 $ of t.resolver.grantTemplateKeys){let O=d.grantTemplates.find(E=>E.configKey===$);if(O===void 0)throw new Error(`Unknown grant template ${$}`);c[$]=O.id}let u=Lv(t.resolver.config,o.billingItemIds,c),m=(await e.query(x.contractGeneratorRevisions.model,{client:n})).find($=>$.definition.key===t.resolver.key),y=m?.currentRevisionId?await e.query(x.contractGeneratorRevisions.detail,{client:n,id:m.currentRevisionId}):null,k=m?.revisions.find($=>$.status==="draft"),g=k?await e.query(x.contractGeneratorRevisions.detail,{client:n,id:k.id}):null,b=l||y===null?void 0:J5([y],{source:r,config:u,legalText:t.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:t.resolver.billingItemKeys.map($=>o.billingItemIds[$]??`not-created:${$}`),grantTemplateIds:Object.values(c),feeGroups:t.resolver.feeGroups.map($=>({key:$.key,name:$.name,billingItemDefinitionIds:$.billingItemKeys.map(O=>o.billingItemIds[O]??`not-created:${O}`)}))}),A=o.rows.map($=>({step:$.kind,target:$.key,action:$.action,detail:$.detail}));return A.push({step:"wordTemplate",target:t.contractTemplate.key,action:l?"create":"same",detail:z.basename(i.file)}),A.push({step:"generatorRevision",target:t.resolver.key,action:b?"same":"create",detail:b?`Current sealed revision ${b.revisionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:A,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:m,current:y,draft:g,match:b,template:{documentTemplateId:a?.id??null,upload:l}}}s(Nd,"planResolverSetup");async function Z0(e,n,t){let r=await Nd(e,n,t);if(r.rows.every(f=>f.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,...J0(t)});if(r.match)return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}};let o=r.template.upload?await dp(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.contractGeneratorRevisions.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.contractGeneratorRevisions.cloneDraft,{client:n,id:r.current._id})}let l=await e.query(x.contractGeneratorRevisions.detail,{client:n,id:a}),d=await e.mutation(x.contractGeneratorRevisions.save,{client:n,id:a,expectedSourceRevision:l.sourceRevision,config:Lv(t.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:t.resolver.legalText,documentTemplateId:o}),c=await e.action(x.contractGeneratorRevisionActions.saveSource,{client:n,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:t.resolver.billingItemKeys.map(f=>i.billingItemIds[f]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:t.resolver.feeGroups.map(f=>({key:f.key,name:f.name,billingItemDefinitionIds:f.billingItemKeys.map(m=>i.billingItemIds[m])}))});if(c.diagnostics.length||c.sourceRevision===null||c.artifactHash===null)throw new Error(c.diagnostics.join(`
10814
- `));if(d=c.sourceRevision,await e.mutation(x.contractGeneratorRevisions.approveScenarios,{client:n,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:Lv({scenarios:t.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(x.contractGeneratorRevisions.seal,{client:n,id:a,expectedSourceRevision:d}),(await Nd(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(Z0,"applyResolverSetup");async function Mv(e,n,t){let r=z.join(t.dir,G5);if(!Se(r)||t.workflow===void 0)return[];let i=Nm(r);if((await Nd(e,n,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(Mv,"pinSetupRevisions");function Q5(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(Q5,"nodeText");function Cd(e,n){let t=[],r=[],i=[],o={},a=n.progressEvents??[],l=Q5(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 f=e.type==="decision"&&d==="released"&&l!==void 0,m=f?l:u.label,y=u.tone,k={id:c,label:m,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 g=u.phase,b=Z5(g,e.id),A=i.find($=>$.id===b);if(A)A.states=[...A.states,c];else{let $={id:b,label:f?m:g.label,tone:y,states:[c]};g.track&&($.track=g.track),g.defaultCollapsed&&($.defaultCollapsed=!0),g.waitlist&&($.waitlist=!0),i.push($)}u.terminal&&(o[c]=u.terminal)}return{states:t,mappings:r,columns:i,terminalSemantics:o}}s(Cd,"deriveProgressEntriesForNode");function Cm(e){return Object.entries(e).filter(([,n])=>n.outcome==="approved").map(([n])=>n)}s(Cm,"seatedTerminalStates");function Z5(e,n){return e.scope==="global"?`col.${e.key}`:`${n}.${e.key}`}s(Z5,"columnIdFor");function X0(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(X0,"orderProcessColumns");var ir=s((e,n)=>({de:e,en:n}),"lt"),Kv=gs("start",[]),Dm=gs("form",[Kv]),qv=gs("end",[Kv,Dm]);function X5(e){let n=[Cd({id:Dm,type:"form",label:ir("Formular","Form")},Uo.form),Cd({id:qv,type:"end",label:ir("Ende","End")},Uo.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 f=r.find(m=>m.id===u.id);f?f.states=[...new Set([...f.states,...u.states])]:r.push(u)}}let a=Cm(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:t,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:ir("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(X5,"buildStarterProgress");function eM(e){let{slug:n,title:t,tenant:r,unit:i,responsible:o}=e,a=n,l=`${n}-form`,d=`${n}-flow`,c=[{id:Kv,type:"eventTrigger",label:ir("Start","Start"),sublabel:ir("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:Dm}}},{id:Dm,type:"form",label:t,sublabel:ir("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:ir("Standard","Standard")}],next:{standard:{to:qv}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:qv,type:"end",label:ir("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:AP(TP([{slot:"responsible",rules:[{when:Ki,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Wf({nodes:c})))},{layout:f,wiring:m}=X5(d),y={id:ya("section.applicant"),label:ir("Antragsteller","Applicant"),fields:[{key:ot("applicant.vorname"),label:ir("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:ot("applicant.nachname"),label:ir("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:Wi("standard"),label:ir("Standard","Standard"),when:"true",output:{fields:[{path:ot("applicant.vorname")},{path:ot("applicant.nachname")}],includeForm:!0}}],g={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,...g}},workflow:{graph:u,progressLayout:f,progressWiring:m}}}s(eM,"buildSkeletonBundle");var Wo={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function Nn(e,n,t){let i=(await e.query(x.workflow.listManifests,{client:n})).find(o=>o.offerKey===t);if(!i)throw new Error(`offer: no offer "${t}" in tenant "${n}"`);return i}s(Nn,"findOfferHandle");function st(e,n,t){return e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0})}s(st,"loadConfig");function jv(e,n){let t=e.units.find(r=>r.key===n);if(!t)throw new Error(`offer: unit "${n}" not found. Available keys: ${e.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return t.unitId}s(jv,"resolveUnitId");function ba(e,n){let t=nM(e),r=e.runs.find(i=>i.key===ci(t,n));if(!r)throw new Error(`offer: run "${n}" not found. Available keys: ${e.runs.map(i=>SD(t,i.key)).join(", ")||"(none)"}`);return r.runId}s(ba,"resolveRunId");function va(e,n){let t=nM(e),r=e.stages.find(i=>i.key===Ib(t,n));if(!r)throw new Error(`offer: level "${n}" not found. Available keys: ${e.stages.map(i=>jr(t,i.key)).join(", ")||"(none)"}`);return r.stageId}s(va,"resolveStageId");function nM(e){if(e.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(nM,"requireProgramKey");async function Bv(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(Bv,"linkUnit");function Yo(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(Yo,"parsePositiveInt");var xa=s((e="Offer slug (required)")=>p.String("--offer",{description:e}),"offerOption"),Uv=s(()=>p.String("--slug",{hidden:!0}),"retiredSlugOption");function Vv(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new kn(`--offer "${e.offer}" and --slug "${e.retiredSlug}" name different offers \u2014 pass only --offer.`);return an(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new kn("Missing --offer <slug>.");return e.offer}s(Vv,"requireOffer");var nn=class extends D{static{s(this,"OfferCommand")}offer=xa();retiredSlug=Uv();#e;get offerSlug(){return this.#e??=Vv(this),this.#e}};var Dd=class extends nn{static{s(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=T.Usage({category:"Offer",description:"Pull an offer's published generation (manifest + smartforms + workflow + program) into a bundle; --draft pulls the draft"});offer=xa("Manifest slug to export (required)");out=p.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=An();draft=p.Boolean("--draft",!1,{description:"Export the editable draft instead of the published generation (the live head, else the staged candidate)"});async execute(){let n=Nw(this.out,this.force),t=await this.caller(),r=this.requireTenant(t),{bundle:i,generation:o,revision:a}=await AL(t,r,this.offerSlug,this.draft?"draft":"published");return Tt({...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}},Fd=class extends xe{static{s(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=T.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});offer=xa("New offer slug (identity key) (required)");retiredSlug=Uv();title=p.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=p.String("--title-en",{required:!0,description:"The same title in English, e.g. 'Primary School' (every name a reader sees has both)"});tenant=p.String("--tenant",{required:!0,description:"Tenant slug (stamped on bundle.yaml)"});unit=p.String("--unit",{description:"Pedagogic unit (school) the portal resolves the offer through \u2014 its config key"});responsible=p.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=p.String("--template","basic",{description:"Scaffold template (only 'basic')"});out=p.String("--out",{description:"Output directory (default: offers/<tenant>/<slug>; refused when not empty, unless --force)"});force=An();async execute(){let n=Vv(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let t=Nw(this.out??z.join("offers",this.tenant,n),this.force),r=eM({slug:n,title:Hn({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 Tt({...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}},Ld=class extends xe{static{s(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=T.Usage({category:"Offer",description:"Run the publish-gate validators locally against a bundle (no deployment)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=Rt(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}},Md=class extends D{static{s(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=T.Usage({category:"Offer",description:"Read-only: local validation (resolver pins stamped from the environment, as publish would) + remote\u2194local diff (create/change/same)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await tM(t,n),a=await bv(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:Wo[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:Wo[d],target:`smartform:${l}`,detail:d})),{kind:Wo[a.workflow],target:"workflow",detail:a.workflow},...rM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...iM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...oM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...sM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},qd=class extends D{static{s(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=T.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=await this.caller(),r=await Mv(t,n.index.tenant,n),i=await bv(t,n);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:Wo[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:Wo[a],target:`smartform:${o}`,status:a})),{icon:Wo[i.workflow],target:"workflow",status:i.workflow},...rM(i),...iM(i),...oM(i),...sM(i)]),0}};async function tM(e,n){let t=await Mv(e,n.index.tenant,n),r=await Nv(e,n.index.tenant,n),i=await Cv(e,n.index.tenant,n);return{pins:t,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Rt(n)]}}s(tM,"validateOnEnvironment");function rM(e){return e.addresses===null?[]:vL(e.addresses)}s(rM,"addressRows");function iM(e){let n={insert:"+",update:"~",archive:"-"};return e.stages.map(t=>({icon:n[t.op],target:`stage:${t.key}`,status:Vp(t)}))}s(iM,"stageRows");function oM(e){return e.capacities.map(n=>({icon:"~",target:`cap:${n.run}\xD7${n.stageKey}`,status:Wp(n)}))}s(oM,"capacityRows");function sM(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(sM,"publishPendingRows");var Kd=class extends D{static{s(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=T.Usage({category:"Offer",description:"Idempotent create/update; with --publish, release the draft when it differs from what is live"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});publish=p.Boolean("--publish",!1,{description:"Release the draft when it says something the live generation does not"});stage=p.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=je(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await tM(t,n);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
10818
+ `)}`);let c=Ov(l),u=Array.isArray(i.formExports)?i.formExports.map(m=>m.key):null,f=i.formExports===void 0||Pe(i.formExports)!==Pe(c);i.formExports=c,r.push({node:i.id,form:o,before:u,after:c.map(m=>m.key),changed:f})}for(let i of t)if(i.type==="form"&&vt(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(Pm,"restampFormExports");function U0(e){let n=e.workflow?.graph?.nodes??[];return j0(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 B0(o).length>0?[]:Pe(t.formExports)===Pe(Ov(o))?[]:[{node:t.id,form:r}]})}s(U0,"staleFormExports");var _v=["string","number","boolean","date"];function V0(e,n){let t="offer form field export";for(let r of jt(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&&!D0(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 (${_v.join("|")}); an expression has none to infer`);if(!_v.includes(d))throw new Error(`${t}: --type "${d}" is no computed export type (${_v.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(V0,"setFieldExport");function G0(e,n,t){let r="offer workflow node set-generator",i=K0(e,n,r);if(wm(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=ei(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??{},[Kn]:{kind:"literal",value:{kind:t.kind,key:a}}};let u=d?[]:Object.keys(i.inputs).filter(f=>f!==Kn&&f!==qt);return{before:l,after:{key:a,kind:t.kind},droppedStamp:c,keptParameterCells:u}}s(G0,"setGeneratorPin");function z0(e,n,t){let r="offer workflow node set-cockpit-fields",i=K0(e,n,r),o=wm(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"?ei(i)!==null:mr(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 u of t){if(l.has(u))throw new Error(`${r}: --fields names "${u}" twice`);l.add(u)}let d={...i.inputs??{}},c=Object.keys(d).filter(u=>d[u]?.kind==="cockpit");for(let u of t){let f=d[u]?.kind;if(f!==void 0&&f!=="cockpit"&&f!=="unset")throw new Error(`${r}: "${u}" holds a ${String(f)} \u2014 a parameter has one source; remove it first (offer workflow node set-input --clear)`)}for(let u of c)l.has(u)||delete d[u];for(let u of t)d[u]={kind:"cockpit"};return i.inputs=d,{pin:o,before:c,after:[...t]}}s(z0,"setCockpitFields");var j3=new Set(["graph","progressLayout","progressWiring"]);function W0(e){let{label:n,...t}=e;return t}s(W0,"definitionOf");function B3(e){let n=[];for(let o of Object.keys(e))j3.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(BR.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(...P0(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(B3,"workflowShapeIssues");function Y0(e){let n=e.nodes??[],t=new Map;for(let r of n){let i=DI(r);i!==void 0&&t.set(r.id,i)}return t}s(Y0,"formNodeSlugById");function U3(e,n){let t=e.smartforms??{},r=new Map;for(let[i,o]of Y0(n)){let a=t[o];if(a===void 0)return;r.set(i,W0(a))}return qP(r)}s(U3,"readinessContext");function V3(e){return[...Y0(e).values()]}s(V3,"formNodeSlugs");function _m(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(_m,"describe");function Rt(e){let n=[];for(let l of of(e.manifest))n.push({severity:"error",area:"manifest",message:l});let t=Rn(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 Bp(e.index.program?.stages??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of Gp(e.index.program?.runs??[]))n.push({severity:"error",area:"program",message:l.message.de});for(let l of zp(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 b of B3(e.workflow))n.push({severity:"error",area:"workflow",message:b});let l=e.workflow.graph,d=e.workflow.progressLayout,c=e.workflow.progressWiring;if(d!==void 0)for(let b of jR(d))n.push({severity:"error",area:"workflow",message:b});let u=[];for(let{node:b,key:A,kind:$}of km(e))b.generatorStamp?.schemaDigest===void 0&&(u.push(b.id),n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped] Knoten "${b.id}" pinnt ${$}:${A} 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 b of l.nodes)b.type!=="governedDocument"||b.production!=="template"||b.templateStamp!==void 0||n.push({severity:"warning",area:"workflow",message:`[template/notStamped] Knoten "${b.id}" f\xFCllt die Vorlage ${mr(b)??"\u2014"} ohne ihre Parameter \u2014 welche Felder sie hat, pr\xFCft erst \`offer plan\` (stempelt sie vom Vorlagen-Datensatz der Umgebung).`});for(let{node:b,form:A}of U0(e))n.push({severity:"warning",area:"workflow",message:`[formExports/stale] Knoten "${b}": der Stempel formExports passt nicht mehr zum Formular "${A}" \u2014 die Adresspr\xFCfung liest den alten Stand; \`offer workflow restamp-exports\` stempelt ihn neu (publish tut es ohnehin).`});let f=U3(e,l),m=s(b=>{let A=R0(b,{layout:d,wiring:c},f),$=new Set(I0(A));return{issues:A,isError:s(O=>$.has(O)||(O.severity??"error")==="error","isError")}},"blockingOf"),{issues:y,isError:k}=m(l),g=new Set;if(u.length>0){let b=structuredClone(l);for(let E of b.nodes)u.includes(E.id)&&(E.generatorStamp={...E.generatorStamp??{},parts:[{partKey:"?"}]});let A=m(b),$=new Set(A.issues.filter(A.isError).map(_m)),O=s(E=>u.some(I=>E.includes(`$node.${I}.contract`)),"namesOutput");for(let E of y){let I=_m(E);k(E)&&!$.has(I)&&O(I)&&g.add(I)}}for(let b of y){let A=_m(b);if(g.has(A)){n.push({severity:"warning",area:"workflow",message:`[resolver/pinNotStamped \u2192 offer plan] ${A}`});continue}n.push({severity:k(b)?"error":"warning",area:"workflow",message:A})}}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=Rn(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=W0(d);for(let k of UR(u,`smartforms/${l}.json`))n.push({severity:"error",area:"smartform",message:k.de});let f=u,m=Tm(f,{stageKeys:a}),y=new Set($m(m));for(let k of m)n.push({severity:y.has(k)||k.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${_m(k)}`});for(let k of[...LL(f),...FL(f)])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(V3(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(Rt,"validateBundle");async function Nv(e,n,t){let r=km(t);if(r.length===0)return{rows:[],issues:[]};let i=[...new Map(r.map(({key:c,kind:u,revision:f})=>[`${u}:${c}:${f??"current"}`,{key:c,kind:u,...f===void 0?{}:{revision:f}}])).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:f,revision:m}of r){let y=a.get(`${f}:${u}:${m??"current"}`);if(y===void 0)throw new Error(`offer: the environment answered no stamp for ${f}:${u}`);if(y.stamp===null){if(y.refusal===null)throw new Error(`offer: the environment answered neither a stamp nor a refusal for ${f}:${u}`);d.push({severity:"error",area:"workflow",message:`[resolver/pinRefused] Knoten "${c.id}": ${y.refusal.de}`});continue}KR(c,structuredClone(y.stamp),{freezeRevision:!0}),l.push({target:`stamp:${c.id}`,detail:y.stamp.parts===void 0?`${f}:${u} Dokument`:`${f}:${u} kombiniert (${y.stamp.parts.map(k=>k.partKey).join(", ")})`})}return{rows:l,issues:d}}s(Nv,"stampResolverPins");async function Cv(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=mr(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=mr(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(kF(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(Cv,"stampTemplatePins");async function H0(e,n,t){let r=je(t),i=await Nv(e,n,r),o=await Cv(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");Tt(r);let d=a.map(f=>f.target.slice(6)),c=s(f=>d.some(m=>f.includes(`nodes.${m}.`)||f.includes(`node.${m}.`)||f.includes(`"${m}"`)),"onStamped"),u=Rt(r).filter(f=>f.severity==="error"&&c(f.message));return{rows:a,refused:[],open:u}}s(H0,"restampPinsOnDisk");var G3=z.join("contract","resolver-setup.json"),pi="resolver setup",ka=s((e,n)=>_n(e,n,pi),"record"),Hi=s((e,n)=>Ge(e,n,pi),"text");function z3(e,n){let t=ka(e,"Datei"),r=ka(t.contractTemplate,"contractTemplate"),i=ka(t.resolver,"resolver");return{dir:n,contractTemplate:{key:Hi(r.key,"contractTemplate.key"),name:ut(r.name,"contractTemplate.name",pi,"Vorlagennamen"),file:Hi(r.file,"contractTemplate.file"),role:Hi(r.role,"contractTemplate.role")},revenueAccounts:cp(t.revenueAccounts,pi),billingItems:up(t.billingItems,pi),resolver:{key:Hi(i.key,"resolver.key"),name:ut(i.name,"resolver.name",pi,"Generatornamen"),description:i.description===void 0?null:ut(i.description,"resolver.description",pi,"Beschreibungen"),legalText:i.legalText??{},source:Hi(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:Ct(i.feeGroups,"resolver.feeGroups",pi)).map((o,a)=>{let l=ka(o,`resolver.feeGroups[${a}]`);return{key:Hi(l.key,"feeGroup.key"),name:ut(l.name,"feeGroup.name",pi,"Geb\xFChrengruppen"),billingItemKeys:Dv(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:Dv(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:Dv(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:W3(i.scenarios??[]),config:ka(i.config,"resolver.config")}}}s(z3,"parseResolverSetup");function Dv(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(Dv,"stringList");function W3(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=ka(n,"scenario");if(!("input"in t)||!("expected"in t))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Hi(t.key,"scenario.key"),input:t.input,expected:t.expected}})}s(W3,"parseScenarios");function Nm(e){let n=z.resolve(e);return z3(JSON.parse(ye(n,"utf8")),z.dirname(n))}s(Nm,"readResolverSetup");function Y3(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(Y3,"configValue");function J0(e){let n=s(()=>Hi(e.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),t=new Set(e.billingItems.map(r=>r.key));return{revenueAccounts:e.revenueAccounts,catalogItemKeys:[...new Set([...Fv(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"?Y3(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(J0,"billingSetupPayload");function Q0(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(Q0,"billingItemRef");function Fv(e){if(Array.isArray(e))return e.flatMap(Fv);if(typeof e!="object"||e===null)return[];let n=Q0(e);return n!==void 0?[n]:Object.values(e).flatMap(Fv)}s(Fv,"billingItemRefs");function Lv(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=Q0(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(Lv,"renderResolverConfig");function H3(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(H3,"assertPlaceholderParity");function J3(e,n){let t=[...e].filter(r=>r.status==="sealed").sort((r,i)=>i.revisionNumber-r.revisionNumber)[0];if(t!==void 0)return 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(J3,"matchingSealedRevision");async function Nd(e,n,t){if(t.resolver.source===null)throw new Error("generator setup requires a self-contained source file.");let r=ye(z.join(t.dir,t.resolver.source),"utf8"),i=await ql(z.join(t.dir,t.contractTemplate.file));H3(t.resolver.config,i);let o=await e.query(x.contractSetup.planBillingSetup,{client:n,...J0(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 $ of t.resolver.grantTemplateKeys){let O=d.grantTemplates.find(E=>E.configKey===$);if(O===void 0)throw new Error(`Unknown grant template ${$}`);c[$]=O.id}let u=Lv(t.resolver.config,o.billingItemIds,c),m=(await e.query(x.contractGeneratorRevisions.model,{client:n})).find($=>$.definition.key===t.resolver.key),y=m?.currentRevisionId?await e.query(x.contractGeneratorRevisions.detail,{client:n,id:m.currentRevisionId}):null,k=m?.revisions.find($=>$.status==="draft"),g=k?await e.query(x.contractGeneratorRevisions.detail,{client:n,id:k.id}):null,b=l||y===null?void 0:J3([y],{source:r,config:u,legalText:t.resolver.legalText,documentTemplateId:a.id,billingItemDefinitionIds:t.resolver.billingItemKeys.map($=>o.billingItemIds[$]??`not-created:${$}`),grantTemplateIds:Object.values(c),feeGroups:t.resolver.feeGroups.map($=>({key:$.key,name:$.name,billingItemDefinitionIds:$.billingItemKeys.map(O=>o.billingItemIds[O]??`not-created:${O}`)}))}),A=o.rows.map($=>({step:$.kind,target:$.key,action:$.action,detail:$.detail}));return A.push({step:"wordTemplate",target:t.contractTemplate.key,action:l?"create":"same",detail:z.basename(i.file)}),A.push({step:"generatorRevision",target:t.resolver.key,action:b?"same":"create",detail:b?`Current sealed revision ${b.revisionNumber}`:"Save source, review scenarios and seal a new revision"}),{rows:A,docx:i,source:r,renderedConfig:u,billingItemIds:o.billingItemIds,grantTemplateIds:c,head:m,current:y,draft:g,match:b,template:{documentTemplateId:a?.id??null,upload:l}}}s(Nd,"planResolverSetup");async function Z0(e,n,t){let r=await Nd(e,n,t);if(r.rows.every(f=>f.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,...J0(t)});if(r.match)return{rows:r.rows,pin:{key:t.resolver.key,kind:"generator"}};let o=r.template.upload?await dp(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.contractGeneratorRevisions.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.contractGeneratorRevisions.cloneDraft,{client:n,id:r.current._id})}let l=await e.query(x.contractGeneratorRevisions.detail,{client:n,id:a}),d=await e.mutation(x.contractGeneratorRevisions.save,{client:n,id:a,expectedSourceRevision:l.sourceRevision,config:Lv(t.resolver.config,i.billingItemIds,r.grantTemplateIds),legalText:t.resolver.legalText,documentTemplateId:o}),c=await e.action(x.contractGeneratorRevisionActions.saveSource,{client:n,id:a,expectedSourceRevision:d,source:r.source,billingItemDefinitionIds:t.resolver.billingItemKeys.map(f=>i.billingItemIds[f]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:t.resolver.feeGroups.map(f=>({key:f.key,name:f.name,billingItemDefinitionIds:f.billingItemKeys.map(m=>i.billingItemIds[m])}))});if(c.diagnostics.length||c.sourceRevision===null||c.artifactHash===null)throw new Error(c.diagnostics.join(`
10819
+ `));if(d=c.sourceRevision,await e.mutation(x.contractGeneratorRevisions.approveScenarios,{client:n,id:a,expectedSourceRevision:d,artifactHash:c.artifactHash,scenarios:Lv({scenarios:t.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await e.mutation(x.contractGeneratorRevisions.seal,{client:n,id:a,expectedSourceRevision:d}),(await Nd(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(Z0,"applyResolverSetup");async function Mv(e,n,t){let r=z.join(t.dir,G3);if(!Se(r)||t.workflow===void 0)return[];let i=Nm(r);if((await Nd(e,n,i)).match===void 0)throw new Error("Apply the generator setup before publishing the offer.");return[]}s(Mv,"pinSetupRevisions");function Q3(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(Q3,"nodeText");function Cd(e,n){let t=[],r=[],i=[],o={},a=n.progressEvents??[],l=Q3(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 f=e.type==="decision"&&d==="released"&&l!==void 0,m=f?l:u.label,y=u.tone,k={id:c,label:m,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 g=u.phase,b=Z3(g,e.id),A=i.find($=>$.id===b);if(A)A.states=[...A.states,c];else{let $={id:b,label:f?m:g.label,tone:y,states:[c]};g.track&&($.track=g.track),g.defaultCollapsed&&($.defaultCollapsed=!0),g.waitlist&&($.waitlist=!0),i.push($)}u.terminal&&(o[c]=u.terminal)}return{states:t,mappings:r,columns:i,terminalSemantics:o}}s(Cd,"deriveProgressEntriesForNode");function Cm(e){return Object.entries(e).filter(([,n])=>n.outcome==="approved").map(([n])=>n)}s(Cm,"seatedTerminalStates");function Z3(e,n){return e.scope==="global"?`col.${e.key}`:`${n}.${e.key}`}s(Z3,"columnIdFor");function X0(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(X0,"orderProcessColumns");var ir=s((e,n)=>({de:e,en:n}),"lt"),Kv=gs("start",[]),Dm=gs("form",[Kv]),qv=gs("end",[Kv,Dm]);function X3(e){let n=[Cd({id:Dm,type:"form",label:ir("Formular","Form")},Uo.form),Cd({id:qv,type:"end",label:ir("Ende","End")},Uo.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 f=r.find(m=>m.id===u.id);f?f.states=[...new Set([...f.states,...u.states])]:r.push(u)}}let a=Cm(o);return{layout:{id:`layout.${e}.starter`,buses:[{key:"process",states:t,terminalSemantics:o,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:ir("Prozess","Process"),audience:"both",columns:r}]}]},wiring:{mappings:i}}}s(X3,"buildStarterProgress");function eM(e){let{slug:n,title:t,tenant:r,unit:i,responsible:o}=e,a=n,l=`${n}-form`,d=`${n}-flow`,c=[{id:Kv,type:"eventTrigger",label:ir("Start","Start"),sublabel:ir("Eingang externer Bewerber-Aktion","Incoming external applicant action"),next:{bewerbungOffen:{to:Dm}}},{id:Dm,type:"form",label:t,sublabel:ir("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:ir("Standard","Standard")}],next:{standard:{to:qv}},notifications:{submitted:{templateId:"applicant.applicationSubmitted"}}},{id:qv,type:"end",label:ir("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"}}}],u={nodes:c,assignmentRules:AP(TP([{slot:"responsible",rules:[{when:Ki,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:o}}]}],Wf({nodes:c})))},{layout:f,wiring:m}=X3(d),y={id:ya("section.applicant"),label:ir("Antragsteller","Applicant"),fields:[{key:ot("applicant.vorname"),label:ir("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:ot("applicant.nachname"),label:ir("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},k=[{id:Wi("standard"),label:ir("Standard","Standard"),when:"true",output:{fields:[{path:ot("applicant.vorname")},{path:ot("applicant.nachname")}],includeForm:!0}}],g={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,...g}},workflow:{graph:u,progressLayout:f,progressWiring:m}}}s(eM,"buildSkeletonBundle");var Wo={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function Nn(e,n,t){let i=(await e.query(x.workflow.listManifests,{client:n})).find(o=>o.offerKey===t);if(!i)throw new Error(`offer: no offer "${t}" in tenant "${n}"`);return i}s(Nn,"findOfferHandle");function st(e,n,t){return e.query(x.programAdmin.getAngebotConfig,{client:n,offerKey:t,includeArchived:!0})}s(st,"loadConfig");function jv(e,n){let t=e.units.find(r=>r.key===n);if(!t)throw new Error(`offer: unit "${n}" not found. Available keys: ${e.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return t.unitId}s(jv,"resolveUnitId");function ba(e,n){let t=nM(e),r=e.runs.find(i=>i.key===ci(t,n));if(!r)throw new Error(`offer: run "${n}" not found. Available keys: ${e.runs.map(i=>SD(t,i.key)).join(", ")||"(none)"}`);return r.runId}s(ba,"resolveRunId");function va(e,n){let t=nM(e),r=e.stages.find(i=>i.key===Ib(t,n));if(!r)throw new Error(`offer: level "${n}" not found. Available keys: ${e.stages.map(i=>jr(t,i.key)).join(", ")||"(none)"}`);return r.stageId}s(va,"resolveStageId");function nM(e){if(e.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return e.programKey}s(nM,"requireProgramKey");async function Bv(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(Bv,"linkUnit");function Yo(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(Yo,"parsePositiveInt");var xa=s((e="Offer slug (required)")=>p.String("--offer",{description:e}),"offerOption"),Uv=s(()=>p.String("--slug",{hidden:!0}),"retiredSlugOption");function Vv(e){if(e.retiredSlug!==void 0){if(e.offer!==void 0&&e.offer!==e.retiredSlug)throw new kn(`--offer "${e.offer}" and --slug "${e.retiredSlug}" name different offers \u2014 pass only --offer.`);return an(e.context.stderr,"--slug","--offer"),e.retiredSlug}if(e.offer===void 0)throw new kn("Missing --offer <slug>.");return e.offer}s(Vv,"requireOffer");var nn=class extends D{static{s(this,"OfferCommand")}offer=xa();retiredSlug=Uv();#e;get offerSlug(){return this.#e??=Vv(this),this.#e}};var Dd=class extends nn{static{s(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=T.Usage({category:"Offer",description:"Pull an offer's published generation (manifest + smartforms + workflow + program) into a bundle; --draft pulls the draft"});offer=xa("Manifest slug to export (required)");out=p.String("--out",{required:!0,description:"Output bundle directory (refused when not empty, unless --force)"});force=An();draft=p.Boolean("--draft",!1,{description:"Export the editable draft instead of the published generation (the live head, else the staged candidate)"});async execute(){let n=Nw(this.out,this.force),t=await this.caller(),r=this.requireTenant(t),{bundle:i,generation:o,revision:a}=await AL(t,r,this.offerSlug,this.draft?"draft":"published");return Tt({...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}},Fd=class extends xe{static{s(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=T.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});offer=xa("New offer slug (identity key) (required)");retiredSlug=Uv();title=p.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=p.String("--title-en",{required:!0,description:"The same title in English, e.g. 'Primary School' (every name a reader sees has both)"});tenant=p.String("--tenant",{required:!0,description:"Tenant slug (stamped on bundle.yaml)"});unit=p.String("--unit",{description:"Pedagogic unit (school) the portal resolves the offer through \u2014 its config key"});responsible=p.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=p.String("--template","basic",{description:"Scaffold template (only 'basic')"});out=p.String("--out",{description:"Output directory (default: offers/<tenant>/<slug>; refused when not empty, unless --force)"});force=An();async execute(){let n=Vv(this);if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let t=Nw(this.out??z.join("offers",this.tenant,n),this.force),r=eM({slug:n,title:Hn({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 Tt({...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}},Ld=class extends xe{static{s(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=T.Usage({category:"Offer",description:"Run the publish-gate validators locally against a bundle (no deployment)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=Rt(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}},Md=class extends D{static{s(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=T.Usage({category:"Offer",description:"Read-only: local validation (resolver pins stamped from the environment, as publish would) + remote\u2194local diff (create/change/same)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await tM(t,n),a=await bv(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:Wo[a.manifest],target:"manifest",detail:a.manifest},...Object.entries(a.smartforms).map(([l,d])=>({kind:Wo[d],target:`smartform:${l}`,detail:d})),{kind:Wo[a.workflow],target:"workflow",detail:a.workflow},...rM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...iM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...oM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status})),...sM(a).map(l=>({kind:l.icon,target:l.target,detail:l.status}))]),o.some(l=>l.severity==="error")?1:0}},qd=class extends D{static{s(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=T.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=je(this.dir),t=await this.caller(),r=await Mv(t,n.index.tenant,n),i=await bv(t,n);return this.print(i,()=>[...r.map(o=>({icon:"=",target:o.target,status:o.detail})),{icon:Wo[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([o,a])=>({icon:Wo[a],target:`smartform:${o}`,status:a})),{icon:Wo[i.workflow],target:"workflow",status:i.workflow},...rM(i),...iM(i),...oM(i),...sM(i)]),0}};async function tM(e,n){let t=await Mv(e,n.index.tenant,n),r=await Nv(e,n.index.tenant,n),i=await Cv(e,n.index.tenant,n);return{pins:t,stamps:{...r,rows:[...r.rows,...i.rows]},issues:[...r.issues,...i.issues,...Rt(n)]}}s(tM,"validateOnEnvironment");function rM(e){return e.addresses===null?[]:vL(e.addresses)}s(rM,"addressRows");function iM(e){let n={insert:"+",update:"~",archive:"-"};return e.stages.map(t=>({icon:n[t.op],target:`stage:${t.key}`,status:Vp(t)}))}s(iM,"stageRows");function oM(e){return e.capacities.map(n=>({icon:"~",target:`cap:${n.run}\xD7${n.stageKey}`,status:Wp(n)}))}s(oM,"capacityRows");function sM(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(sM,"publishPendingRows");var Kd=class extends D{static{s(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=T.Usage({category:"Offer",description:"Idempotent create/update; with --publish, release the draft when it differs from what is live"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});publish=p.Boolean("--publish",!1,{description:"Release the draft when it says something the live generation does not"});stage=p.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=je(this.dir),t=await this.caller(),{pins:r,stamps:i,issues:o}=await tM(t,n);for(let d of[...r,...i.rows])this.context.stderr.write(` = ${d.target}: ${d.detail}
10815
10820
  `);for(let d of o)d.severity==="warning"&&this.context.stderr.write(` warning ${d.area}: ${d.message}
10816
10821
  `);let a=o.filter(d=>d.severity==="error");if(a.length>0){let d=this.publish?"\u2716":"\u26A0";for(let c of a)this.context.stderr.write(` ${d} ${c.area}: ${c.message}
10817
10822
  `);if(this.publish)throw new Error("offer: fix local validation errors before --publish");this.context.stderr.write(` \u2192 applying as DRAFT despite validation errors (publish will enforce)
10818
- `)}let l=await SL(t,n,{publish:this.publish,publishStage:this.stage});return this.print(l,d=>d.steps.map(c=>({step:c.step,action:c.action,detail:c.detail??""}))),0}};var jd=class extends D{static{s(this,"OfferListCommand")}static paths=[["offer","list"]];static usage=T.Usage({category:"Offer",description:"List offers (manifests) + publish state for a tenant"});all=p.Boolean("--all",!1,{description:"Include archived (soft-deleted) offers"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workflow.listManifests,{client:t}),i=this.all?r:r.filter(o=>o.retiredAt==null);return this.print(i,o=>o.map(a=>({slug:a.offerKey,state:a.retiredAt!=null?"archived":a.isPublished?"published":"draft",sortOrder:a.sortOrder?.toString()??"-",label:_e(a.label)}))),0}},Bd=class extends nn{static{s(this,"OfferStatusCommand")}static paths=[["offer","status"]];static usage=T.Usage({category:"Offer",description:"Publish state + whether program/pedagogy links resolve (applyable?)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),i=(await n.query(x.workflow.listManifests,{client:t})).find(d=>d.offerKey===this.offerSlug);if(!i)throw new Error(`offer: no offer "${this.offerSlug}" in "${t}"`);let o=await n.query(x.workflow.getOfferPublishState,{client:t,offerKey:this.offerSlug}),a=s(d=>d==null?"-":`v${d}`,"rev"),l={manifest:i.isPublished?"published":"draft",workflow:i.workflowDefinitionId?"bound":"MISSING",pedagogy:i.pedagogy?_e(i.pedagogy.unitName):"UNLINKED (not applyable)",draft:a(o?.draftRevision),internal:a(o?.internalHeadRevision),live:a(o?.externalHeadRevision),publish:o===null?"-":o.draftDiffersFromExternal?"PENDING (draft is ahead of live)":"up to date"};return this.print(l,d=>[{field:"manifest",value:d.manifest},{field:"workflow",value:d.workflow},{field:"pedagogy",value:d.pedagogy},{field:"draft",value:d.draft},{field:"internal",value:d.internal},{field:"live",value:d.live},{field:"publish",value:d.publish}]),0}},e3={draft:"draft (editable)",internal:"internal (staged, testable)",published:"published (live)",archived:"archived"},Ud=class extends nn{static{s(this,"OfferVersionsCommand")}static paths=[["offer","versions"]];static usage=T.Usage({category:"Offer",description:"List an offer's versions (generations) \u2014 the id `applications start-test --version` takes",details:"Every generation of the offer family, newest first: the editable draft, an internally staged candidate, the live head and the archived history (still pinned by the applications started on it). `offerVersionId` is what `applications start-test --version` runs on; `workflowVersionId` opens the read-only graph of that generation.",examples:[["The versions of an offer","$0 offer versions --tenant test --slug grundschule-havelland"],["Test the staged candidate","$0 --env staging applications start-test --offer grundschule-havelland --run <run> --stage <stage> --applicant test@example.com --version <offerVersionId>"]]});async execute(){let n=await this.caller(),t=this.requireTenant(n),i=(await n.query(x.workflow.listManifests,{client:t})).find(a=>a.offerKey===this.offerSlug);if(!i)throw new Error(`offer versions: no offer "${this.offerSlug}" in "${t}"`);if(!i.workflowDefinitionId)throw new Error(`offer versions: "${this.offerSlug}" has no workflow yet \u2014 a draft offer has no generation to test`);let o=await n.query(x.workflow.listWorkflowVersions,{workflowDefinitionId:i.workflowDefinitionId});return this.print(o,a=>a.map(l=>({revision:`v${l.revision}`,state:e3[l.state],published:l.publishedAt===null?"\u2014":new Date(l.publishedAt).toISOString().slice(0,16).replace("T"," "),offerVersionId:l.offerVersionId,workflowVersionId:l.versionId}))),0}};var aM={de:"--title",en:"--title-en"},Vd=class extends nn{static{s(this,"OfferCreateCommand")}static paths=[["offer","create"]];static usage=T.Usage({category:"Offer",description:"Create a draft offer (manifest) \u2014 title (= program name) + optional unit"});offer=xa("New offer slug (identity key) (required)");title=p.String("--title",{required:!0,description:"Bare program name in German \u2014 no run/year or levels (those are separate; see `offer init --title`)"});titleEn=p.String("--title-en",{required:!0,description:"The same title in English (every name a reader sees has both)"});unit=p.String("--unit",{description:"Pedagogic unit (school) the offer belongs to \u2014 its config key"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Hn({de:this.title,en:this.titleEn},"offer create",aM);if(await n.mutation(x.workflow.createManifest,{client:t,slug:this.offerSlug,label:r}),this.unit){let i=await st(n,t,this.offerSlug);await Bv(n,t,this.offerSlug,jv(i,this.unit))}return this.print({created:this.offerSlug,title:r,unit:this.unit??null},i=>[{key:"created",value:i.created},{key:"title",value:_e(i.title)},{key:"unit",value:i.unit??"\u2014"}]),0}},Gd=class extends nn{static{s(this,"OfferShowCommand")}static paths=[["offer","show"]];static usage=T.Usage({category:"Offer",description:"Full view of an offer: title, unit, levels, runs, capacity, state (incl. archived)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=new Map(i.stages.map(c=>[c.stageId,c.name])),a=new Map(i.runs.map(c=>[c.runId,c.name])),l=r.retiredAt!=null,d={slug:r.offerKey,title:r.label,sortOrder:r.sortOrder??null,state:l?"archived":r.isPublished?"published":"draft",unit:r.pedagogy?r.pedagogy.unitName:null,workflow:r.workflowDefinitionId?"bound":"MISSING",applyable:!!(r.workflowDefinitionId&&r.pedagogy&&!l),levels:i.stages.map(c=>({key:c.key,name:c.name,sequence:c.sequence,gradeLevel:c.gradeLevel??null,archived:c.archived})),runs:i.runs.map(c=>({key:c.key,name:c.name,status:c.status,isOpen:c.isOpen,startDate:c.startDate??null,endDate:c.endDate??null})),capacity:i.runStages.map(c=>({run:a.get(c.runId)??c.runId,level:o.get(c.stageId)??c.stageId,capacity:c.capacity,isOpen:c.isOpen}))};return this.print(d,c=>[{section:"offer",item:c.slug,detail:_e(c.title)},{section:"state",item:c.state,detail:`unit=${c.unit?_e(c.unit):"\u2014"} sortOrder=${c.sortOrder??"\u2014"} workflow=${c.workflow} applyable=${c.applyable}`},...c.levels.map(u=>({section:"level",item:_e(u.name),detail:`seq=${u.sequence}${u.gradeLevel!=null?` grade=${u.gradeLevel}`:""}${u.archived?" [archived]":""}`})),...c.runs.map(u=>({section:"run",item:_e(u.name),detail:`${u.status}${u.isOpen?" open":""}${u.startDate?` ${u.startDate}\u2192${u.endDate??"?"}`:""}`})),...c.capacity.map(u=>({section:"capacity",item:`${typeof u.run=="string"?u.run:_e(u.run)} \xD7 ${typeof u.level=="string"?u.level:_e(u.level)}`,detail:`${u.capacity??"\u221E"}${u.isOpen?" open":" closed"}`}))]),0}},zd=class extends nn{static{s(this,"OfferSetCommand")}static paths=[["offer","set"]];static usage=T.Usage({category:"Offer",description:"Update an offer's title and/or pedagogic unit"});title=p.String("--title",{description:"New bare offer title in German (offer_versions.label, the offer-title SoT) \u2014 no run/year or levels (those are separate entities)"});titleEn=p.String("--title-en",{description:"New offer title in English \u2014 required with --title: the English is never copied from the German, and a title without English is refused"});programName=p.String("--program-name",{description:"Rename the underlying master-data program in German (programs.name, staff master-data only \u2014 distinct from --title); needs --program-name-en"});programNameEn=p.String("--program-name-en",{description:"The program's name in English (with --program-name)"});unit=p.String("--unit",{description:"New pedagogic unit (school) \u2014 its config key"});sortOrder=p.String("--sort-order",{description:"Display order among the unit's offers (lower = first, non-negative number)"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.title===void 0&&this.titleEn===void 0&&this.programName===void 0&&this.programNameEn===void 0&&!this.unit&&this.sortOrder===void 0)throw new Error("offer set: pass --title/--title-en, --program-name/--program-name-en, --unit and/or --sort-order");let r=await Nn(n,t,this.offerSlug),i=[],o;if(this.sortOrder!==void 0&&(o=Number(this.sortOrder),!Number.isFinite(o)||o<0))throw new Error(`offer set: --sort-order must be a non-negative number, got "${this.sortOrder}"`);let a=Xt(r.label,{de:this.title,en:this.titleEn},"offer set",aM);if((a!==void 0||o!==void 0)&&(await n.mutation(x.workflow.createManifest,{client:t,slug:this.offerSlug,label:a??r.label,...o!==void 0?{sortOrder:o}:{}}),a!==void 0&&i.push(`title=${_e(a)}`),o!==void 0&&i.push(`sortOrder=${o}`)),this.programName!==void 0||this.programNameEn!==void 0){let l=Hn({de:this.programName,en:this.programNameEn},"offer set",{de:"--program-name",en:"--program-name-en"});await n.mutation(x.programAdmin.updateProgram,{client:t,offerKey:r.offerKey,name:l}),i.push(`programName=${_e(l)}`)}if(this.unit){let l=await st(n,t,r.offerKey);await Bv(n,t,r.offerKey,jv(l,this.unit)),i.push(`unit=${this.unit}`)}return this.print({slug:this.offerSlug,changes:i},l=>l.changes.map(d=>({change:d}))),0}},Wd=class extends nn{static{s(this,"OfferArchiveCommand")}static paths=[["offer","archive"]];static usage=T.Usage({category:"Offer",description:"Archive (soft-delete) an offer \u2014 `offer restore` brings it back, never orphans data"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);return await n.mutation(x.programAdmin.setManifestArchived,{client:t,offerKey:r.offerKey,archived:!0}),this.print({archived:this.offerSlug},i=>[{key:"archived (soft-deleted)",value:i.archived}]),0}},Yd=class extends nn{static{s(this,"OfferRestoreCommand")}static paths=[["offer","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived offer"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);return await n.mutation(x.programAdmin.setManifestArchived,{client:t,offerKey:r.offerKey,archived:!1}),this.print({restored:this.offerSlug},i=>[{key:"restored",value:i.restored}]),0}},Hd=class extends nn{static{s(this,"OfferDeleteCommand")}static paths=[["offer","delete"],["offer","hard-delete"]];static usage=T.Usage({category:"Offer",description:"HARD-delete an offer (manifest + versions + workflow + smartform + program + stages + runs) \u2014 irreversible, plan unless --confirm; refused while any application exists. To take an offer down reversibly use `offer archive`.",examples:[["Plan","$0 --env staging --tenant <slug> offer delete --offer <offer>"],["Delete","$0 --env staging --tenant <slug> offer delete --offer <offer> --confirm"]]});confirm=p.Boolean("--confirm",!1,{description:"Delete for good (without it, only the plan is printed)."});retiredYes=p.Boolean("--yes",!1,{hidden:!0});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);if(!this.confirm){let o=await st(n,t,r.offerKey),a={offer:r.offerKey,title:r.label,levels:o.stages.length,runs:o.runs.length,deleted:!1};return this.print(a,l=>[{key:"would HARD-delete offer",value:`${l.offer} (${_e(l.title)}) \u2014 irreversible`},{key:"with",value:`${l.levels} level(s), ${l.runs} run(s), its versions, workflow and form`},{key:"refused when",value:"any application exists"},{key:"next",value:"re-run with --confirm \u2014 or `offer archive` to take it down reversibly"}]),0}let i=await n.mutation(x.programAdmin.hardDeleteOffer,{client:t,offerKey:r.offerKey});return this.print(i,o=>[{key:"hard-deleted offer",value:this.offerSlug},{key:"offerKey",value:o.deletedOfferKey},{key:"program",value:o.deletedProgramId??"(none)"},{key:"counts",value:JSON.stringify(o.counts)}]),0}};var lM={de:"--name",en:"--name-en"},Jd=class extends nn{static{s(this,"OfferRunAddCommand")}static paths=[["offer","run","add"]];static usage=T.Usage({category:"Offer",description:"Add a run (Schuljahr) to an offer"});name=p.String("--name",{required:!0,description:"Run name in German (e.g. Schuljahr 2026/27)"});nameEn=p.String("--name-en",{required:!0,description:"Run name in English (e.g. School year 2026/27)"});key=p.String("--key",{description:"Stable run key, as in bundle.yaml program.runs[].key (lowercase slug, e.g. 2026-27). Without it the key is derived from the German --name \u2014 and keeps that value after a rename"});start=p.String("--start",{description:"Start date (ISO, e.g. 2026-08-01)"});end=p.String("--end",{description:"End date (ISO)"});capacity=p.String("--capacity",{description:"Default seat capacity per level"});closed=p.Boolean("--closed",!1,{description:"Create closed (default: open)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=Yo("capacity",this.capacity),o=Hn({de:this.name,en:this.nameEn},"offer run add",lM);return await n.mutation(x.programAdmin.addProgramRun,{client:t,offerKey:r.offerKey,name:o,...this.key!==void 0?{key:this.key}:{},isOpen:!this.closed,...this.start?{startDate:this.start}:{},...this.end?{endDate:this.end}:{},...i!==void 0?{defaultCapacity:i}:{}}),this.print({added:o},a=>[{key:"run added",value:_e(a.added)}]),0}},Qd=class extends nn{static{s(this,"OfferRunSetCommand")}static paths=[["offer","run","set"]];static usage=T.Usage({category:"Offer",description:"Update a run: rename / dates"});run=p.String("--run",{required:!0,description:"Key of the run to update (bundle.yaml program.runs[].key)"});name=p.String("--name",{description:"New run name in German"});nameEn=p.String("--name-en",{description:"New run name in English"});start=p.String("--start",{description:"Start date (ISO)"});end=p.String("--end",{description:"End date (ISO)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=ba(i,this.run),a=i.runs.find(d=>d.runId===o),l=Xt(a.name,{de:this.name,en:this.nameEn},"offer run set",lM);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:o,...l!==void 0?{name:l}:{},...this.start?{startDate:this.start}:{},...this.end?{endDate:this.end}:{}}),this.print({updated:this.run},d=>[{key:"run updated",value:d.updated}]),0}},Zd=class extends nn{static{s(this,"OfferRunArchiveCommand")}static paths=[["offer","run","archive"]];static usage=T.Usage({category:"Offer",description:"Soft-delete (archive) a run \u2014 retired from the portal, restorable"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),status:"archived"}),this.print({archived:this.run},o=>[{key:"run archived",value:o.archived}]),0}},Xd=class extends nn{static{s(this,"OfferRunRestoreCommand")}static paths=[["offer","run","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived run"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),status:"active"}),this.print({restored:this.run},o=>[{key:"run restored",value:o.restored}]),0}};var dM={de:"--name",en:"--name-en"},ec=class extends nn{static{s(this,"OfferLevelAddCommand")}static paths=[["offer","level","add"]];static usage=T.Usage({category:"Offer",description:"Add a level (Klassenstufe) to an offer"});name=p.String("--name",{required:!0,description:"Level name in German"});nameEn=p.String("--name-en",{required:!0,description:"Level name in English"});grade=p.String("--grade",{description:"Grade level (integer)"});key=p.String("--key",{description:"Stable level key, as in bundle.yaml program.stages[].key (lowercase slug). Without it the key is derived from the German --name \u2014 and keeps that value after a rename"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=Yo("grade",this.grade),o=Hn({de:this.name,en:this.nameEn},"offer level add",dM);return await n.mutation(x.programAdmin.addProgramStage,{client:t,offerKey:r.offerKey,name:o,...i!==void 0?{gradeLevel:i}:{},...this.key!==void 0?{key:this.key}:{}}),this.print({added:o},a=>[{key:"level added",value:_e(a.added)}]),0}},nc=class extends nn{static{s(this,"OfferLevelSetCommand")}static paths=[["offer","level","set"],["offer","level","rename"]];static usage=T.Usage({category:"Offer",description:"Change a level's name and/or grade"});level=p.String("--level",{required:!0,description:"Key of the level to update (bundle.yaml program.stages[].key)"});name=p.String("--name",{description:"New level name in German"});nameEn=p.String("--name-en",{description:"New level name in English"});grade=p.String("--grade",{description:"New grade level (integer)"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.name===void 0&&this.nameEn===void 0&&this.grade===void 0)throw new Error("offer level set: pass --name/--name-en and/or --grade");let r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=Yo("grade",this.grade),a=va(i,this.level),l=i.stages.find(c=>c.stageId===a),d=Xt(l.name,{de:this.name,en:this.nameEn},"offer level set",dM);return await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:a,...d!==void 0?{name:d}:{},...o!==void 0?{gradeLevel:o}:{}}),this.print({updated:this.level},c=>[{key:"level updated",value:c.updated}]),0}},tc=class extends nn{static{s(this,"OfferLevelArchiveCommand")}static paths=[["offer","level","archive"],["offer","level","remove"]];static usage=T.Usage({category:"Offer",description:"Soft-delete (archive) a level \u2014 retired from the portal, restorable. Refused while an active application sits on the level"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),{warnings:o}=await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:va(i,this.level),archived:!0});return this.print({removed:this.level,warnings:o},a=>[{key:"level removed (soft)",value:a.removed},...a.warnings.map(l=>({key:"warning",value:l}))]),0}},rc=class extends nn{static{s(this,"OfferLevelRestoreCommand")}static paths=[["offer","level","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived level"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:va(i,this.level),archived:!1}),this.print({restored:this.level},o=>[{key:"level restored",value:o.restored}]),0}},ic=class extends nn{static{s(this,"OfferLevelMoveCommand")}static paths=[["offer","level","move"]];static usage=T.Usage({category:"Offer",description:"Reorder a level among the offer's levels (--before|--after another level)"});level=p.String("--level",{required:!0,description:"Key of the level to move"});before=p.String("--before",{description:"Place before the level with this key"});after=p.String("--after",{description:"Place after the level with this key"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.before===void 0==(this.after===void 0))throw new Error("offer level move: pass exactly one of --before <level> / --after <level>");let r=this.before??this.after;if(r===this.level)throw new Error("offer level move: --before/--after anchor cannot be the level itself");let i=await Nn(n,t,this.offerSlug),o=await st(n,t,i.offerKey);if(o.programKey===null)throw new Error("offer level move: the offer has no program yet");let a=o.programKey,l=o.stages.map(f=>({stageId:f.stageId,key:jr(a,f.key),name:f.name})),d=l.find(f=>f.key===this.level);if(!d)throw new Error(`offer level move: level "${this.level}" not found. Available keys: ${l.map(f=>f.key).join(", ")||"(none)"}`);if(!l.some(f=>f.key===r))throw new Error(`offer level move: anchor level "${r}" not found. Available keys: ${l.map(f=>f.key).join(", ")}`);let c=l.filter(f=>f.key!==this.level),u=c.findIndex(f=>f.key===r);c.splice(this.before!==void 0?u:u+1,0,d);for(let f=0;f<c.length;f++)await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:i.offerKey,stageId:c[f].stageId,sequence:f+1});return this.print({moved:this.level,order:c.map(f=>f.key)},f=>[{key:"level moved",value:f.moved},{key:"new order",value:f.order.join(" \u2192 ")}]),0}};var oc=class extends nn{static{s(this,"OfferCapacitySetCommand")}static paths=[["offer","capacity","set"]];static usage=T.Usage({category:"Offer",description:"Set seat capacity and/or open-state for one run \xD7 level cell"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});capacity=p.String("--capacity",{description:'Seat capacity (whole number) or "unlimited"'});open=p.Boolean("--open",!1,{description:"Open this cell"});close=p.Boolean("--close",!1,{description:"Close this cell"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.open&&this.close)throw new Error("offer capacity set: pass only one of --open / --close");let r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=this.capacity==="unlimited"?"unlimited":Yo("capacity",this.capacity),a=this.open?!0:this.close?!1:void 0;return await n.mutation(x.programAdmin.setRunStageCapacity,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),stageId:va(i,this.level),...o!==void 0?{capacity:o}:{},...a!==void 0?{isOpen:a}:{}}),this.print({run:this.run,level:this.level},l=>[{key:"capacity set",value:`${l.run} \xD7 ${l.level}`}]),0}};function Gv(e,n,t){let r=e.indexOf("=");if(r<=0||r===e.length-1)throw new Error(`offer upgrade: ${n} takes ${t} (got "${e}")`);return[e.slice(0,r),e.slice(r+1)]}s(Gv,"splitPair");function n3(e,n){let t={waitlistOrder:e};if(!ny(t))throw new Error(`offer upgrade: ${n} takes <node>=<arrival|manual> (got "${e}")`);return t}s(n3,"parsePolicy");function Fm(e,n){if(e===void 0)return{};if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`offer upgrade: ${n} must be an object`);return e}s(Fm,"record");function cM(e){let n={},t={},r={},i=s((a,l,d,c)=>{if(Object.hasOwn(a,l)&&JSON.stringify(a[l])!==JSON.stringify(d))throw new Error(`offer upgrade: ${c} "${l}" is answered twice with different values`);a[l]=d},"put"),o=Fm(e.answersFile,"the answers file");for(let a of Object.keys(o))if(a!=="semantics"&&a!=="waitlistPolicy"&&a!=="payee")throw new Error(`offer upgrade: the answers file has an unknown key "${a}" (semantics | waitlistPolicy | payee)`);for(let[a,l]of Object.entries(Fm(o.semantics,"answers.semantics"))){if(typeof l!="string")throw new Error(`offer upgrade: answers.semantics["${a}"] must be a string`);i(n,a,l,"the outcome")}for(let[a,l]of Object.entries(Fm(o.waitlistPolicy,"answers.waitlistPolicy"))){if(!ny(l))throw new Error(`offer upgrade: answers.waitlistPolicy["${a}"] must be { waitlistOrder: arrival|manual }`);i(t,a,l,"the waitlist node")}for(let[a,l]of Object.entries(Fm(o.payee,"answers.payee"))){if(typeof l!="string"||l==="")throw new Error(`offer upgrade: answers.payee["${a}"] must be a Tr\xE4ger key`);i(r,a,l,"the payment node")}for(let a of e.semantic??[]){let[l,d]=Gv(a,"--semantic","<node>.<outcome>=<meaning>");if(!l.includes("."))throw new Error(`offer upgrade: --semantic takes <node>.<outcome>=<meaning> (got "${a}")`);i(n,l,d,"the outcome")}for(let a of e.waitlistPolicy??[]){let[l,d]=Gv(a,"--waitlist-policy","<node>=<arrival|manual>");i(t,l,n3(d,"--waitlist-policy"),"the waitlist node")}for(let a of e.payee??[]){let[l,d]=Gv(a,"--payee","<node>=<Tr\xE4ger key>");i(r,l,d,"the payment node")}return{semantics:n,waitlistPolicy:t,payee:r}}s(cM,"parseUpgradeAnswers");function uM(e){let n=e.candidates?.join("|")??"";switch(e.answer){case"semantic":return`--semantic ${e.answerKey}=<${n}>`;case"waitlistPolicy":return`--waitlist-policy ${e.answerKey}=<arrival|manual>`;case"payee":return`--payee ${e.answerKey}=<Tr\xE4ger key>`;case"edit":return"edit the file by hand"}}s(uM,"answerHint");function fM(e){let n=e.defaulted;if(n===void 0)return"-";switch(n.answer){case"semantic":return`--semantic ${n.answerKey}=${n.value}`;case"waitlistPolicy":return`--waitlist-policy ${n.answerKey}=${n.value}`;case"undeclaredBinding":return`${n.answerKey} deleted (publish refuses an undeclared input)`}}s(fM,"defaultedHint");function pM(e,n){Cn(n,{recursive:!0});for(let t of $r(e,{withFileTypes:!0})){let r=z.join(e,t.name),i=z.join(n,t.name);if(t.isDirectory())pM(r,i);else if(t.isFile())We(i,ye(r));else throw new Error(`offer upgrade: ${r} is neither a file nor a directory \u2014 refusing to copy it`)}}s(pM,"copyTree");function mM(e){let n=j_(e.dir),{bundle:t,changes:r,refusals:i}=L_(n,e.answers);if(!e.write||i.length>0)return{dir:n.dir,changes:r,refusals:i,written:null};let o=n.dir;if(e.out!==void 0){if(o=z.resolve(e.out),Se(o)&&$r(o).length>0)throw new Error(`offer upgrade: --out ${o} is not empty \u2014 choose a fresh directory`);pM(n.dir,o)}return Tt({...t,dir:o}),{dir:n.dir,changes:r,refusals:i,written:o}}s(mM,"runUpgrade");var sc=class extends xe{static{s(this,"OfferUpgradeCommand")}static paths=[["offer","upgrade"]];static usage=T.Usage({category:"Offer",description:"Rewrite a bundle exported in an older format into the current one (offline; dry run unless --write)",details:`
10823
+ `)}let l=await SL(t,n,{publish:this.publish,publishStage:this.stage});return this.print(l,d=>d.steps.map(c=>({step:c.step,action:c.action,detail:c.detail??""}))),0}};var jd=class extends D{static{s(this,"OfferListCommand")}static paths=[["offer","list"]];static usage=T.Usage({category:"Offer",description:"List offers (manifests) + publish state for a tenant"});all=p.Boolean("--all",!1,{description:"Include archived (soft-deleted) offers"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await n.query(x.workflow.listManifests,{client:t}),i=this.all?r:r.filter(o=>o.retiredAt==null);return this.print(i,o=>o.map(a=>({slug:a.offerKey,state:a.retiredAt!=null?"archived":a.isPublished?"published":"draft",sortOrder:a.sortOrder?.toString()??"-",label:_e(a.label)}))),0}},Bd=class extends nn{static{s(this,"OfferStatusCommand")}static paths=[["offer","status"]];static usage=T.Usage({category:"Offer",description:"Publish state + whether program/pedagogy links resolve (applyable?)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),i=(await n.query(x.workflow.listManifests,{client:t})).find(d=>d.offerKey===this.offerSlug);if(!i)throw new Error(`offer: no offer "${this.offerSlug}" in "${t}"`);let o=await n.query(x.workflow.getOfferPublishState,{client:t,offerKey:this.offerSlug}),a=s(d=>d==null?"-":`v${d}`,"rev"),l={manifest:i.isPublished?"published":"draft",workflow:i.workflowDefinitionId?"bound":"MISSING",pedagogy:i.pedagogy?_e(i.pedagogy.unitName):"UNLINKED (not applyable)",draft:a(o?.draftRevision),internal:a(o?.internalHeadRevision),live:a(o?.externalHeadRevision),publish:o===null?"-":o.draftDiffersFromExternal?"PENDING (draft is ahead of live)":"up to date"};return this.print(l,d=>[{field:"manifest",value:d.manifest},{field:"workflow",value:d.workflow},{field:"pedagogy",value:d.pedagogy},{field:"draft",value:d.draft},{field:"internal",value:d.internal},{field:"live",value:d.live},{field:"publish",value:d.publish}]),0}},e5={draft:"draft (editable)",internal:"internal (staged, testable)",published:"published (live)",archived:"archived"},Ud=class extends nn{static{s(this,"OfferVersionsCommand")}static paths=[["offer","versions"]];static usage=T.Usage({category:"Offer",description:"List an offer's versions (generations) \u2014 the id `applications start-test --version` takes",details:"Every generation of the offer family, newest first: the editable draft, an internally staged candidate, the live head and the archived history (still pinned by the applications started on it). `offerVersionId` is what `applications start-test --version` runs on; `workflowVersionId` opens the read-only graph of that generation.",examples:[["The versions of an offer","$0 offer versions --tenant test --slug grundschule-havelland"],["Test the staged candidate","$0 --env staging applications start-test --offer grundschule-havelland --run <run> --stage <stage> --applicant test@example.com --version <offerVersionId>"]]});async execute(){let n=await this.caller(),t=this.requireTenant(n),i=(await n.query(x.workflow.listManifests,{client:t})).find(a=>a.offerKey===this.offerSlug);if(!i)throw new Error(`offer versions: no offer "${this.offerSlug}" in "${t}"`);if(!i.workflowDefinitionId)throw new Error(`offer versions: "${this.offerSlug}" has no workflow yet \u2014 a draft offer has no generation to test`);let o=await n.query(x.workflow.listWorkflowVersions,{workflowDefinitionId:i.workflowDefinitionId});return this.print(o,a=>a.map(l=>({revision:`v${l.revision}`,state:e5[l.state],published:l.publishedAt===null?"\u2014":new Date(l.publishedAt).toISOString().slice(0,16).replace("T"," "),offerVersionId:l.offerVersionId,workflowVersionId:l.versionId}))),0}};var aM={de:"--title",en:"--title-en"},Vd=class extends nn{static{s(this,"OfferCreateCommand")}static paths=[["offer","create"]];static usage=T.Usage({category:"Offer",description:"Create a draft offer (manifest) \u2014 title (= program name) + optional unit"});offer=xa("New offer slug (identity key) (required)");title=p.String("--title",{required:!0,description:"Bare program name in German \u2014 no run/year or levels (those are separate; see `offer init --title`)"});titleEn=p.String("--title-en",{required:!0,description:"The same title in English (every name a reader sees has both)"});unit=p.String("--unit",{description:"Pedagogic unit (school) the offer belongs to \u2014 its config key"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=Hn({de:this.title,en:this.titleEn},"offer create",aM);if(await n.mutation(x.workflow.createManifest,{client:t,slug:this.offerSlug,label:r}),this.unit){let i=await st(n,t,this.offerSlug);await Bv(n,t,this.offerSlug,jv(i,this.unit))}return this.print({created:this.offerSlug,title:r,unit:this.unit??null},i=>[{key:"created",value:i.created},{key:"title",value:_e(i.title)},{key:"unit",value:i.unit??"\u2014"}]),0}},Gd=class extends nn{static{s(this,"OfferShowCommand")}static paths=[["offer","show"]];static usage=T.Usage({category:"Offer",description:"Full view of an offer: title, unit, levels, runs, capacity, state (incl. archived)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=new Map(i.stages.map(c=>[c.stageId,c.name])),a=new Map(i.runs.map(c=>[c.runId,c.name])),l=r.retiredAt!=null,d={slug:r.offerKey,title:r.label,sortOrder:r.sortOrder??null,state:l?"archived":r.isPublished?"published":"draft",unit:r.pedagogy?r.pedagogy.unitName:null,workflow:r.workflowDefinitionId?"bound":"MISSING",applyable:!!(r.workflowDefinitionId&&r.pedagogy&&!l),levels:i.stages.map(c=>({key:c.key,name:c.name,sequence:c.sequence,gradeLevel:c.gradeLevel??null,archived:c.archived})),runs:i.runs.map(c=>({key:c.key,name:c.name,status:c.status,isOpen:c.isOpen,startDate:c.startDate??null,endDate:c.endDate??null})),capacity:i.runStages.map(c=>({run:a.get(c.runId)??c.runId,level:o.get(c.stageId)??c.stageId,capacity:c.capacity,isOpen:c.isOpen}))};return this.print(d,c=>[{section:"offer",item:c.slug,detail:_e(c.title)},{section:"state",item:c.state,detail:`unit=${c.unit?_e(c.unit):"\u2014"} sortOrder=${c.sortOrder??"\u2014"} workflow=${c.workflow} applyable=${c.applyable}`},...c.levels.map(u=>({section:"level",item:_e(u.name),detail:`seq=${u.sequence}${u.gradeLevel!=null?` grade=${u.gradeLevel}`:""}${u.archived?" [archived]":""}`})),...c.runs.map(u=>({section:"run",item:_e(u.name),detail:`${u.status}${u.isOpen?" open":""}${u.startDate?` ${u.startDate}\u2192${u.endDate??"?"}`:""}`})),...c.capacity.map(u=>({section:"capacity",item:`${typeof u.run=="string"?u.run:_e(u.run)} \xD7 ${typeof u.level=="string"?u.level:_e(u.level)}`,detail:`${u.capacity??"\u221E"}${u.isOpen?" open":" closed"}`}))]),0}},zd=class extends nn{static{s(this,"OfferSetCommand")}static paths=[["offer","set"]];static usage=T.Usage({category:"Offer",description:"Update an offer's title and/or pedagogic unit"});title=p.String("--title",{description:"New bare offer title in German (offer_versions.label, the offer-title SoT) \u2014 no run/year or levels (those are separate entities)"});titleEn=p.String("--title-en",{description:"New offer title in English \u2014 required with --title: the English is never copied from the German, and a title without English is refused"});programName=p.String("--program-name",{description:"Rename the underlying master-data program in German (programs.name, staff master-data only \u2014 distinct from --title); needs --program-name-en"});programNameEn=p.String("--program-name-en",{description:"The program's name in English (with --program-name)"});unit=p.String("--unit",{description:"New pedagogic unit (school) \u2014 its config key"});sortOrder=p.String("--sort-order",{description:"Display order among the unit's offers (lower = first, non-negative number)"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.title===void 0&&this.titleEn===void 0&&this.programName===void 0&&this.programNameEn===void 0&&!this.unit&&this.sortOrder===void 0)throw new Error("offer set: pass --title/--title-en, --program-name/--program-name-en, --unit and/or --sort-order");let r=await Nn(n,t,this.offerSlug),i=[],o;if(this.sortOrder!==void 0&&(o=Number(this.sortOrder),!Number.isFinite(o)||o<0))throw new Error(`offer set: --sort-order must be a non-negative number, got "${this.sortOrder}"`);let a=Xt(r.label,{de:this.title,en:this.titleEn},"offer set",aM);if((a!==void 0||o!==void 0)&&(await n.mutation(x.workflow.createManifest,{client:t,slug:this.offerSlug,label:a??r.label,...o!==void 0?{sortOrder:o}:{}}),a!==void 0&&i.push(`title=${_e(a)}`),o!==void 0&&i.push(`sortOrder=${o}`)),this.programName!==void 0||this.programNameEn!==void 0){let l=Hn({de:this.programName,en:this.programNameEn},"offer set",{de:"--program-name",en:"--program-name-en"});await n.mutation(x.programAdmin.updateProgram,{client:t,offerKey:r.offerKey,name:l}),i.push(`programName=${_e(l)}`)}if(this.unit){let l=await st(n,t,r.offerKey);await Bv(n,t,r.offerKey,jv(l,this.unit)),i.push(`unit=${this.unit}`)}return this.print({slug:this.offerSlug,changes:i},l=>l.changes.map(d=>({change:d}))),0}},Wd=class extends nn{static{s(this,"OfferArchiveCommand")}static paths=[["offer","archive"]];static usage=T.Usage({category:"Offer",description:"Archive (soft-delete) an offer \u2014 `offer restore` brings it back, never orphans data"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);return await n.mutation(x.programAdmin.setManifestArchived,{client:t,offerKey:r.offerKey,archived:!0}),this.print({archived:this.offerSlug},i=>[{key:"archived (soft-deleted)",value:i.archived}]),0}},Yd=class extends nn{static{s(this,"OfferRestoreCommand")}static paths=[["offer","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived offer"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);return await n.mutation(x.programAdmin.setManifestArchived,{client:t,offerKey:r.offerKey,archived:!1}),this.print({restored:this.offerSlug},i=>[{key:"restored",value:i.restored}]),0}},Hd=class extends nn{static{s(this,"OfferDeleteCommand")}static paths=[["offer","delete"],["offer","hard-delete"]];static usage=T.Usage({category:"Offer",description:"HARD-delete an offer (manifest + versions + workflow + smartform + program + stages + runs) \u2014 irreversible, plan unless --confirm; refused while any application exists. To take an offer down reversibly use `offer archive`.",examples:[["Plan","$0 --env staging --tenant <slug> offer delete --offer <offer>"],["Delete","$0 --env staging --tenant <slug> offer delete --offer <offer> --confirm"]]});confirm=p.Boolean("--confirm",!1,{description:"Delete for good (without it, only the plan is printed)."});retiredYes=p.Boolean("--yes",!1,{hidden:!0});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug);if(!this.confirm){let o=await st(n,t,r.offerKey),a={offer:r.offerKey,title:r.label,levels:o.stages.length,runs:o.runs.length,deleted:!1};return this.print(a,l=>[{key:"would HARD-delete offer",value:`${l.offer} (${_e(l.title)}) \u2014 irreversible`},{key:"with",value:`${l.levels} level(s), ${l.runs} run(s), its versions, workflow and form`},{key:"refused when",value:"any application exists"},{key:"next",value:"re-run with --confirm \u2014 or `offer archive` to take it down reversibly"}]),0}let i=await n.mutation(x.programAdmin.hardDeleteOffer,{client:t,offerKey:r.offerKey});return this.print(i,o=>[{key:"hard-deleted offer",value:this.offerSlug},{key:"offerKey",value:o.deletedOfferKey},{key:"program",value:o.deletedProgramId??"(none)"},{key:"counts",value:JSON.stringify(o.counts)}]),0}};var lM={de:"--name",en:"--name-en"},Jd=class extends nn{static{s(this,"OfferRunAddCommand")}static paths=[["offer","run","add"]];static usage=T.Usage({category:"Offer",description:"Add a run (Schuljahr) to an offer"});name=p.String("--name",{required:!0,description:"Run name in German (e.g. Schuljahr 2026/27)"});nameEn=p.String("--name-en",{required:!0,description:"Run name in English (e.g. School year 2026/27)"});key=p.String("--key",{description:"Stable run key, as in bundle.yaml program.runs[].key (lowercase slug, e.g. 2026-27). Without it the key is derived from the German --name \u2014 and keeps that value after a rename"});start=p.String("--start",{description:"Start date (ISO, e.g. 2026-08-01)"});end=p.String("--end",{description:"End date (ISO)"});capacity=p.String("--capacity",{description:"Default seat capacity per level"});closed=p.Boolean("--closed",!1,{description:"Create closed (default: open)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=Yo("capacity",this.capacity),o=Hn({de:this.name,en:this.nameEn},"offer run add",lM);return await n.mutation(x.programAdmin.addProgramRun,{client:t,offerKey:r.offerKey,name:o,...this.key!==void 0?{key:this.key}:{},isOpen:!this.closed,...this.start?{startDate:this.start}:{},...this.end?{endDate:this.end}:{},...i!==void 0?{defaultCapacity:i}:{}}),this.print({added:o},a=>[{key:"run added",value:_e(a.added)}]),0}},Qd=class extends nn{static{s(this,"OfferRunSetCommand")}static paths=[["offer","run","set"]];static usage=T.Usage({category:"Offer",description:"Update a run: rename / dates"});run=p.String("--run",{required:!0,description:"Key of the run to update (bundle.yaml program.runs[].key)"});name=p.String("--name",{description:"New run name in German"});nameEn=p.String("--name-en",{description:"New run name in English"});start=p.String("--start",{description:"Start date (ISO)"});end=p.String("--end",{description:"End date (ISO)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=ba(i,this.run),a=i.runs.find(d=>d.runId===o),l=Xt(a.name,{de:this.name,en:this.nameEn},"offer run set",lM);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:o,...l!==void 0?{name:l}:{},...this.start?{startDate:this.start}:{},...this.end?{endDate:this.end}:{}}),this.print({updated:this.run},d=>[{key:"run updated",value:d.updated}]),0}},Zd=class extends nn{static{s(this,"OfferRunArchiveCommand")}static paths=[["offer","run","archive"]];static usage=T.Usage({category:"Offer",description:"Soft-delete (archive) a run \u2014 retired from the portal, restorable"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),status:"archived"}),this.print({archived:this.run},o=>[{key:"run archived",value:o.archived}]),0}},Xd=class extends nn{static{s(this,"OfferRunRestoreCommand")}static paths=[["offer","run","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived run"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramRun,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),status:"active"}),this.print({restored:this.run},o=>[{key:"run restored",value:o.restored}]),0}};var dM={de:"--name",en:"--name-en"},ec=class extends nn{static{s(this,"OfferLevelAddCommand")}static paths=[["offer","level","add"]];static usage=T.Usage({category:"Offer",description:"Add a level (Klassenstufe) to an offer"});name=p.String("--name",{required:!0,description:"Level name in German"});nameEn=p.String("--name-en",{required:!0,description:"Level name in English"});grade=p.String("--grade",{description:"Grade level (integer)"});key=p.String("--key",{description:"Stable level key, as in bundle.yaml program.stages[].key (lowercase slug). Without it the key is derived from the German --name \u2014 and keeps that value after a rename"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=Yo("grade",this.grade),o=Hn({de:this.name,en:this.nameEn},"offer level add",dM);return await n.mutation(x.programAdmin.addProgramStage,{client:t,offerKey:r.offerKey,name:o,...i!==void 0?{gradeLevel:i}:{},...this.key!==void 0?{key:this.key}:{}}),this.print({added:o},a=>[{key:"level added",value:_e(a.added)}]),0}},nc=class extends nn{static{s(this,"OfferLevelSetCommand")}static paths=[["offer","level","set"],["offer","level","rename"]];static usage=T.Usage({category:"Offer",description:"Change a level's name and/or grade"});level=p.String("--level",{required:!0,description:"Key of the level to update (bundle.yaml program.stages[].key)"});name=p.String("--name",{description:"New level name in German"});nameEn=p.String("--name-en",{description:"New level name in English"});grade=p.String("--grade",{description:"New grade level (integer)"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.name===void 0&&this.nameEn===void 0&&this.grade===void 0)throw new Error("offer level set: pass --name/--name-en and/or --grade");let r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=Yo("grade",this.grade),a=va(i,this.level),l=i.stages.find(c=>c.stageId===a),d=Xt(l.name,{de:this.name,en:this.nameEn},"offer level set",dM);return await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:a,...d!==void 0?{name:d}:{},...o!==void 0?{gradeLevel:o}:{}}),this.print({updated:this.level},c=>[{key:"level updated",value:c.updated}]),0}},tc=class extends nn{static{s(this,"OfferLevelArchiveCommand")}static paths=[["offer","level","archive"],["offer","level","remove"]];static usage=T.Usage({category:"Offer",description:"Soft-delete (archive) a level \u2014 retired from the portal, restorable. Refused while an active application sits on the level"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),{warnings:o}=await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:va(i,this.level),archived:!0});return this.print({removed:this.level,warnings:o},a=>[{key:"level removed (soft)",value:a.removed},...a.warnings.map(l=>({key:"warning",value:l}))]),0}},rc=class extends nn{static{s(this,"OfferLevelRestoreCommand")}static paths=[["offer","level","restore"]];static usage=T.Usage({category:"Offer",description:"Restore an archived level"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey);return await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:r.offerKey,stageId:va(i,this.level),archived:!1}),this.print({restored:this.level},o=>[{key:"level restored",value:o.restored}]),0}},ic=class extends nn{static{s(this,"OfferLevelMoveCommand")}static paths=[["offer","level","move"]];static usage=T.Usage({category:"Offer",description:"Reorder a level among the offer's levels (--before|--after another level)"});level=p.String("--level",{required:!0,description:"Key of the level to move"});before=p.String("--before",{description:"Place before the level with this key"});after=p.String("--after",{description:"Place after the level with this key"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.before===void 0==(this.after===void 0))throw new Error("offer level move: pass exactly one of --before <level> / --after <level>");let r=this.before??this.after;if(r===this.level)throw new Error("offer level move: --before/--after anchor cannot be the level itself");let i=await Nn(n,t,this.offerSlug),o=await st(n,t,i.offerKey);if(o.programKey===null)throw new Error("offer level move: the offer has no program yet");let a=o.programKey,l=o.stages.map(f=>({stageId:f.stageId,key:jr(a,f.key),name:f.name})),d=l.find(f=>f.key===this.level);if(!d)throw new Error(`offer level move: level "${this.level}" not found. Available keys: ${l.map(f=>f.key).join(", ")||"(none)"}`);if(!l.some(f=>f.key===r))throw new Error(`offer level move: anchor level "${r}" not found. Available keys: ${l.map(f=>f.key).join(", ")}`);let c=l.filter(f=>f.key!==this.level),u=c.findIndex(f=>f.key===r);c.splice(this.before!==void 0?u:u+1,0,d);for(let f=0;f<c.length;f++)await n.mutation(x.programAdmin.updateProgramStage,{client:t,offerKey:i.offerKey,stageId:c[f].stageId,sequence:f+1});return this.print({moved:this.level,order:c.map(f=>f.key)},f=>[{key:"level moved",value:f.moved},{key:"new order",value:f.order.join(" \u2192 ")}]),0}};var oc=class extends nn{static{s(this,"OfferCapacitySetCommand")}static paths=[["offer","capacity","set"]];static usage=T.Usage({category:"Offer",description:"Set seat capacity and/or open-state for one run \xD7 level cell"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});capacity=p.String("--capacity",{description:'Seat capacity (whole number) or "unlimited"'});open=p.Boolean("--open",!1,{description:"Open this cell"});close=p.Boolean("--close",!1,{description:"Close this cell"});async execute(){let n=await this.caller(),t=this.requireTenant(n);if(this.open&&this.close)throw new Error("offer capacity set: pass only one of --open / --close");let r=await Nn(n,t,this.offerSlug),i=await st(n,t,r.offerKey),o=this.capacity==="unlimited"?"unlimited":Yo("capacity",this.capacity),a=this.open?!0:this.close?!1:void 0;return await n.mutation(x.programAdmin.setRunStageCapacity,{client:t,offerKey:r.offerKey,runId:ba(i,this.run),stageId:va(i,this.level),...o!==void 0?{capacity:o}:{},...a!==void 0?{isOpen:a}:{}}),this.print({run:this.run,level:this.level},l=>[{key:"capacity set",value:`${l.run} \xD7 ${l.level}`}]),0}};function Gv(e,n,t){let r=e.indexOf("=");if(r<=0||r===e.length-1)throw new Error(`offer upgrade: ${n} takes ${t} (got "${e}")`);return[e.slice(0,r),e.slice(r+1)]}s(Gv,"splitPair");function n5(e,n){let t={waitlistOrder:e};if(!ny(t))throw new Error(`offer upgrade: ${n} takes <node>=<arrival|manual> (got "${e}")`);return t}s(n5,"parsePolicy");function Fm(e,n){if(e===void 0)return{};if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`offer upgrade: ${n} must be an object`);return e}s(Fm,"record");function cM(e){let n={},t={},r={},i=s((a,l,d,c)=>{if(Object.hasOwn(a,l)&&JSON.stringify(a[l])!==JSON.stringify(d))throw new Error(`offer upgrade: ${c} "${l}" is answered twice with different values`);a[l]=d},"put"),o=Fm(e.answersFile,"the answers file");for(let a of Object.keys(o))if(a!=="semantics"&&a!=="waitlistPolicy"&&a!=="payee")throw new Error(`offer upgrade: the answers file has an unknown key "${a}" (semantics | waitlistPolicy | payee)`);for(let[a,l]of Object.entries(Fm(o.semantics,"answers.semantics"))){if(typeof l!="string")throw new Error(`offer upgrade: answers.semantics["${a}"] must be a string`);i(n,a,l,"the outcome")}for(let[a,l]of Object.entries(Fm(o.waitlistPolicy,"answers.waitlistPolicy"))){if(!ny(l))throw new Error(`offer upgrade: answers.waitlistPolicy["${a}"] must be { waitlistOrder: arrival|manual }`);i(t,a,l,"the waitlist node")}for(let[a,l]of Object.entries(Fm(o.payee,"answers.payee"))){if(typeof l!="string"||l==="")throw new Error(`offer upgrade: answers.payee["${a}"] must be a Tr\xE4ger key`);i(r,a,l,"the payment node")}for(let a of e.semantic??[]){let[l,d]=Gv(a,"--semantic","<node>.<outcome>=<meaning>");if(!l.includes("."))throw new Error(`offer upgrade: --semantic takes <node>.<outcome>=<meaning> (got "${a}")`);i(n,l,d,"the outcome")}for(let a of e.waitlistPolicy??[]){let[l,d]=Gv(a,"--waitlist-policy","<node>=<arrival|manual>");i(t,l,n5(d,"--waitlist-policy"),"the waitlist node")}for(let a of e.payee??[]){let[l,d]=Gv(a,"--payee","<node>=<Tr\xE4ger key>");i(r,l,d,"the payment node")}return{semantics:n,waitlistPolicy:t,payee:r}}s(cM,"parseUpgradeAnswers");function uM(e){let n=e.candidates?.join("|")??"";switch(e.answer){case"semantic":return`--semantic ${e.answerKey}=<${n}>`;case"waitlistPolicy":return`--waitlist-policy ${e.answerKey}=<arrival|manual>`;case"payee":return`--payee ${e.answerKey}=<Tr\xE4ger key>`;case"edit":return"edit the file by hand"}}s(uM,"answerHint");function fM(e){let n=e.defaulted;if(n===void 0)return"-";switch(n.answer){case"semantic":return`--semantic ${n.answerKey}=${n.value}`;case"waitlistPolicy":return`--waitlist-policy ${n.answerKey}=${n.value}`;case"undeclaredBinding":return`${n.answerKey} deleted (publish refuses an undeclared input)`}}s(fM,"defaultedHint");function pM(e,n){Cn(n,{recursive:!0});for(let t of $r(e,{withFileTypes:!0})){let r=z.join(e,t.name),i=z.join(n,t.name);if(t.isDirectory())pM(r,i);else if(t.isFile())We(i,ye(r));else throw new Error(`offer upgrade: ${r} is neither a file nor a directory \u2014 refusing to copy it`)}}s(pM,"copyTree");function mM(e){let n=j_(e.dir),{bundle:t,changes:r,refusals:i}=L_(n,e.answers);if(!e.write||i.length>0)return{dir:n.dir,changes:r,refusals:i,written:null};let o=n.dir;if(e.out!==void 0){if(o=z.resolve(e.out),Se(o)&&$r(o).length>0)throw new Error(`offer upgrade: --out ${o} is not empty \u2014 choose a fresh directory`);pM(n.dir,o)}return Tt({...t,dir:o}),{dir:n.dir,changes:r,refusals:i,written:o}}s(mM,"runUpgrade");var sc=class extends xe{static{s(this,"OfferUpgradeCommand")}static paths=[["offer","upgrade"]];static usage=T.Usage({category:"Offer",description:"Rewrite a bundle exported in an older format into the current one (offline; dry run unless --write)",details:`
10819
10824
  Prints every change. Where the old format left a value to a code
10820
10825
  default, the upgrade writes the value the process ran with and prints it
10821
10826
  as DEFAULT with the flag that would set it (an outcome without a known
@@ -10825,7 +10830,7 @@ Platzhalter: ${i||"\u2014"}
10825
10830
  payment without a payee, a malformed policy, a hand edit) it refuses that
10826
10831
  node and names the answer it needs. Nothing is written while a refusal is
10827
10832
  open.
10828
- `,examples:[["Dry run","$0 offer upgrade --dir ./offers/school/grundschule"],["Answer and write a copy","$0 offer upgrade --dir ./old --semantic invite.einladen=granted --waitlist-policy queue=manual --write --out ./new"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory (read)"});write=p.Boolean("--write",!1,{description:"Write the upgraded bundle (default: dry run)"});out=p.String("--out",{description:"With --write: write a full copy here (an empty directory) instead of over --dir"});semantic=p.Array("--semantic",{description:"<node>.<outcome>=<granted|rejected|waitlisted|other> \u2014 the meaning of an outcome the upgrade will not assume"});waitlistPolicy=p.Array("--waitlist-policy",{description:"<node>=<arrival|manual> \u2014 a waitlist's queue order"});payee=p.Array("--payee",{description:"<node>=<Tr\xE4ger key> \u2014 the payee of an online payment"});answers=p.String("--answers",{description:"JSON file { semantics, waitlistPolicy, payee } with the same answers"});async execute(){if(this.out!==void 0&&!this.write)throw new Error("offer upgrade: --out needs --write");let n=cM({...this.semantic?{semantic:this.semantic}:{},...this.waitlistPolicy?{waitlistPolicy:this.waitlistPolicy}:{},...this.payee?{payee:this.payee}:{},...this.answers?{answersFile:JSON.parse(ye(this.answers,"utf8"))}:{}}),t=mM({dir:this.dir,answers:n,write:this.write,...this.out!==void 0?{out:this.out}:{}}),r=t.changes.filter(l=>l.defaulted!==void 0).length,i=r>0?` (${r} answer${r===1?"":"s"} set to the former behaviour \u2014 see DEFAULT)`:"",a=`${t.refusals.length>0?`${t.refusals.length} refused \u2014 nothing written; answer them and run again`:t.written!==null?`written to ${t.written}; next: offer validate --dir ${t.written}`:t.changes.length===0?"already current \u2014 nothing to do":"dry run \u2014 nothing written; run again with --write"}${i}`;return this.print({...t,status:a},l=>[...l.changes.map(d=>({kind:d.defaulted!==void 0?"DEFAULT":"change",file:d.file,node:d.nodeId??"-",message:d.message,answer:fM(d)})),...l.refusals.map(d=>({kind:"REFUSED",file:d.file,node:d.nodeId??"-",message:`[${d.code}] ${d.message}`,answer:uM(d)})),{kind:"status",file:"-",node:"-",message:l.status,answer:"-"}]),t.refusals.length>0?1:0}};var ac=class extends D{static{s(this,"OfferUnitCreateCommand")}static paths=[["offer","unit","create"]];static usage=T.Usage({category:"Offer",description:"Create a pedagogic unit (school) \u2014 makes it applyable: creates the unit + its pedagogy bridge"});name=p.String("--name",{required:!0,description:"Unit (school) name in German"});nameEn=p.String("--name-en",{required:!0,description:"Unit (school) name in English"});kind=p.String("--kind",{description:`Unit kind (default school): ${Ft.join("|")}`});parent=p.String("--parent",{description:"Parent unit (nest under it) \u2014 its id, config key or URL slug"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=this.kind??"school";Co(r,Ft,"--kind");let i;this.parent&&(i=Mt(await $t(n,t),this.parent,"unit").node.id);let{id:o}=await n.mutation(x.masterData.createUnit,{client:t,name:Hn({de:this.name,en:this.nameEn},"offer unit create",{de:"--name",en:"--name-en"}),kind:r,...i?{parentUnitId:i}:{}}),{pedagogyUnitId:a,created:l}=await n.mutation(x.programAdmin.ensurePedagogyUnit,{client:t,unitId:o});return this.print({unitId:o,pedagogyUnitId:a,created:l},d=>[{key:"unit created",value:d.unitId},{key:"pedagogyUnit",value:d.pedagogyUnitId},{key:"applyable",value:"yes"}]),0}},lc=class extends D{static{s(this,"OfferUnitEnsurePedagogyCommand")}static paths=[["offer","unit","ensure-pedagogy"]];static usage=T.Usage({category:"Offer",description:"Mark an EXISTING unit as a pedagogy unit (add its bridge) \u2014 idempotent"});unit=p.String("--unit",{required:!0,description:"Unit to upgrade \u2014 its id, config key or URL slug"});async execute(){let n=await this.caller(),t=this.requireTenant(n),{node:r}=Mt(await $t(n,t),this.unit,"unit"),{pedagogyUnitId:i,created:o}=await n.mutation(x.programAdmin.ensurePedagogyUnit,{client:t,unitId:r.id});return this.print({pedagogyUnitId:i,created:o},a=>[{key:"pedagogyUnit",value:a.pedagogyUnitId},{key:o?"created":"already a pedagogy unit",value:"yes"}]),0}},dc=class extends wd{static{s(this,"OfferUnitDeleteCommand")}static paths=[["offer","unit","delete"]];unit=p.String("--unit",{required:!0,description:"Unit to delete \u2014 its id, config key or URL slug"});async execute(){return an(this.context.stderr,"offer unit delete --unit <unit>","org unit delete <unit>"),await this.deleteUnit(this.unit)}};var hM=[Fd,Dd,Ld,sc,Md,qd,Kd,jd,Bd,Ud,Vd,Gd,zd,Wd,Yd,Hd,Jd,Qd,Zd,Xd,ec,nc,ic,tc,rc,oc,ac,lc,dc];function gM(e,n){if(rr(e,n.id))throw new Error(`offer form section add: section "${n.id}" already exists`);Jn(n.visibleIf,`section "${n.id}" visibleIf`);let t=`offer form section add: section "${n.id}"`,r=Vo(n.notice,n.noticeEn,t,"--notice"),i={id:ya(n.id),label:un(n.label,n.labelEn,t),fields:[],...n.visibleIf?{visibleIf:n.visibleIf}:{},...r?{notice:r}:{}};if(n.parentId){let o=rr(e,n.parentId);if(!o)throw new Error(`offer form section add: parent section "${n.parentId}" not found`);o.subsections=[...o.subsections??[],i]}else e.sections.push(i)}s(gM,"addSection");function yM(e,n){let t=rr(e,n.id);if(!t)throw new Error(`offer form section set: section "${n.id}" not found`);if(Jn(n.visibleIf,`section "${n.id}" visibleIf`),wn(t,"label",{de:n.label,en:n.labelEn},`offer form section set: section "${n.id}"`),wn(t,"notice",{de:n.notice,en:n.noticeEn,clearable:!0},`offer form section set: section "${n.id}" notice`),n.visibleIf!==void 0&&(n.visibleIf===""?delete t.visibleIf:t.visibleIf=n.visibleIf),n.visibleTo!==void 0){let r=t;if(n.visibleTo==="")delete r.visibleTo;else{let i=n.visibleTo.split(",").map(o=>o.trim());if(i.some(o=>o===""))throw new Error(`offer form section set: --visible-to "${n.visibleTo}" has an empty key`);r.visibleTo=i}}if(n.parentId!==void 0&&t3(e,n.id,n.parentId),n.label===void 0&&n.labelEn===void 0&&n.visibleIf===void 0&&n.visibleTo===void 0&&n.parentId===void 0&&n.notice===void 0&&n.noticeEn===void 0)throw new Error("offer form section set: nothing to change \u2014 pass --label/--label-en/--visible-if/--visible-to/--parent/--notice")}s(yM,"setSection");function wM(e,n){return e.id===n?!0:e.subsections?.some(t=>wM(t,n))??!1}s(wM,"isSelfOrDescendant");function kM(e,n){let t=s(i=>{let o=i.findIndex(a=>a.id===n);if(o>=0)return i.splice(o,1)[0];for(let a of i)if(a.subsections){let l=t(a.subsections);if(l)return l}},"removeFrom"),r=t(e.sections);if(!r)throw new Error(`offer form: section "${n}" not found`);return r}s(kM,"detachSection");function t3(e,n,t){let r=rr(e,n);if(!r)throw new Error(`offer form section set: section "${n}" not found`);if(t!==""){if(!rr(e,t))throw new Error(`offer form section set: parent section "${t}" not found`);if(wM(r,t))throw new Error(`offer form section set: cannot reparent "${n}" under "${t}" \u2014 that would create a cycle`)}let i=kM(e,n);if(t==="")e.sections.push(i);else{let o=rr(e,t);o.subsections=[...o.subsections??[],i]}}s(t3,"reparentSection");function bM(e,n){let t=kM(e,n),r=[],i=s(o=>{o.fields.forEach(a=>r.push(a.key)),o.subsections?.forEach(a=>i(a))},"collect");return i(t),r}s(bM,"removeSection");function vM(e,n,t,r){if(e==="enum"){if(n&&t)throw new Error(`${r}: pass only one of --enum, --enum-list-key (enum options come from exactly one source)`)}else if(n||t)throw new Error(`${r}: --enum/--enum-list-key only valid on an enum field`)}s(vM,"validateEnumChoice");function r3(e,n,t,r){if(!(e===void 0&&n===void 0&&t===void 0&&r===void 0))return{...e&&e.length?{mimeType:e}:{},...n!==void 0?{maxSize:n}:{},...t!==void 0?{multiple:t}:{},...r!==void 0?{minFiles:r}:{}}}s(r3,"buildDocRef");function xM(e,n,t,r){let i=n===void 0&&t===void 0?{de:"Erkl\xE4rung",en:"Declaration"}:un(n??"",t,r,"--declaration-label");return{url:e,filename:i.de,mimeType:"text/html",label:i,renderAs:"inlineLink"}}s(xM,"declarationAttachment");function SM(e,n){if(e!=="yesNo")throw new Error(`${n}: --presentation must be "yesNo" (or "" to clear), got "${e}"`)}s(SM,"validatePresentation");function AM(e,n){if(!xr.includes(n.type))throw new Error(`offer form field add: unknown --type "${n.type}" (one of: ${xr.join(", ")})`);let t=rr(e,n.section);if(!t)throw new Error(`offer form field add: section "${n.section}" not found`);if(zo(e).has(n.key))throw new Error(`offer form field add: field key "${n.key}" already exists in this form`);if(n.type==="enum"&&!n.enum&&!n.enumListKey)throw new Error(`offer form field add: enum field "${n.key}" needs --enum a,b,c or --enum-list-key <list>`);if(n.multiple&&n.type!=="enum")throw new Error("offer form field add: --multiple only valid on an enum field");vM(n.type,n.enum,n.enumListKey,"offer form field add"),n.presentation!==void 0&&SM(n.presentation,"offer form field add");let r=r3(n.docMime,n.docMaxSize,n.docMultiple,n.docMinFiles);if(r&&n.type!=="docRef")throw new Error("offer form field add: --doc-mime/--doc-max-size/--doc-multiple/--doc-min-files only valid with --type docRef");let i=`offer form field add: field "${n.key}"`,o=n.label===void 0&&n.labelEn===void 0?{de:n.key,en:n.key}:un(n.label??"",n.labelEn,i),a=Vo(n.placeholder,n.placeholderEn,i,"--placeholder"),l=Vo(n.help,n.helpEn,i,"--help-text"),d=Vo(n.notice,n.noticeEn,i,"--notice"),c={key:ot(n.key),label:o,kind:"control",type:n.type,...n.required?{required:!0}:{},...n.reviewRequired?{reviewRequired:!0}:{},...n.bucket?{bucket:n.bucket}:{},...n.enum?{enumOptions:n.enum}:{},...n.enumListKey?{enumListKey:n.enumListKey}:{},...n.multiple?{multiple:!0}:{},...n.presentation?{presentation:n.presentation}:{},...a?{placeholder:a}:{},...l?{helpText:l}:{},...d?{notice:d}:{},...r?{docRefConstraints:r}:{},...n.consentTextKey?{consentTextKey:n.consentTextKey}:{},...n.consentVersion?{consentVersion:n.consentVersion}:{},...n.declarationUrl?{attachments:[xM(n.declarationUrl,n.declarationLabel,n.declarationLabelEn,`${i} declaration`)]}:{}};t.fields.push(c),n.persist!==void 0&&zv(e,{key:n.key,...n.persist})}s(AM,"addField");function zv(e,n){let t=`offer form field: field "${n.key}"`,r=Go(e,n.key);if(!r)throw new Error(`${t} not found (only a top-level section field can be persisted here)`);let i=r.field,o=e.effects??=[],a=s(u=>u.kind==="fieldMap","isFieldMap"),l=new Set;for(let u of o.filter(a)){let f=u.mappings.length;u.mappings=u.mappings.filter(m=>m.from!==n.key),f>0&&u.mappings.length===0&&l.add(u.id)}let d=s(()=>{e.effects=o.filter(u=>!(a(u)&&l.has(u.id)&&u.mappings.length===0))},"dropEmptied");if(n.mapsTo===""){d(),i.kind="control";return}if(n.fieldMap===void 0)throw new Error(`${t}: --maps-to needs --fieldmap <effectId> (the fieldMap effect that carries the mapping)`);let c=o.find(u=>u.id===n.fieldMap);if(c===void 0){if(n.target===void 0)throw new Error(`${t}: fieldMap effect "${n.fieldMap}" does not exist \u2014 pass --target <$partyEffect> to create it`);c={id:n.fieldMap,kind:"fieldMap",target:n.target,mappings:[]},o.push(c)}if(!a(c))throw new Error(`${t}: effect "${n.fieldMap}" is a ${String(c.kind)} effect, not a fieldMap`);if(n.target!==void 0&&c.target!==n.target)throw new Error(`${t}: fieldMap "${n.fieldMap}" writes ${c.target}, not ${n.target}`);c.mappings=[...c.mappings,{from:n.key,to:n.mapsTo}],d(),i.kind="cf_value"}s(zv,"persistField");function i3(e,n,t){if(!xr.includes(n))throw new Error(`offer form field set: unknown --type "${n}" (one of: ${xr.join(", ")})`);let r=bm[e],i=bm[n];if(r!==i)throw new Error(`offer form field set: field "${t}" is ${e} (${r}); ${n} (${i}) stores a different value \u2014 add a new field instead`);return n}s(i3,"sameDatumType");function EM(e,n){let t=Go(e,n.key);if(!t)throw new Error(`offer form field set: field "${n.key}" not found`);Jn(n.visibleIf,`field "${n.key}" visibleIf`),Jn(n.requiredIf,`field "${n.key}" requiredIf`),Jn(n.defaultValue,`field "${n.key}" defaultValue`),Jn(n.disabledIf,`field "${n.key}" disabledIf`);let r=t.field;n.type!==void 0&&(r.type=i3(String(r.type),n.type,n.key));let i=String(r.type),o=`offer form field set: field "${n.key}"`;wn(r,"label",{de:n.label,en:n.labelEn},o),wn(r,"placeholder",{de:n.placeholder,en:n.placeholderEn,clearable:!0},`${o} placeholder`),wn(r,"helpText",{de:n.helpText,en:n.helpTextEn,clearable:!0},`${o} help text`),wn(r,"notice",{de:n.notice,en:n.noticeEn,clearable:!0},`${o} notice`),n.required!==void 0&&(r.required=n.required),n.reviewRequired===!0?r.reviewRequired=!0:n.reviewRequired===!1&&delete r.reviewRequired;let a=s((l,d)=>{let c=n[l];c!==void 0&&(c===""?delete r[d]:r[d]=c)},"expr");if(a("visibleIf","visibleIf"),a("requiredIf","requiredIf"),a("defaultValue","defaultValue"),a("disabledIf","disabledIf"),a("bucket","bucket"),a("consentTextKey","consentTextKey"),a("consentVersion","consentVersion"),(n.enum!==void 0||n.enumListKey!==void 0)&&(vM(i,n.enum,n.enumListKey,"offer form field set"),n.enum!==void 0&&(n.enum.length?r.enumOptions=n.enum:delete r.enumOptions,delete r.enumListKey),n.enumListKey!==void 0&&(n.enumListKey===""?delete r.enumListKey:(r.enumListKey=n.enumListKey,delete r.enumOptions,delete r.enumOptionLabels))),n.multiple!==void 0){if(i!=="enum")throw new Error("offer form field set: --multiple only valid on an enum field");n.multiple?r.multiple=!0:delete r.multiple}if(n.presentation!==void 0&&(n.presentation===""?delete r.presentation:(SM(n.presentation,"offer form field set"),r.presentation=n.presentation)),n.requiredFor!==void 0&&(n.requiredFor.length?r.requiredFor=n.requiredFor.map(l=>Wi(l)):delete r.requiredFor),n.docMime!==void 0||n.docMaxSize!==void 0||n.docMultiple!==void 0||n.docMinFiles!==void 0){if(i!=="docRef")throw new Error("offer form field set: --doc-mime/--doc-max-size/--doc-multiple/--doc-min-files only valid on a docRef field");let d={...r.docRefConstraints??{}};n.docMime!==void 0&&(n.docMime.length?d.mimeType=n.docMime:delete d.mimeType),n.docMaxSize!==void 0&&(d.maxSize=n.docMaxSize),n.docMultiple!==void 0&&(d.multiple=n.docMultiple),n.docMinFiles===null?delete d.minFiles:n.docMinFiles!==void 0&&(d.minFiles=n.docMinFiles),Object.keys(d).length?r.docRefConstraints=d:delete r.docRefConstraints}if(n.declarationUrl!==void 0){let l=Array.isArray(r.attachments)?r.attachments:[],d=l.filter(c=>c.renderAs!=="inlineLink");if(n.declarationUrl==="")d.length?r.attachments=d:delete r.attachments;else{let c=l.find(u=>u.renderAs==="inlineLink");if(c===void 0)d.push(xM(n.declarationUrl,n.declarationLabel,n.declarationLabelEn,`${o} declaration`));else{let u={...c,url:n.declarationUrl};wn(u,"label",{de:n.declarationLabel,en:n.declarationLabelEn},`offer form field set: field "${n.key}" declaration`),u.filename=u.label.de,d.push(u)}r.attachments=d}}}s(EM,"setField");function TM(e,n,t,r,i){if(t.kind==="top"){e.unshift(n);return}if(t.kind==="bottom"){e.push(n);return}let o=e.findIndex(a=>r(a)===t.anchor);if(o<0)throw new Error(`${i}: anchor "${t.anchor}" not found among siblings`);e.splice(t.kind==="before"?o:o+1,0,n)}s(TM,"spliceAt");function $M(e,n,t,r){let i=Go(e,n);if(!i)throw new Error(`offer form field move: field "${n}" not found`);if((t.kind==="before"||t.kind==="after")&&t.anchor===n)throw new Error("offer form field move: --before/--after anchor cannot be the field itself");let o=r===void 0?i.section:rr(e,r);if(!o)throw new Error(`offer form field move: section "${r}" not found`);let a=o.fields;if((t.kind==="before"||t.kind==="after")&&!a.some(d=>d.key===t.anchor))throw new Error(`offer form field move: anchor "${t.anchor}" not found in section "${o.id}"`);let[l]=i.section.fields.splice(i.index,1);TM(a,l,t,d=>d.key,"offer form field move")}s($M,"moveField");function RM(e,n,t){if((t.kind==="before"||t.kind==="after")&&t.anchor===n)throw new Error("offer form section move: --before/--after anchor cannot be the section itself");let r=s(l=>{if(l.some(d=>d.id===n))return l;for(let d of l)if(d.subsections){let c=r(d.subsections);if(c)return c}},"findContainer"),i=r(e.sections);if(!i)throw new Error(`offer form section move: section "${n}" not found`);let o=i.findIndex(l=>l.id===n),[a]=i.splice(o,1);TM(i,a,t,l=>l.id,"offer form section move")}s(RM,"moveSection");function IM(e,n){let t=Go(e,n);if(!t)throw new Error(`offer form field rm: field "${n}" not found`);return t.section.fields.splice(t.index,1),n}s(IM,"removeField");function OM(e,n){let t=Go(e,n.key);if(!t)throw new Error(`offer form field attach: field "${n.key}" not found`);if(!ea(n.fileKey))throw new Error(`offer form field attach: --file-key "${n.fileKey}" is not a valid key (a-z, 0-9, "-")`);let r=n.renderAs??"download";if(r==="inlineLink"&&!n.label)throw new Error("offer form field attach: --render inlineLink needs --label (the linked phrase in the field label)");let i=t.field,o=(i.attachments??[]).filter(a=>a.fileKey!==n.fileKey);o.push({fileKey:n.fileKey,...r==="inlineLink"?{renderAs:r}:{},...n.label?{label:un(n.label,n.labelEn,`offer form field attach: field "${n.key}"`)}:{}}),i.attachments=o}s(OM,"attachFile");function PM(e,n,t){let r=Go(e,n);if(!r)throw new Error(`offer form field detach: field "${n}" not found`);let i=r.field,o=(i.attachments??[]).filter(a=>a.fileKey!==t);if(o.length===(i.attachments??[]).length)throw new Error(`offer form field detach: field "${n}" does not attach file "${t}"`);o.length>0?i.attachments=o:delete i.attachments}s(PM,"detachFile");var _M=`--name-from is for organizations only: a person's name is its fieldMap onto first_name / last_name (offer form effect add --kind fieldMap --target <person> --map "<first-name-key>:first_name,<last-name-key>:last_name")`;function NM(e,n){let t=e,r=t.outcomes??(t.outcomes=[]);if(r.some(a=>a.id===n.id))throw new Error(`offer form outcome add: outcome "${n.id}" already exists`);Jn(n.when,`outcome "${n.id}" when`);let i=n.label===void 0&&n.labelEn===void 0?{de:n.id,en:n.id}:un(n.label??"",n.labelEn,`offer form outcome add: outcome "${n.id}"`),o={id:Wi(n.id),label:i,when:n.when,...n.blocking?{blocking:!0}:{},output:{...n.fields&&n.fields.length?{fields:n.fields.map(a=>({path:ot(a)}))}:{},...n.effectRefs&&n.effectRefs.length?{effectRefs:n.effectRefs.map(a=>({effect:a.effect,as:a.as}))}:{},includeForm:!0}};r.push(o)}s(NM,"addOutcome");function CM(e,n){let t=o3(e,n.id);if(!t)throw new Error(`offer form outcome set: outcome "${n.id}" not found`);if(Jn(n.when,`outcome "${n.id}" when`),n.when!==void 0&&(t.when=n.when),n.blocking!==void 0&&(t.blocking=n.blocking),wn(t,"label",{de:n.label,en:n.labelEn},`offer form outcome set: outcome "${n.id}"`),n.fields!==void 0||n.effectRefs!==void 0){let r=t.output??{includeForm:!0};n.fields!==void 0&&(n.fields.length?r.fields=n.fields.map(i=>({path:ot(i)})):delete r.fields),n.effectRefs!==void 0&&(n.effectRefs.length?r.effectRefs=n.effectRefs.map(i=>({effect:i.effect,as:i.as})):delete r.effectRefs),t.output=r}}s(CM,"setOutcome");function DM(e,n){let t=e,r=t.outcomes??[];if(!r.some(i=>i.id===n))throw new Error(`offer form outcome rm: outcome "${n}" not found`);t.outcomes=r.filter(i=>i.id!==n)}s(DM,"removeOutcome");function Yv(e,n){return e.effects.find(t=>t.id===n)}s(Yv,"findEffect");function o3(e,n){return e.outcomes?.find(t=>t.id===n)}s(o3,"findOutcome");function Sa(e){return e.startsWith("$")?e:`$${e}`}s(Sa,"asRef");function Wv(e,n){if(e!==void 0){if(!wa.includes(e))throw new Error(`offer form effect: unknown --identity "${e}" (one of: ${wa.join(", ")})`);if(e==="keyed"){if(!n||n.length===0)throw new Error("offer form effect: --identity keyed needs --identity-key-from <fieldKeys>");return{strategy:"keyed",keyFrom:n}}return{strategy:e}}}s(Wv,"buildIdentity");function FM(e,n){let t=e.effects;if(Yv(e,n.id))throw new Error(`offer form effect add: effect "${n.id}" already exists`);Jn(n.when,`effect "${n.id}" when`);let r={id:F0(n.id),...n.when?{when:n.when}:{}},i;switch(n.kind){case"person":{if(!n.bucket)throw new Error("offer form effect add: person needs --bucket");let o=n.policy??"auto-on-required-complete";if(!Yi.includes(o))throw new Error(`offer form effect add: unknown --policy "${o}" (one of: ${Yi.join(", ")})`);if(n.nameFrom!==void 0)throw new Error(_M);let a=Wv(n.identity,n.identityKeyFrom);i={...r,kind:"person",bucket:n.bucket,policy:o,...a?{identity:a}:{},...n.role?{role:n.role}:{}};break}case"organization":{if(!n.orgKind)throw new Error("offer form effect add: organization needs --org-kind");let o=Wv(n.identity,n.identityKeyFrom);i={...r,kind:"organization",orgKind:n.orgKind,...o?{identity:o}:{},...n.nameFrom?.length?{nameFrom:n.nameFrom.map(a=>ot(a))}:{},...n.role?{role:n.role}:{}};break}case"relationship":{if(!n.from||!n.to||!n.relKind)throw new Error("offer form effect add: relationship needs --from, --to and --rel-kind");i={...r,kind:"relationship",from:Sa(n.from),to:Sa(n.to),relKind:n.relKind};break}case"fieldMap":{if(!n.target||!n.mappings||n.mappings.length===0)throw new Error("offer form effect add: fieldMap needs --target and --map from:to,\u2026");i={...r,kind:"fieldMap",target:Sa(n.target),mappings:n.mappings};break}default:throw new Error(`offer form effect add: unknown --kind "${n.kind}" (one of: ${Pd.join(", ")})`)}t.push(i)}s(FM,"addEffect");function Sr(e,n,t,r){if(!n.includes(e))throw new Error(`offer form effect set: ${t} is only valid on a ${r} effect (this effect is "${e}")`)}s(Sr,"assertEffectKind");function LM(e,n){let t=Yv(e,n.id);if(!t)throw new Error(`offer form effect set: effect "${n.id}" not found`);let r=String(t.kind);if(Jn(n.when,`effect "${n.id}" when`),n.when!==void 0&&(n.when===""?delete t.when:t.when=n.when),n.role!==void 0&&(Sr(r,["person","organization"],"--role","person/organization"),n.role===""?delete t.role:t.role=n.role),n.policy!==void 0){if(Sr(r,["person"],"--policy","person"),!Yi.includes(n.policy))throw new Error(`offer form effect set: unknown --policy "${n.policy}" (one of: ${Yi.join(", ")})`);t.policy=n.policy}if(n.nameFrom!==void 0){if(r==="person")throw new Error(_M);Sr(r,["organization"],"--name-from","organization"),t.nameFrom=n.nameFrom.map(i=>ot(i))}if(n.bucket!==void 0&&(Sr(r,["person"],"--bucket","person"),t.bucket=n.bucket),n.identity!==void 0||n.identityKeyFrom!==void 0){Sr(r,["person","organization"],"--identity","person/organization");let i=n.identity??t.identity?.strategy;t.identity=Wv(i,n.identityKeyFrom)}if(n.orgKind!==void 0&&(Sr(r,["organization"],"--org-kind","organization"),t.orgKind=n.orgKind),n.from!==void 0&&(Sr(r,["relationship"],"--from","relationship"),t.from=Sa(n.from)),n.to!==void 0&&(Sr(r,["relationship"],"--to","relationship"),t.to=Sa(n.to)),n.relKind!==void 0&&(Sr(r,["relationship"],"--rel-kind","relationship"),t.relKind=n.relKind),n.target!==void 0&&(Sr(r,["fieldMap"],"--target","fieldMap"),t.target=Sa(n.target)),n.mappings!==void 0){if(Sr(r,["fieldMap"],"--map","fieldMap"),n.mappings.length===0)throw new Error("offer form effect set: --map cannot be empty for a fieldMap");t.mappings=n.mappings}}s(LM,"setEffect");function MM(e,n){let t=e;if(!Yv(e,n))throw new Error(`offer form effect rm: effect "${n}" not found`);t.effects=t.effects.filter(r=>r.id!==n)}s(MM,"removeEffect");function qM(e,n){let t=rr(e,n.section);if(!t)throw new Error(`offer form repeated add: section "${n.section}" not found`);let r=zo(e);if(r.has(n.key))throw new Error(`offer form repeated add: key "${n.key}" already exists in this form`);if(n.itemFields.length===0)throw new Error("offer form repeated add: needs --item-fields key:type,\u2026");for(let l of n.itemFields){if(!xr.includes(l.type))throw new Error(`offer form repeated add: item field "${l.key}" has unknown type "${l.type}" (one of: ${xr.join(", ")})`);if(r.has(l.key))throw new Error(`offer form repeated add: item field key "${l.key}" already exists in this form`)}Jn(n.itemVisibleIf,`repeated "${n.key}" itemVisibleIf`);let i=new Set(n.itemFields.map(l=>l.key));for(let l of n.uniqueBy??[])if(!i.has(l))throw new Error(`offer form repeated add: --unique-by "${l}" is not one of the item fields (${[...i].join(", ")})`);let o=n.label===void 0&&n.labelEn===void 0?{de:n.key,en:n.key}:un(n.label??"",n.labelEn,`offer form repeated add: repeated "${n.key}"`),a={key:ot(n.key),label:o,itemTemplate:n.itemFields.map(l=>({key:ot(l.key),label:{de:l.key,en:l.key},kind:"control",type:l.type})),...n.min!==void 0?{minItems:n.min}:{},...n.max!==void 0?{maxItems:n.max}:{},...n.itemVisibleIf?{itemVisibleIf:n.itemVisibleIf}:{},...n.uniqueBy?.length?{uniqueBy:n.uniqueBy}:{}};t.repeated=[...t.repeated??[],a]}s(qM,"addRepeated");function KM(e,n){for(let t of jt(e)){let r=(t.repeated??[]).findIndex(i=>i.key===n);if(r>=0)return{section:t,repeated:t.repeated[r],index:r}}}s(KM,"findRepeated");function jM(e,n){let t=KM(e,n.key);if(!t)throw new Error(`offer form repeated set: repeated field "${n.key}" not found`);Jn(n.itemVisibleIf,`repeated "${n.key}" itemVisibleIf`);let r=t.repeated;if(wn(r,"label",{de:n.label,en:n.labelEn},`offer form repeated set: repeated field "${n.key}"`),n.min!==void 0&&(n.min<0?delete r.minItems:r.minItems=n.min),n.max!==void 0&&(n.max<0?delete r.maxItems:r.maxItems=n.max),n.itemVisibleIf!==void 0&&(n.itemVisibleIf===""?delete r.itemVisibleIf:r.itemVisibleIf=n.itemVisibleIf),n.uniqueBy!==void 0)if(n.uniqueBy.length){let i=new Set(t.repeated.itemTemplate.map(o=>o.key));for(let o of n.uniqueBy)if(!i.has(o))throw new Error(`offer form repeated set: --unique-by "${o}" is not an item field (${[...i].join(", ")})`);r.uniqueBy=n.uniqueBy}else delete r.uniqueBy}s(jM,"setRepeated");function BM(e,n){let t=KM(e,n);if(!t)throw new Error(`offer form repeated rm: repeated field "${n}" not found`);return t.section.repeated.splice(t.index,1),n}s(BM,"removeRepeated");function UM(e,n){let t=rr(e,n.section);if(!t)throw new Error(`offer form computed add: section "${n.section}" not found`);if(zo(e).has(n.key))throw new Error(`offer form computed add: key "${n.key}" already exists in this form`);Jn(n.expression,`computed "${n.key}" expression`);let r={key:ot(n.key),expression:n.expression};t.computed=[...t.computed??[],r]}s(UM,"addComputed");function VM(e,n){for(let t of jt(e)){let r=(t.computed??[]).findIndex(i=>i.key===n);if(r>=0)return{section:t,index:r}}}s(VM,"findComputed");function GM(e,n){let t=VM(e,n.key);if(!t)throw new Error(`offer form computed set: computed field "${n.key}" not found`);Jn(n.expression,`computed "${n.key}" expression`),t.section.computed[t.index].expression=n.expression}s(GM,"setComputed");function zM(e,n){let t=VM(e,n);if(!t)throw new Error(`offer form computed rm: computed field "${n}" not found`);return t.section.computed.splice(t.index,1),n}s(zM,"removeComputed");function WM(e){let n=new Set(Pv(e));return _d(e).map(t=>{let r=Im(e,t),i=jt(r);return{slug:t,label:r.label,sections:i.length,fields:[...zo(r)].length,outcomes:(r.outcomes??[]).length,effects:(r.effects??[]).length,boundByNode:n.has(t)}})}s(WM,"listForms");function YM(e,n){let t=Im(e,n),r=[];for(let i of jt(t)){for(let o of i.fields){let a=[],l=o;for(let d of["visibleIf","requiredIf","disabledIf","defaultValue","requiredFor","bucket","docRefConstraints","consentTextKey"])l[d]!==void 0&&a.push(d==="docRefConstraints"?"docRef":d);l.enumOptions&&a.push("enum"),l.presentation!==void 0&&a.push(String(l.presentation)),r.push({section:i.id,key:o.key,type:o.type,required:o.required===!0,flags:a.join(",")})}for(let o of i.repeated??[])r.push({section:i.id,key:o.key,type:"repeated",required:(o.minItems??0)>0,flags:[`items:${o.itemTemplate.length}`,o.uniqueBy?.length?"uniqueBy":"",o.itemVisibleIf?"itemVisibleIf":""].filter(Boolean).join(",")});for(let o of i.computed??[])r.push({section:i.id,key:o.key,type:"computed",required:!1,flags:"expr"})}return{slug:n,label:t.label,fields:r,outcomes:(t.outcomes??[]).map(i=>({id:i.id,when:i.when})),effects:(t.effects??[]).map(i=>({id:i.id,kind:i.kind}))}}s(YM,"showForm");function cc(e){return e.testScenarios??[]}s(cc,"scenarios");function Lm(e,n,t){let r=cc(e).find(i=>i.id===n);if(!r){let i=cc(e).map(o=>o.id);throw new Error(`${t}: no scenario "${n}" (have: ${i.join(", ")||"none"})`)}return r}s(Lm,"findScenario");function s3(e){let n=new Map;for(let t of jt(e)){for(let r of t.fields)n.set(r.key,r);for(let r of t.groups??[])for(let i of r.fields)n.set(i.key,i)}return n}s(s3,"prefillableFields");function Hv(e,n,t){let r=s3(e),i={};for(let o of n){let a=o.indexOf("=");if(a<=0)throw new Error(`${t}: --prefill "${o}" must be key=value`);let l=o.slice(0,a),d=o.slice(a+1),c=r.get(l);if(c===void 0)throw new Error(`${t}: --prefill "${l}" is not a field of this form (repeated rows and addresses: --prefill-json)`);switch(c.type){case"boolean":if(d!=="true"&&d!=="false")throw new Error(`${t}: --prefill ${l} is a boolean field \u2014 use true or false`);i[l]=d==="true";break;case"consent":if(d!=="true")throw new Error(`${t}: --prefill ${l} is a consent \u2014 only true (leave it out for "not given")`);i[l]=!0;break;case"enum":i[l]=c.multiple?d.split(",").map(u=>u.trim()).filter(u=>u.length>0):d;break;case"address":throw new Error(`${t}: --prefill ${l} is an address \u2014 pass it with --prefill-json`);case"docRef":throw new Error(`${t}: --prefill ${l} is a file field \u2014 test mode stubs files itself, they are never prefilled`);default:i[l]=d}}return i}s(Hv,"parsePrefillPairs");function Aa(e,n,t){let r;try{r=JSON.parse(e)}catch(i){throw new Error(`${t}: ${n} is not valid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`${t}: ${n} must be a JSON object`);return r}s(Aa,"parseJsonObject");function HM(e,n){let t="offer form scenario add";if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(n.id))throw new Error(`${t}: --id "${n.id}" must be a kebab-case key (e.g. standard, mit-geschwistern)`);if(cc(e).some(d=>d.id===n.id))throw new Error(`${t}: scenario "${n.id}" already exists`);if(n.label.trim()==="")throw new Error(`${t}: --label cannot be empty`);let r=un(n.label,n.labelEn,t),i=Vo(n.description,n.descriptionEn,t,"--description"),o=n.from===void 0?void 0:structuredClone(Lm(e,n.from,t)),a=n.env??o?.env,l=e;(l.testScenarios??=[]).push({id:n.id,label:r,...i?{description:i}:{},prefill:{...o?.prefill??{},...n.prefill},...a!==void 0?{env:a}:{}})}s(HM,"addScenario");function JM(e,n){let t=`offer form scenario set: scenario "${n.id}"`,r=Lm(e,n.id,"offer form scenario set");if(n.prefillMerge!==void 0&&n.prefillReplace!==void 0)throw new Error(`${t}: pass --prefill (merge) or --prefill-json (replace), not both`);if(n.label==="")throw new Error(`${t}: --label cannot be empty`);wn(r,"label",{de:n.label,en:n.labelEn},t),wn(r,"description",{de:n.description,en:n.descriptionEn,clearable:!0},`${t} description`),n.prefillReplace!==void 0&&(r.prefill=n.prefillReplace),n.prefillMerge!==void 0&&(r.prefill={...r.prefill,...n.prefillMerge});for(let o of n.unset??[]){if(!(o in r.prefill))throw new Error(`${t}: --unset "${o}" is not in the prefill`);let a={...r.prefill};delete a[o],r.prefill=a}if(n.env===null?delete r.env:n.env!==void 0&&(r.env=n.env),![n.label,n.labelEn,n.description,n.descriptionEn,n.prefillMerge,n.prefillReplace,n.unset,n.env].some(o=>o!==void 0))throw new Error(`${t}: nothing to change \u2014 pass --label/--label-en/--description/--prefill/--prefill-json/--unset/--env-json`)}s(JM,"setScenario");function QM(e,n){Lm(e,n,"offer form scenario rm");let t=e;t.testScenarios=cc(e).filter(r=>r.id!==n),t.testScenarios.length===0&&delete t.testScenarios}s(QM,"removeScenario");function ZM(e,n){let t="offer form env set";for(let a of n.keys)if(!ws(a))throw new Error(`${t}: unknown environment key "${a}" (one of: ${ys.join(", ")})`);let r=new Set(n.keys),i=e;r.size===0?delete i.env:i.env=[...r];for(let[a,l]of Object.entries(n.samples??{})){let d=Object.keys(l).filter(u=>!r.has(u));if(d.length>0)throw new Error(`${t}: --sample ${a} samples ${d.join(", ")}, which --keys does not declare`);let c=Lm(e,a,t);c.env={...c.env??{},...l}}let o=[];for(let a of cc(e)){if(a.env===void 0)continue;let l=Object.fromEntries(Object.entries(a.env).filter(([d])=>r.has(d)));Object.keys(l).length!==Object.keys(a.env).length&&(o.push(a.id),Object.keys(l).length===0?delete a.env:a.env=l)}return o}s(ZM,"setEnv");function uc(e,n){let t;try{t=Rt(e)}catch(i){throw new Error(`${n}: validation threw \u2014 nothing written: ${kt(i)}`,{cause:i})}let r=t.filter(i=>i.severity==="error");if(r.length>0)throw new Error(`${n}: validation failed \u2014 nothing written:
10833
+ `,examples:[["Dry run","$0 offer upgrade --dir ./offers/school/grundschule"],["Answer and write a copy","$0 offer upgrade --dir ./old --semantic invite.einladen=granted --waitlist-policy queue=manual --write --out ./new"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory (read)"});write=p.Boolean("--write",!1,{description:"Write the upgraded bundle (default: dry run)"});out=p.String("--out",{description:"With --write: write a full copy here (an empty directory) instead of over --dir"});semantic=p.Array("--semantic",{description:"<node>.<outcome>=<granted|rejected|waitlisted|other> \u2014 the meaning of an outcome the upgrade will not assume"});waitlistPolicy=p.Array("--waitlist-policy",{description:"<node>=<arrival|manual> \u2014 a waitlist's queue order"});payee=p.Array("--payee",{description:"<node>=<Tr\xE4ger key> \u2014 the payee of an online payment"});answers=p.String("--answers",{description:"JSON file { semantics, waitlistPolicy, payee } with the same answers"});async execute(){if(this.out!==void 0&&!this.write)throw new Error("offer upgrade: --out needs --write");let n=cM({...this.semantic?{semantic:this.semantic}:{},...this.waitlistPolicy?{waitlistPolicy:this.waitlistPolicy}:{},...this.payee?{payee:this.payee}:{},...this.answers?{answersFile:JSON.parse(ye(this.answers,"utf8"))}:{}}),t=mM({dir:this.dir,answers:n,write:this.write,...this.out!==void 0?{out:this.out}:{}}),r=t.changes.filter(l=>l.defaulted!==void 0).length,i=r>0?` (${r} answer${r===1?"":"s"} set to the former behaviour \u2014 see DEFAULT)`:"",a=`${t.refusals.length>0?`${t.refusals.length} refused \u2014 nothing written; answer them and run again`:t.written!==null?`written to ${t.written}; next: offer validate --dir ${t.written}`:t.changes.length===0?"already current \u2014 nothing to do":"dry run \u2014 nothing written; run again with --write"}${i}`;return this.print({...t,status:a},l=>[...l.changes.map(d=>({kind:d.defaulted!==void 0?"DEFAULT":"change",file:d.file,node:d.nodeId??"-",message:d.message,answer:fM(d)})),...l.refusals.map(d=>({kind:"REFUSED",file:d.file,node:d.nodeId??"-",message:`[${d.code}] ${d.message}`,answer:uM(d)})),{kind:"status",file:"-",node:"-",message:l.status,answer:"-"}]),t.refusals.length>0?1:0}};var ac=class extends D{static{s(this,"OfferUnitCreateCommand")}static paths=[["offer","unit","create"]];static usage=T.Usage({category:"Offer",description:"Create a pedagogic unit (school) \u2014 makes it applyable: creates the unit + its pedagogy bridge"});name=p.String("--name",{required:!0,description:"Unit (school) name in German"});nameEn=p.String("--name-en",{required:!0,description:"Unit (school) name in English"});kind=p.String("--kind",{description:`Unit kind (default school): ${Ft.join("|")}`});parent=p.String("--parent",{description:"Parent unit (nest under it) \u2014 its id, config key or URL slug"});async execute(){let n=await this.caller(),t=this.requireTenant(n),r=this.kind??"school";Co(r,Ft,"--kind");let i;this.parent&&(i=Mt(await $t(n,t),this.parent,"unit").node.id);let{id:o}=await n.mutation(x.masterData.createUnit,{client:t,name:Hn({de:this.name,en:this.nameEn},"offer unit create",{de:"--name",en:"--name-en"}),kind:r,...i?{parentUnitId:i}:{}}),{pedagogyUnitId:a,created:l}=await n.mutation(x.programAdmin.ensurePedagogyUnit,{client:t,unitId:o});return this.print({unitId:o,pedagogyUnitId:a,created:l},d=>[{key:"unit created",value:d.unitId},{key:"pedagogyUnit",value:d.pedagogyUnitId},{key:"applyable",value:"yes"}]),0}},lc=class extends D{static{s(this,"OfferUnitEnsurePedagogyCommand")}static paths=[["offer","unit","ensure-pedagogy"]];static usage=T.Usage({category:"Offer",description:"Mark an EXISTING unit as a pedagogy unit (add its bridge) \u2014 idempotent"});unit=p.String("--unit",{required:!0,description:"Unit to upgrade \u2014 its id, config key or URL slug"});async execute(){let n=await this.caller(),t=this.requireTenant(n),{node:r}=Mt(await $t(n,t),this.unit,"unit"),{pedagogyUnitId:i,created:o}=await n.mutation(x.programAdmin.ensurePedagogyUnit,{client:t,unitId:r.id});return this.print({pedagogyUnitId:i,created:o},a=>[{key:"pedagogyUnit",value:a.pedagogyUnitId},{key:o?"created":"already a pedagogy unit",value:"yes"}]),0}},dc=class extends wd{static{s(this,"OfferUnitDeleteCommand")}static paths=[["offer","unit","delete"]];unit=p.String("--unit",{required:!0,description:"Unit to delete \u2014 its id, config key or URL slug"});async execute(){return an(this.context.stderr,"offer unit delete --unit <unit>","org unit delete <unit>"),await this.deleteUnit(this.unit)}};var hM=[Fd,Dd,Ld,sc,Md,qd,Kd,jd,Bd,Ud,Vd,Gd,zd,Wd,Yd,Hd,Jd,Qd,Zd,Xd,ec,nc,ic,tc,rc,oc,ac,lc,dc];function gM(e,n){if(rr(e,n.id))throw new Error(`offer form section add: section "${n.id}" already exists`);Jn(n.visibleIf,`section "${n.id}" visibleIf`);let t=`offer form section add: section "${n.id}"`,r=Vo(n.notice,n.noticeEn,t,"--notice"),i={id:ya(n.id),label:un(n.label,n.labelEn,t),fields:[],...n.visibleIf?{visibleIf:n.visibleIf}:{},...r?{notice:r}:{}};if(n.parentId){let o=rr(e,n.parentId);if(!o)throw new Error(`offer form section add: parent section "${n.parentId}" not found`);o.subsections=[...o.subsections??[],i]}else e.sections.push(i)}s(gM,"addSection");function yM(e,n){let t=rr(e,n.id);if(!t)throw new Error(`offer form section set: section "${n.id}" not found`);if(Jn(n.visibleIf,`section "${n.id}" visibleIf`),wn(t,"label",{de:n.label,en:n.labelEn},`offer form section set: section "${n.id}"`),wn(t,"notice",{de:n.notice,en:n.noticeEn,clearable:!0},`offer form section set: section "${n.id}" notice`),n.visibleIf!==void 0&&(n.visibleIf===""?delete t.visibleIf:t.visibleIf=n.visibleIf),n.visibleTo!==void 0){let r=t;if(n.visibleTo==="")delete r.visibleTo;else{let i=n.visibleTo.split(",").map(o=>o.trim());if(i.some(o=>o===""))throw new Error(`offer form section set: --visible-to "${n.visibleTo}" has an empty key`);r.visibleTo=i}}if(n.parentId!==void 0&&t5(e,n.id,n.parentId),n.label===void 0&&n.labelEn===void 0&&n.visibleIf===void 0&&n.visibleTo===void 0&&n.parentId===void 0&&n.notice===void 0&&n.noticeEn===void 0)throw new Error("offer form section set: nothing to change \u2014 pass --label/--label-en/--visible-if/--visible-to/--parent/--notice")}s(yM,"setSection");function wM(e,n){return e.id===n?!0:e.subsections?.some(t=>wM(t,n))??!1}s(wM,"isSelfOrDescendant");function kM(e,n){let t=s(i=>{let o=i.findIndex(a=>a.id===n);if(o>=0)return i.splice(o,1)[0];for(let a of i)if(a.subsections){let l=t(a.subsections);if(l)return l}},"removeFrom"),r=t(e.sections);if(!r)throw new Error(`offer form: section "${n}" not found`);return r}s(kM,"detachSection");function t5(e,n,t){let r=rr(e,n);if(!r)throw new Error(`offer form section set: section "${n}" not found`);if(t!==""){if(!rr(e,t))throw new Error(`offer form section set: parent section "${t}" not found`);if(wM(r,t))throw new Error(`offer form section set: cannot reparent "${n}" under "${t}" \u2014 that would create a cycle`)}let i=kM(e,n);if(t==="")e.sections.push(i);else{let o=rr(e,t);o.subsections=[...o.subsections??[],i]}}s(t5,"reparentSection");function bM(e,n){let t=kM(e,n),r=[],i=s(o=>{o.fields.forEach(a=>r.push(a.key)),o.subsections?.forEach(a=>i(a))},"collect");return i(t),r}s(bM,"removeSection");function vM(e,n,t,r){if(e==="enum"){if(n&&t)throw new Error(`${r}: pass only one of --enum, --enum-list-key (enum options come from exactly one source)`)}else if(n||t)throw new Error(`${r}: --enum/--enum-list-key only valid on an enum field`)}s(vM,"validateEnumChoice");function r5(e,n,t,r){if(!(e===void 0&&n===void 0&&t===void 0&&r===void 0))return{...e&&e.length?{mimeType:e}:{},...n!==void 0?{maxSize:n}:{},...t!==void 0?{multiple:t}:{},...r!==void 0?{minFiles:r}:{}}}s(r5,"buildDocRef");function xM(e,n,t,r){let i=n===void 0&&t===void 0?{de:"Erkl\xE4rung",en:"Declaration"}:un(n??"",t,r,"--declaration-label");return{url:e,filename:i.de,mimeType:"text/html",label:i,renderAs:"inlineLink"}}s(xM,"declarationAttachment");function SM(e,n){if(e!=="yesNo")throw new Error(`${n}: --presentation must be "yesNo" (or "" to clear), got "${e}"`)}s(SM,"validatePresentation");function AM(e,n){if(!xr.includes(n.type))throw new Error(`offer form field add: unknown --type "${n.type}" (one of: ${xr.join(", ")})`);let t=rr(e,n.section);if(!t)throw new Error(`offer form field add: section "${n.section}" not found`);if(zo(e).has(n.key))throw new Error(`offer form field add: field key "${n.key}" already exists in this form`);if(n.type==="enum"&&!n.enum&&!n.enumListKey)throw new Error(`offer form field add: enum field "${n.key}" needs --enum a,b,c or --enum-list-key <list>`);if(n.multiple&&n.type!=="enum")throw new Error("offer form field add: --multiple only valid on an enum field");vM(n.type,n.enum,n.enumListKey,"offer form field add"),n.presentation!==void 0&&SM(n.presentation,"offer form field add");let r=r5(n.docMime,n.docMaxSize,n.docMultiple,n.docMinFiles);if(r&&n.type!=="docRef")throw new Error("offer form field add: --doc-mime/--doc-max-size/--doc-multiple/--doc-min-files only valid with --type docRef");let i=`offer form field add: field "${n.key}"`,o=n.label===void 0&&n.labelEn===void 0?{de:n.key,en:n.key}:un(n.label??"",n.labelEn,i),a=Vo(n.placeholder,n.placeholderEn,i,"--placeholder"),l=Vo(n.help,n.helpEn,i,"--help-text"),d=Vo(n.notice,n.noticeEn,i,"--notice"),c={key:ot(n.key),label:o,kind:"control",type:n.type,...n.required?{required:!0}:{},...n.reviewRequired?{reviewRequired:!0}:{},...n.bucket?{bucket:n.bucket}:{},...n.enum?{enumOptions:n.enum}:{},...n.enumListKey?{enumListKey:n.enumListKey}:{},...n.multiple?{multiple:!0}:{},...n.presentation?{presentation:n.presentation}:{},...a?{placeholder:a}:{},...l?{helpText:l}:{},...d?{notice:d}:{},...r?{docRefConstraints:r}:{},...n.consentTextKey?{consentTextKey:n.consentTextKey}:{},...n.consentVersion?{consentVersion:n.consentVersion}:{},...n.declarationUrl?{attachments:[xM(n.declarationUrl,n.declarationLabel,n.declarationLabelEn,`${i} declaration`)]}:{}};t.fields.push(c),n.persist!==void 0&&zv(e,{key:n.key,...n.persist})}s(AM,"addField");function zv(e,n){let t=`offer form field: field "${n.key}"`,r=Go(e,n.key);if(!r)throw new Error(`${t} not found (only a top-level section field can be persisted here)`);let i=r.field,o=e.effects??=[],a=s(u=>u.kind==="fieldMap","isFieldMap"),l=new Set;for(let u of o.filter(a)){let f=u.mappings.length;u.mappings=u.mappings.filter(m=>m.from!==n.key),f>0&&u.mappings.length===0&&l.add(u.id)}let d=s(()=>{e.effects=o.filter(u=>!(a(u)&&l.has(u.id)&&u.mappings.length===0))},"dropEmptied");if(n.mapsTo===""){d(),i.kind="control";return}if(n.fieldMap===void 0)throw new Error(`${t}: --maps-to needs --fieldmap <effectId> (the fieldMap effect that carries the mapping)`);let c=o.find(u=>u.id===n.fieldMap);if(c===void 0){if(n.target===void 0)throw new Error(`${t}: fieldMap effect "${n.fieldMap}" does not exist \u2014 pass --target <$partyEffect> to create it`);c={id:n.fieldMap,kind:"fieldMap",target:n.target,mappings:[]},o.push(c)}if(!a(c))throw new Error(`${t}: effect "${n.fieldMap}" is a ${String(c.kind)} effect, not a fieldMap`);if(n.target!==void 0&&c.target!==n.target)throw new Error(`${t}: fieldMap "${n.fieldMap}" writes ${c.target}, not ${n.target}`);c.mappings=[...c.mappings,{from:n.key,to:n.mapsTo}],d(),i.kind="cf_value"}s(zv,"persistField");function i5(e,n,t){if(!xr.includes(n))throw new Error(`offer form field set: unknown --type "${n}" (one of: ${xr.join(", ")})`);let r=bm[e],i=bm[n];if(r!==i)throw new Error(`offer form field set: field "${t}" is ${e} (${r}); ${n} (${i}) stores a different value \u2014 add a new field instead`);return n}s(i5,"sameDatumType");function EM(e,n){let t=Go(e,n.key);if(!t)throw new Error(`offer form field set: field "${n.key}" not found`);Jn(n.visibleIf,`field "${n.key}" visibleIf`),Jn(n.requiredIf,`field "${n.key}" requiredIf`),Jn(n.defaultValue,`field "${n.key}" defaultValue`),Jn(n.disabledIf,`field "${n.key}" disabledIf`);let r=t.field;n.type!==void 0&&(r.type=i5(String(r.type),n.type,n.key));let i=String(r.type),o=`offer form field set: field "${n.key}"`;wn(r,"label",{de:n.label,en:n.labelEn},o),wn(r,"placeholder",{de:n.placeholder,en:n.placeholderEn,clearable:!0},`${o} placeholder`),wn(r,"helpText",{de:n.helpText,en:n.helpTextEn,clearable:!0},`${o} help text`),wn(r,"notice",{de:n.notice,en:n.noticeEn,clearable:!0},`${o} notice`),n.required!==void 0&&(r.required=n.required),n.reviewRequired===!0?r.reviewRequired=!0:n.reviewRequired===!1&&delete r.reviewRequired;let a=s((l,d)=>{let c=n[l];c!==void 0&&(c===""?delete r[d]:r[d]=c)},"expr");if(a("visibleIf","visibleIf"),a("requiredIf","requiredIf"),a("defaultValue","defaultValue"),a("disabledIf","disabledIf"),a("bucket","bucket"),a("consentTextKey","consentTextKey"),a("consentVersion","consentVersion"),(n.enum!==void 0||n.enumListKey!==void 0)&&(vM(i,n.enum,n.enumListKey,"offer form field set"),n.enum!==void 0&&(n.enum.length?r.enumOptions=n.enum:delete r.enumOptions,delete r.enumListKey),n.enumListKey!==void 0&&(n.enumListKey===""?delete r.enumListKey:(r.enumListKey=n.enumListKey,delete r.enumOptions,delete r.enumOptionLabels))),n.multiple!==void 0){if(i!=="enum")throw new Error("offer form field set: --multiple only valid on an enum field");n.multiple?r.multiple=!0:delete r.multiple}if(n.presentation!==void 0&&(n.presentation===""?delete r.presentation:(SM(n.presentation,"offer form field set"),r.presentation=n.presentation)),n.requiredFor!==void 0&&(n.requiredFor.length?r.requiredFor=n.requiredFor.map(l=>Wi(l)):delete r.requiredFor),n.docMime!==void 0||n.docMaxSize!==void 0||n.docMultiple!==void 0||n.docMinFiles!==void 0){if(i!=="docRef")throw new Error("offer form field set: --doc-mime/--doc-max-size/--doc-multiple/--doc-min-files only valid on a docRef field");let d={...r.docRefConstraints??{}};n.docMime!==void 0&&(n.docMime.length?d.mimeType=n.docMime:delete d.mimeType),n.docMaxSize!==void 0&&(d.maxSize=n.docMaxSize),n.docMultiple!==void 0&&(d.multiple=n.docMultiple),n.docMinFiles===null?delete d.minFiles:n.docMinFiles!==void 0&&(d.minFiles=n.docMinFiles),Object.keys(d).length?r.docRefConstraints=d:delete r.docRefConstraints}if(n.declarationUrl!==void 0){let l=Array.isArray(r.attachments)?r.attachments:[],d=l.filter(c=>c.renderAs!=="inlineLink");if(n.declarationUrl==="")d.length?r.attachments=d:delete r.attachments;else{let c=l.find(u=>u.renderAs==="inlineLink");if(c===void 0)d.push(xM(n.declarationUrl,n.declarationLabel,n.declarationLabelEn,`${o} declaration`));else{let u={...c,url:n.declarationUrl};wn(u,"label",{de:n.declarationLabel,en:n.declarationLabelEn},`offer form field set: field "${n.key}" declaration`),u.filename=u.label.de,d.push(u)}r.attachments=d}}}s(EM,"setField");function TM(e,n,t,r,i){if(t.kind==="top"){e.unshift(n);return}if(t.kind==="bottom"){e.push(n);return}let o=e.findIndex(a=>r(a)===t.anchor);if(o<0)throw new Error(`${i}: anchor "${t.anchor}" not found among siblings`);e.splice(t.kind==="before"?o:o+1,0,n)}s(TM,"spliceAt");function $M(e,n,t,r){let i=Go(e,n);if(!i)throw new Error(`offer form field move: field "${n}" not found`);if((t.kind==="before"||t.kind==="after")&&t.anchor===n)throw new Error("offer form field move: --before/--after anchor cannot be the field itself");let o=r===void 0?i.section:rr(e,r);if(!o)throw new Error(`offer form field move: section "${r}" not found`);let a=o.fields;if((t.kind==="before"||t.kind==="after")&&!a.some(d=>d.key===t.anchor))throw new Error(`offer form field move: anchor "${t.anchor}" not found in section "${o.id}"`);let[l]=i.section.fields.splice(i.index,1);TM(a,l,t,d=>d.key,"offer form field move")}s($M,"moveField");function RM(e,n,t){if((t.kind==="before"||t.kind==="after")&&t.anchor===n)throw new Error("offer form section move: --before/--after anchor cannot be the section itself");let r=s(l=>{if(l.some(d=>d.id===n))return l;for(let d of l)if(d.subsections){let c=r(d.subsections);if(c)return c}},"findContainer"),i=r(e.sections);if(!i)throw new Error(`offer form section move: section "${n}" not found`);let o=i.findIndex(l=>l.id===n),[a]=i.splice(o,1);TM(i,a,t,l=>l.id,"offer form section move")}s(RM,"moveSection");function IM(e,n){let t=Go(e,n);if(!t)throw new Error(`offer form field rm: field "${n}" not found`);return t.section.fields.splice(t.index,1),n}s(IM,"removeField");function OM(e,n){let t=Go(e,n.key);if(!t)throw new Error(`offer form field attach: field "${n.key}" not found`);if(!ea(n.fileKey))throw new Error(`offer form field attach: --file-key "${n.fileKey}" is not a valid key (a-z, 0-9, "-")`);let r=n.renderAs??"download";if(r==="inlineLink"&&!n.label)throw new Error("offer form field attach: --render inlineLink needs --label (the linked phrase in the field label)");let i=t.field,o=(i.attachments??[]).filter(a=>a.fileKey!==n.fileKey);o.push({fileKey:n.fileKey,...r==="inlineLink"?{renderAs:r}:{},...n.label?{label:un(n.label,n.labelEn,`offer form field attach: field "${n.key}"`)}:{}}),i.attachments=o}s(OM,"attachFile");function PM(e,n,t){let r=Go(e,n);if(!r)throw new Error(`offer form field detach: field "${n}" not found`);let i=r.field,o=(i.attachments??[]).filter(a=>a.fileKey!==t);if(o.length===(i.attachments??[]).length)throw new Error(`offer form field detach: field "${n}" does not attach file "${t}"`);o.length>0?i.attachments=o:delete i.attachments}s(PM,"detachFile");var _M=`--name-from is for organizations only: a person's name is its fieldMap onto first_name / last_name (offer form effect add --kind fieldMap --target <person> --map "<first-name-key>:first_name,<last-name-key>:last_name")`;function NM(e,n){let t=e,r=t.outcomes??(t.outcomes=[]);if(r.some(a=>a.id===n.id))throw new Error(`offer form outcome add: outcome "${n.id}" already exists`);Jn(n.when,`outcome "${n.id}" when`);let i=n.label===void 0&&n.labelEn===void 0?{de:n.id,en:n.id}:un(n.label??"",n.labelEn,`offer form outcome add: outcome "${n.id}"`),o={id:Wi(n.id),label:i,when:n.when,...n.blocking?{blocking:!0}:{},output:{...n.fields&&n.fields.length?{fields:n.fields.map(a=>({path:ot(a)}))}:{},...n.effectRefs&&n.effectRefs.length?{effectRefs:n.effectRefs.map(a=>({effect:a.effect,as:a.as}))}:{},includeForm:!0}};r.push(o)}s(NM,"addOutcome");function CM(e,n){let t=o5(e,n.id);if(!t)throw new Error(`offer form outcome set: outcome "${n.id}" not found`);if(Jn(n.when,`outcome "${n.id}" when`),n.when!==void 0&&(t.when=n.when),n.blocking!==void 0&&(t.blocking=n.blocking),wn(t,"label",{de:n.label,en:n.labelEn},`offer form outcome set: outcome "${n.id}"`),n.fields!==void 0||n.effectRefs!==void 0){let r=t.output??{includeForm:!0};n.fields!==void 0&&(n.fields.length?r.fields=n.fields.map(i=>({path:ot(i)})):delete r.fields),n.effectRefs!==void 0&&(n.effectRefs.length?r.effectRefs=n.effectRefs.map(i=>({effect:i.effect,as:i.as})):delete r.effectRefs),t.output=r}}s(CM,"setOutcome");function DM(e,n){let t=e,r=t.outcomes??[];if(!r.some(i=>i.id===n))throw new Error(`offer form outcome rm: outcome "${n}" not found`);t.outcomes=r.filter(i=>i.id!==n)}s(DM,"removeOutcome");function Yv(e,n){return e.effects.find(t=>t.id===n)}s(Yv,"findEffect");function o5(e,n){return e.outcomes?.find(t=>t.id===n)}s(o5,"findOutcome");function Sa(e){return e.startsWith("$")?e:`$${e}`}s(Sa,"asRef");function Wv(e,n){if(e!==void 0){if(!wa.includes(e))throw new Error(`offer form effect: unknown --identity "${e}" (one of: ${wa.join(", ")})`);if(e==="keyed"){if(!n||n.length===0)throw new Error("offer form effect: --identity keyed needs --identity-key-from <fieldKeys>");return{strategy:"keyed",keyFrom:n}}return{strategy:e}}}s(Wv,"buildIdentity");function FM(e,n){let t=e.effects;if(Yv(e,n.id))throw new Error(`offer form effect add: effect "${n.id}" already exists`);Jn(n.when,`effect "${n.id}" when`);let r={id:F0(n.id),...n.when?{when:n.when}:{}},i;switch(n.kind){case"person":{if(!n.bucket)throw new Error("offer form effect add: person needs --bucket");let o=n.policy??"auto-on-required-complete";if(!Yi.includes(o))throw new Error(`offer form effect add: unknown --policy "${o}" (one of: ${Yi.join(", ")})`);if(n.nameFrom!==void 0)throw new Error(_M);let a=Wv(n.identity,n.identityKeyFrom);i={...r,kind:"person",bucket:n.bucket,policy:o,...a?{identity:a}:{},...n.role?{role:n.role}:{}};break}case"organization":{if(!n.orgKind)throw new Error("offer form effect add: organization needs --org-kind");let o=Wv(n.identity,n.identityKeyFrom);i={...r,kind:"organization",orgKind:n.orgKind,...o?{identity:o}:{},...n.nameFrom?.length?{nameFrom:n.nameFrom.map(a=>ot(a))}:{},...n.role?{role:n.role}:{}};break}case"relationship":{if(!n.from||!n.to||!n.relKind)throw new Error("offer form effect add: relationship needs --from, --to and --rel-kind");i={...r,kind:"relationship",from:Sa(n.from),to:Sa(n.to),relKind:n.relKind};break}case"fieldMap":{if(!n.target||!n.mappings||n.mappings.length===0)throw new Error("offer form effect add: fieldMap needs --target and --map from:to,\u2026");i={...r,kind:"fieldMap",target:Sa(n.target),mappings:n.mappings};break}default:throw new Error(`offer form effect add: unknown --kind "${n.kind}" (one of: ${Pd.join(", ")})`)}t.push(i)}s(FM,"addEffect");function Sr(e,n,t,r){if(!n.includes(e))throw new Error(`offer form effect set: ${t} is only valid on a ${r} effect (this effect is "${e}")`)}s(Sr,"assertEffectKind");function LM(e,n){let t=Yv(e,n.id);if(!t)throw new Error(`offer form effect set: effect "${n.id}" not found`);let r=String(t.kind);if(Jn(n.when,`effect "${n.id}" when`),n.when!==void 0&&(n.when===""?delete t.when:t.when=n.when),n.role!==void 0&&(Sr(r,["person","organization"],"--role","person/organization"),n.role===""?delete t.role:t.role=n.role),n.policy!==void 0){if(Sr(r,["person"],"--policy","person"),!Yi.includes(n.policy))throw new Error(`offer form effect set: unknown --policy "${n.policy}" (one of: ${Yi.join(", ")})`);t.policy=n.policy}if(n.nameFrom!==void 0){if(r==="person")throw new Error(_M);Sr(r,["organization"],"--name-from","organization"),t.nameFrom=n.nameFrom.map(i=>ot(i))}if(n.bucket!==void 0&&(Sr(r,["person"],"--bucket","person"),t.bucket=n.bucket),n.identity!==void 0||n.identityKeyFrom!==void 0){Sr(r,["person","organization"],"--identity","person/organization");let i=n.identity??t.identity?.strategy;t.identity=Wv(i,n.identityKeyFrom)}if(n.orgKind!==void 0&&(Sr(r,["organization"],"--org-kind","organization"),t.orgKind=n.orgKind),n.from!==void 0&&(Sr(r,["relationship"],"--from","relationship"),t.from=Sa(n.from)),n.to!==void 0&&(Sr(r,["relationship"],"--to","relationship"),t.to=Sa(n.to)),n.relKind!==void 0&&(Sr(r,["relationship"],"--rel-kind","relationship"),t.relKind=n.relKind),n.target!==void 0&&(Sr(r,["fieldMap"],"--target","fieldMap"),t.target=Sa(n.target)),n.mappings!==void 0){if(Sr(r,["fieldMap"],"--map","fieldMap"),n.mappings.length===0)throw new Error("offer form effect set: --map cannot be empty for a fieldMap");t.mappings=n.mappings}}s(LM,"setEffect");function MM(e,n){let t=e;if(!Yv(e,n))throw new Error(`offer form effect rm: effect "${n}" not found`);t.effects=t.effects.filter(r=>r.id!==n)}s(MM,"removeEffect");function qM(e,n){let t=rr(e,n.section);if(!t)throw new Error(`offer form repeated add: section "${n.section}" not found`);let r=zo(e);if(r.has(n.key))throw new Error(`offer form repeated add: key "${n.key}" already exists in this form`);if(n.itemFields.length===0)throw new Error("offer form repeated add: needs --item-fields key:type,\u2026");for(let l of n.itemFields){if(!xr.includes(l.type))throw new Error(`offer form repeated add: item field "${l.key}" has unknown type "${l.type}" (one of: ${xr.join(", ")})`);if(r.has(l.key))throw new Error(`offer form repeated add: item field key "${l.key}" already exists in this form`)}Jn(n.itemVisibleIf,`repeated "${n.key}" itemVisibleIf`);let i=new Set(n.itemFields.map(l=>l.key));for(let l of n.uniqueBy??[])if(!i.has(l))throw new Error(`offer form repeated add: --unique-by "${l}" is not one of the item fields (${[...i].join(", ")})`);let o=n.label===void 0&&n.labelEn===void 0?{de:n.key,en:n.key}:un(n.label??"",n.labelEn,`offer form repeated add: repeated "${n.key}"`),a={key:ot(n.key),label:o,itemTemplate:n.itemFields.map(l=>({key:ot(l.key),label:{de:l.key,en:l.key},kind:"control",type:l.type})),...n.min!==void 0?{minItems:n.min}:{},...n.max!==void 0?{maxItems:n.max}:{},...n.itemVisibleIf?{itemVisibleIf:n.itemVisibleIf}:{},...n.uniqueBy?.length?{uniqueBy:n.uniqueBy}:{}};t.repeated=[...t.repeated??[],a]}s(qM,"addRepeated");function KM(e,n){for(let t of jt(e)){let r=(t.repeated??[]).findIndex(i=>i.key===n);if(r>=0)return{section:t,repeated:t.repeated[r],index:r}}}s(KM,"findRepeated");function jM(e,n){let t=KM(e,n.key);if(!t)throw new Error(`offer form repeated set: repeated field "${n.key}" not found`);Jn(n.itemVisibleIf,`repeated "${n.key}" itemVisibleIf`);let r=t.repeated;if(wn(r,"label",{de:n.label,en:n.labelEn},`offer form repeated set: repeated field "${n.key}"`),n.min!==void 0&&(n.min<0?delete r.minItems:r.minItems=n.min),n.max!==void 0&&(n.max<0?delete r.maxItems:r.maxItems=n.max),n.itemVisibleIf!==void 0&&(n.itemVisibleIf===""?delete r.itemVisibleIf:r.itemVisibleIf=n.itemVisibleIf),n.uniqueBy!==void 0)if(n.uniqueBy.length){let i=new Set(t.repeated.itemTemplate.map(o=>o.key));for(let o of n.uniqueBy)if(!i.has(o))throw new Error(`offer form repeated set: --unique-by "${o}" is not an item field (${[...i].join(", ")})`);r.uniqueBy=n.uniqueBy}else delete r.uniqueBy}s(jM,"setRepeated");function BM(e,n){let t=KM(e,n);if(!t)throw new Error(`offer form repeated rm: repeated field "${n}" not found`);return t.section.repeated.splice(t.index,1),n}s(BM,"removeRepeated");function UM(e,n){let t=rr(e,n.section);if(!t)throw new Error(`offer form computed add: section "${n.section}" not found`);if(zo(e).has(n.key))throw new Error(`offer form computed add: key "${n.key}" already exists in this form`);Jn(n.expression,`computed "${n.key}" expression`);let r={key:ot(n.key),expression:n.expression};t.computed=[...t.computed??[],r]}s(UM,"addComputed");function VM(e,n){for(let t of jt(e)){let r=(t.computed??[]).findIndex(i=>i.key===n);if(r>=0)return{section:t,index:r}}}s(VM,"findComputed");function GM(e,n){let t=VM(e,n.key);if(!t)throw new Error(`offer form computed set: computed field "${n.key}" not found`);Jn(n.expression,`computed "${n.key}" expression`),t.section.computed[t.index].expression=n.expression}s(GM,"setComputed");function zM(e,n){let t=VM(e,n);if(!t)throw new Error(`offer form computed rm: computed field "${n}" not found`);return t.section.computed.splice(t.index,1),n}s(zM,"removeComputed");function WM(e){let n=new Set(Pv(e));return _d(e).map(t=>{let r=Im(e,t),i=jt(r);return{slug:t,label:r.label,sections:i.length,fields:[...zo(r)].length,outcomes:(r.outcomes??[]).length,effects:(r.effects??[]).length,boundByNode:n.has(t)}})}s(WM,"listForms");function YM(e,n){let t=Im(e,n),r=[];for(let i of jt(t)){for(let o of i.fields){let a=[],l=o;for(let d of["visibleIf","requiredIf","disabledIf","defaultValue","requiredFor","bucket","docRefConstraints","consentTextKey"])l[d]!==void 0&&a.push(d==="docRefConstraints"?"docRef":d);l.enumOptions&&a.push("enum"),l.presentation!==void 0&&a.push(String(l.presentation)),r.push({section:i.id,key:o.key,type:o.type,required:o.required===!0,flags:a.join(",")})}for(let o of i.repeated??[])r.push({section:i.id,key:o.key,type:"repeated",required:(o.minItems??0)>0,flags:[`items:${o.itemTemplate.length}`,o.uniqueBy?.length?"uniqueBy":"",o.itemVisibleIf?"itemVisibleIf":""].filter(Boolean).join(",")});for(let o of i.computed??[])r.push({section:i.id,key:o.key,type:"computed",required:!1,flags:"expr"})}return{slug:n,label:t.label,fields:r,outcomes:(t.outcomes??[]).map(i=>({id:i.id,when:i.when})),effects:(t.effects??[]).map(i=>({id:i.id,kind:i.kind}))}}s(YM,"showForm");function cc(e){return e.testScenarios??[]}s(cc,"scenarios");function Lm(e,n,t){let r=cc(e).find(i=>i.id===n);if(!r){let i=cc(e).map(o=>o.id);throw new Error(`${t}: no scenario "${n}" (have: ${i.join(", ")||"none"})`)}return r}s(Lm,"findScenario");function s5(e){let n=new Map;for(let t of jt(e)){for(let r of t.fields)n.set(r.key,r);for(let r of t.groups??[])for(let i of r.fields)n.set(i.key,i)}return n}s(s5,"prefillableFields");function Hv(e,n,t){let r=s5(e),i={};for(let o of n){let a=o.indexOf("=");if(a<=0)throw new Error(`${t}: --prefill "${o}" must be key=value`);let l=o.slice(0,a),d=o.slice(a+1),c=r.get(l);if(c===void 0)throw new Error(`${t}: --prefill "${l}" is not a field of this form (repeated rows and addresses: --prefill-json)`);switch(c.type){case"boolean":if(d!=="true"&&d!=="false")throw new Error(`${t}: --prefill ${l} is a boolean field \u2014 use true or false`);i[l]=d==="true";break;case"consent":if(d!=="true")throw new Error(`${t}: --prefill ${l} is a consent \u2014 only true (leave it out for "not given")`);i[l]=!0;break;case"enum":i[l]=c.multiple?d.split(",").map(u=>u.trim()).filter(u=>u.length>0):d;break;case"address":throw new Error(`${t}: --prefill ${l} is an address \u2014 pass it with --prefill-json`);case"docRef":throw new Error(`${t}: --prefill ${l} is a file field \u2014 test mode stubs files itself, they are never prefilled`);default:i[l]=d}}return i}s(Hv,"parsePrefillPairs");function Aa(e,n,t){let r;try{r=JSON.parse(e)}catch(i){throw new Error(`${t}: ${n} is not valid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`${t}: ${n} must be a JSON object`);return r}s(Aa,"parseJsonObject");function HM(e,n){let t="offer form scenario add";if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(n.id))throw new Error(`${t}: --id "${n.id}" must be a kebab-case key (e.g. standard, mit-geschwistern)`);if(cc(e).some(d=>d.id===n.id))throw new Error(`${t}: scenario "${n.id}" already exists`);if(n.label.trim()==="")throw new Error(`${t}: --label cannot be empty`);let r=un(n.label,n.labelEn,t),i=Vo(n.description,n.descriptionEn,t,"--description"),o=n.from===void 0?void 0:structuredClone(Lm(e,n.from,t)),a=n.env??o?.env,l=e;(l.testScenarios??=[]).push({id:n.id,label:r,...i?{description:i}:{},prefill:{...o?.prefill??{},...n.prefill},...a!==void 0?{env:a}:{}})}s(HM,"addScenario");function JM(e,n){let t=`offer form scenario set: scenario "${n.id}"`,r=Lm(e,n.id,"offer form scenario set");if(n.prefillMerge!==void 0&&n.prefillReplace!==void 0)throw new Error(`${t}: pass --prefill (merge) or --prefill-json (replace), not both`);if(n.label==="")throw new Error(`${t}: --label cannot be empty`);wn(r,"label",{de:n.label,en:n.labelEn},t),wn(r,"description",{de:n.description,en:n.descriptionEn,clearable:!0},`${t} description`),n.prefillReplace!==void 0&&(r.prefill=n.prefillReplace),n.prefillMerge!==void 0&&(r.prefill={...r.prefill,...n.prefillMerge});for(let o of n.unset??[]){if(!(o in r.prefill))throw new Error(`${t}: --unset "${o}" is not in the prefill`);let a={...r.prefill};delete a[o],r.prefill=a}if(n.env===null?delete r.env:n.env!==void 0&&(r.env=n.env),![n.label,n.labelEn,n.description,n.descriptionEn,n.prefillMerge,n.prefillReplace,n.unset,n.env].some(o=>o!==void 0))throw new Error(`${t}: nothing to change \u2014 pass --label/--label-en/--description/--prefill/--prefill-json/--unset/--env-json`)}s(JM,"setScenario");function QM(e,n){Lm(e,n,"offer form scenario rm");let t=e;t.testScenarios=cc(e).filter(r=>r.id!==n),t.testScenarios.length===0&&delete t.testScenarios}s(QM,"removeScenario");function ZM(e,n){let t="offer form env set";for(let a of n.keys)if(!ws(a))throw new Error(`${t}: unknown environment key "${a}" (one of: ${ys.join(", ")})`);let r=new Set(n.keys),i=e;r.size===0?delete i.env:i.env=[...r];for(let[a,l]of Object.entries(n.samples??{})){let d=Object.keys(l).filter(u=>!r.has(u));if(d.length>0)throw new Error(`${t}: --sample ${a} samples ${d.join(", ")}, which --keys does not declare`);let c=Lm(e,a,t);c.env={...c.env??{},...l}}let o=[];for(let a of cc(e)){if(a.env===void 0)continue;let l=Object.fromEntries(Object.entries(a.env).filter(([d])=>r.has(d)));Object.keys(l).length!==Object.keys(a.env).length&&(o.push(a.id),Object.keys(l).length===0?delete a.env:a.env=l)}return o}s(ZM,"setEnv");function uc(e,n){let t;try{t=Rt(e)}catch(i){throw new Error(`${n}: validation threw \u2014 nothing written: ${kt(i)}`,{cause:i})}let r=t.filter(i=>i.severity==="error");if(r.length>0)throw new Error(`${n}: validation failed \u2014 nothing written:
10829
10834
  `+r.map(i=>` [${i.area}] ${i.message}`).join(`
10830
10835
  `));return Tt(e),t.filter(i=>i.severity==="warning")}s(uc,"commitBundle");function Mm(e,n,t,r){if([e!==void 0?"before":null,n!==void 0?"after":null,t?"top":null,r?"bottom":null].filter(Boolean).length!==1)throw new Error("offer form move: pass exactly one of --before <id> / --after <id> / --to-top / --to-bottom");return e!==void 0?{kind:"before",anchor:e}:n!==void 0?{kind:"after",anchor:n}:t?{kind:"top"}:{kind:"bottom"}}s(Mm,"parseMove");function fn(e){return e?e.split(",").map(n=>n.trim()).filter(n=>n.length>0):[]}s(fn,"csv");function Jv(e,n){if(e!==void 0)return fn(e).map(t=>{let[r,i]=t.split(":");if(!r||!i)throw new Error(`${n}: --effect-refs token "${t}" must be effect:slot`);return{effect:r,as:i}})}s(Jv,"parseEffectRefs");function Qv(e,n){if(e!==void 0)return fn(e).map(t=>{let[r,i]=t.split(":");if(!r||!i)throw new Error(`${n}: --map token "${t}" must be from:to`);return{from:r,to:i}})}s(Qv,"parseMappings");var qe=class extends Ei{static{s(this,"FormMutationCommand")}withBundle(n,t){let r=je(n);t(r);let i=uc(r,"offer form");return this.warn(i),[r,i]}withForm(n,t,r){let i=je(n),o=Rm(i,t);r(i,o);let a=uc(i,"offer form");return this.warn(a),[i,o,a]}};var fc=class extends xe{static{s(this,"OfferFormListCommand")}static paths=[["offer","form","list"]];static usage=T.Usage({category:"Offer",description:"List the bundle's SmartForms"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=WM(je(this.dir));return this.print(n,t=>t.length===0?[{slug:"(none)",label:"",fields:"",outcomes:"",bound:""}]:t.map(r=>({slug:r.slug,label:`${r.label.de} / ${r.label.en}`,fields:String(r.fields),outcomes:String(r.outcomes),effects:String(r.effects),bound:r.boundByNode?"yes":"no"}))),0}},pc=class extends xe{static{s(this,"OfferFormShowCommand")}static paths=[["offer","form","show"]];static usage=T.Usage({category:"Offer",description:"Show one SmartForm's sections/fields/outcomes/effects"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});async execute(){let n=je(this.dir),t=YM(n,Rm(n,this.form));return this.print(t,r=>r.fields.length===0?[{section:"(no fields)",key:"",type:"",required:"",flags:""}]:r.fields.map(i=>({section:i.section,key:i.key,type:i.type,required:i.required?"yes":"",flags:i.flags}))),0}},mc=class extends qe{static{s(this,"OfferFormAddCommand")}static paths=[["offer","form","add"]];static usage=T.Usage({category:"Offer",description:"Scaffold a new SmartForm into the bundle (one section, default outcome)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"Form slug (= file + bundle.yaml key)"});label=p.String("--label",{required:!0,description:"Form label"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});async execute(){return this.withBundle(this.dir,n=>{Om(n,{key:this.key,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}),this.print({added:this.key,file:`smartforms/${this.key}.json`},n=>[{key:"added",value:n.added},{key:"file",value:n.file},{key:"next",value:`offer workflow node add --type form --form ${n.added}`}]),0}},hc=class extends qe{static{s(this,"OfferFormRemoveCommand")}static paths=[["offer","form","delete"],["offer","form","rm"]];static usage=T.Usage({category:"Offer",description:"Remove a SmartForm from the bundle (fails if a form node binds it)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{required:!0,description:"Form slug to remove"});async execute(){let n=this.form,[t]=this.withBundle(this.dir,i=>L0(i,n)),r=z.join(t.dir,"smartforms",`${n}.json`);return Se(r)&&ts(r),this.print({removed:n},i=>[{key:"removed",value:i.removed}]),0}},gc=class extends qe{static{s(this,"OfferFormSetCommand")}static paths=[["offer","form","set"]];static usage=T.Usage({category:"Offer",description:"Edit a SmartForm's label"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{required:!0,description:"Form slug to edit"});label=p.String("--label",{description:"New form label"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});async execute(){return this.withBundle(this.dir,n=>{M0(n,{slug:this.form,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}),this.print({form:this.form,updated:!0},n=>[{key:"form",value:n.form}]),0}};var yc=class extends qe{static{s(this,"OfferFormSectionAddCommand")}static paths=[["offer","form","section","add"]];static usage=T.Usage({category:"Offer",description:"Add a section to a SmartForm"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});id=p.String("--id",{required:!0,description:"Section id (e.g. section.kind)"});label=p.String("--label",{required:!0,description:"Section label"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});parent=p.String("--parent",{description:"Parent section id (nest as subsection)"});visibleIf=p.String("--visible-if",{description:"visibleIf expression"});notice=p.String("--notice",{description:"Notice under the section heading (bordered, bold, always visible)"});noticeEn=p.String("--notice-en",{description:"English notice \u2014 required with --notice"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{gM(t.smartforms[r],{id:this.id,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.parent?{parentId:this.parent}:{},...this.visibleIf?{visibleIf:this.visibleIf}:{},...this.notice!==void 0?{notice:this.notice}:{},...this.noticeEn!==void 0?{noticeEn:this.noticeEn}:{}})});return this.print({form:n,section:this.id},t=>[{key:"form",value:t.form},{key:"section",value:t.section}]),0}},wc=class extends qe{static{s(this,"OfferFormSectionSetCommand")}static paths=[["offer","form","section","set"]];static usage=T.Usage({category:"Offer",description:"Update a section's label/notice/visibleIf/visibleTo/parent"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});id=p.String("--id",{required:!0,description:"Section id"});label=p.String("--label",{description:"New label"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});visibleIf=p.String("--visible-if",{description:'visibleIf expression ("" to clear)'});visibleTo=p.String("--visible-to",{description:`Only these teams/permission groups (comma-separated keys) and admins read the section's values; the family always does ("" to clear)`});parent=p.String("--parent",{description:'Reparent under this section ("" \u2192 top-level)'});notice=p.String("--notice",{description:'Notice under the section heading ("" clears it and its English)'});noticeEn=p.String("--notice-en",{description:"English notice \u2014 required when --notice changes a translated text"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{yM(t.smartforms[r],{id:this.id,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.visibleIf!==void 0?{visibleIf:this.visibleIf}:{},...this.visibleTo!==void 0?{visibleTo:this.visibleTo}:{},...this.parent!==void 0?{parentId:this.parent}:{},...this.notice!==void 0?{notice:this.notice}:{},...this.noticeEn!==void 0?{noticeEn:this.noticeEn}:{}})});return this.print({form:n,section:this.id,updated:!0},t=>[{key:"form",value:t.form},{key:"section",value:t.section}]),0}},kc=class extends qe{static{s(this,"OfferFormSectionMoveCommand")}static paths=[["offer","form","section","move"]];static usage=T.Usage({category:"Offer",description:"Reorder a section among its siblings"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});id=p.String("--id",{required:!0,description:"Section id to move"});before=p.String("--before",{description:"Place before this sibling id"});after=p.String("--after",{description:"Place after this sibling id"});toTop=p.Boolean("--to-top",!1,{description:"Move to first"});toBottom=p.Boolean("--to-bottom",!1,{description:"Move to last"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{RM(t.smartforms[r],this.id,Mm(this.before,this.after,this.toTop,this.toBottom))});return this.print({form:n,section:this.id,moved:!0},t=>[{key:"form",value:t.form},{key:"section",value:t.section}]),0}},bc=class extends qe{static{s(this,"OfferFormSectionRemoveCommand")}static paths=[["offer","form","section","delete"],["offer","form","section","rm"]];static usage=T.Usage({category:"Offer",description:"Remove a section (and its fields) from a SmartForm"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});id=p.String("--id",{required:!0,description:"Section id"});async execute(){let n=[],[,t]=this.withForm(this.dir,this.form,(r,i)=>{n=bM(r.smartforms[i],this.id)});return this.print({form:t,section:this.id,removedFields:n},r=>[{key:"form",value:r.form},{key:"section",value:r.section},{key:"removedFields",value:n.join(", ")||"(none)"}]),n.length>0&&this.context.stderr.write(`warning: removed ${n.length} field key(s) \u2014 re-publishing this form over an already-published version will be rejected by the field-key stability gate.
10831
10836
  `),0}};var vc=class extends qe{static{s(this,"OfferFormFieldAddCommand")}static paths=[["offer","form","field","add"]];static usage=T.Usage({category:"Offer",description:`Add a field to a section (types: ${xr.join("|")})`});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});section=p.String("--section",{required:!0,description:"Target section id"});key=p.String("--key",{required:!0,description:"Field key (dotted, e.g. kind.vorname)"});type=p.String("--type",{required:!0,description:xr.join("|")});label=p.String("--label",{description:"Field label (default: key)"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});required=p.Boolean("--required",!1,{description:"Mark required"});reviewRequired=p.Boolean("--review-required",!1,{description:"Staff check the entered value: a review node of this form waits until it is ticked"});bucket=p.String("--bucket",{description:"Party bucket (e.g. applicant, kind)"});enumOpts=p.String("--enum",{description:"Inline enum options (a,b,c) \u2014 type enum"});enumListKey=p.String("--enum-list-key",{description:"Tenant custom_field_lists key (runtime-resolved list)"});multiple=p.Boolean("--multiple",!1,{description:"Multi-select enum (value is a list)"});presentation=p.String("--presentation",{description:'boolean: "yesNo" \u2014 the explicit Ja | Nein answer, nothing preselected (no --default allowed)'});placeholder=p.String("--placeholder",{description:"Placeholder text"});placeholderEn=p.String("--placeholder-en",{description:"English placeholder \u2014 required with --placeholder"});helpText=p.String("--help-text",{description:"Help text"});helpTextEn=p.String("--help-text-en",{description:"English help text \u2014 required with --help-text"});notice=p.String("--notice",{description:"Notice directly under the question (bordered, bold, always visible)"});noticeEn=p.String("--notice-en",{description:"English notice \u2014 required with --notice"});docMime=p.String("--doc-mime",{description:"docRef: allowed MIME types (a,b)"});docMaxSize=p.String("--doc-max-size",{description:"docRef: max bytes"});docMultiple=p.Boolean("--doc-multiple",!1,{description:"docRef: allow multiple files"});docMinFiles=p.String("--doc-min-files",{description:"docRef with --doc-multiple: at least N files (whole number >= 2)"});consentKey=p.String("--consent-key",{description:"consent: legal-text key"});consentVersion=p.String("--consent-version",{description:"consent: pinned version"});declarationUrl=p.String("--declaration-url",{description:"consent: pin a declaration link (AGB/Erkl\xE4rung) rendered inline in the label"});declarationLabel=p.String("--declaration-label",{description:"consent: linked phrase shown in the label (default: Erkl\xE4rung)"});declarationLabelEn=p.String("--declaration-label-en",{description:"consent: English linked phrase \u2014 required with --declaration-label"});mapsTo=p.String("--maps-to",{description:"Persist the field: the tenant's custom-field key it is written to (creates a cf_value field + its fieldMap mapping)"});fieldMap=p.String("--fieldmap",{description:"With --maps-to: id of the fieldMap effect carrying the mapping (created with --target when absent)"});target=p.String("--target",{description:"With --maps-to: the party effect a new fieldMap writes ($p.kind)"});async execute(){if(this.mapsTo===void 0&&(this.fieldMap!==void 0||this.target!==void 0))throw new Error("offer form field add: --fieldmap/--target only with --maps-to");let[,n]=this.withForm(this.dir,this.form,(t,r)=>{AM(t.smartforms[r],{...this.mapsTo!==void 0?{persist:{mapsTo:this.mapsTo,...this.fieldMap!==void 0?{fieldMap:this.fieldMap}:{},...this.target!==void 0?{target:this.target}:{}}}:{},section:this.section,key:this.key,type:this.type,required:this.required,...this.reviewRequired?{reviewRequired:!0}:{},...this.label?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.bucket?{bucket:this.bucket}:{},...this.enumOpts?{enum:fn(this.enumOpts)}:{},...this.enumListKey?{enumListKey:this.enumListKey}:{},...this.multiple?{multiple:!0}:{},...this.presentation!==void 0?{presentation:this.presentation}:{},...this.placeholder?{placeholder:this.placeholder}:{},...this.placeholderEn!==void 0?{placeholderEn:this.placeholderEn}:{},...this.helpText?{help:this.helpText}:{},...this.helpTextEn!==void 0?{helpEn:this.helpTextEn}:{},...this.notice!==void 0?{notice:this.notice}:{},...this.noticeEn!==void 0?{noticeEn:this.noticeEn}:{},...this.docMime?{docMime:fn(this.docMime)}:{},...this.docMaxSize!==void 0?{docMaxSize:Number(this.docMaxSize)}:{},...this.docMultiple?{docMultiple:!0}:{},...this.docMinFiles!==void 0?{docMinFiles:Number(this.docMinFiles)}:{},...this.consentKey?{consentTextKey:this.consentKey}:{},...this.consentVersion?{consentVersion:this.consentVersion}:{},...this.declarationUrl!==void 0?{declarationUrl:this.declarationUrl}:{},...this.declarationLabel!==void 0?{declarationLabel:this.declarationLabel}:{},...this.declarationLabelEn!==void 0?{declarationLabelEn:this.declarationLabelEn}:{}})});return this.print({form:n,section:this.section,field:this.key,type:this.type},t=>[{key:"form",value:t.form},{key:"field",value:t.field},{key:"type",value:t.type}]),0}},xc=class extends qe{static{s(this,"OfferFormFieldSetCommand")}static paths=[["offer","form","field","set"]];static usage=T.Usage({category:"Offer",description:"Set a field's validation/visibility expressions and flags"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key to edit"});type=p.String("--type",{description:"Another type of the same datum (boolean|consent, string|email|tel) \u2014 e.g. a boolean that is a consent"});label=p.String("--label",{description:"New label"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});required=p.Boolean("--required",{description:"Required (or --no-required)"});reviewRequired=p.Boolean("--review-required",{description:"Staff check the entered value before a review of this form passes (or --no-review-required)"});visibleIf=p.String("--visible-if",{description:'visibleIf ("" clears)'});requiredIf=p.String("--required-if",{description:'requiredIf ("" clears)'});defaultValue=p.String("--default",{description:'defaultValue expression ("" clears)'});disabledIf=p.String("--disabled-if",{description:'disabledIf ("" clears)'});bucket=p.String("--bucket",{description:'Party bucket ("" clears)'});placeholder=p.String("--placeholder",{description:'Placeholder ("" clears it and its English)'});placeholderEn=p.String("--placeholder-en",{description:"English placeholder \u2014 required when --placeholder changes a translated text"});helpText=p.String("--help-text",{description:'Help text ("" clears it and its English)'});helpTextEn=p.String("--help-text-en",{description:"English help text \u2014 required when --help-text changes a translated text"});notice=p.String("--notice",{description:'Notice directly under the question ("" clears it and its English)'});noticeEn=p.String("--notice-en",{description:"English notice \u2014 required when --notice changes a translated text"});enumOpts=p.String("--enum",{description:"Replace inline enum options (a,b,c)"});enumListKey=p.String("--enum-list-key",{description:'Set tenant custom_field_lists key; "" clears'});multiple=p.Boolean("--multiple",{description:"Multi-select enum (or --no-multiple)"});presentation=p.String("--presentation",{description:'boolean: "yesNo" \u2014 the explicit Ja | Nein answer; "" back to the checkbox'});requiredFor=p.String("--required-for",{description:'Outcome-scoped required (o1,o2); "" clears'});docMime=p.String("--doc-mime",{description:"docRef: allowed MIME types (a,b)"});docMaxSize=p.String("--doc-max-size",{description:"docRef: max bytes"});docMultiple=p.Boolean("--doc-multiple",{description:"docRef: allow multiple (or --no-doc-multiple)"});docMinFiles=p.String("--doc-min-files",{description:'docRef, multiple only: at least N files (whole number >= 2); "" clears'});consentKey=p.String("--consent-key",{description:'consent: legal-text key ("" clears)'});consentVersion=p.String("--consent-version",{description:'consent: pinned version ("" clears)'});declarationUrl=p.String("--declaration-url",{description:'consent: pin a declaration link (AGB/Erkl\xE4rung) inline in the label ("" clears)'});declarationLabel=p.String("--declaration-label",{description:"consent: linked phrase shown in the label (default: Erkl\xE4rung)"});declarationLabelEn=p.String("--declaration-label-en",{description:"consent: English linked phrase \u2014 required with --declaration-label"});mapsTo=p.String("--maps-to",{description:'Persist the field onto this tenant custom-field key (kind cf_value + fieldMap mapping, one write); "" takes it back (mappings removed, kind control)'});fieldMap=p.String("--fieldmap",{description:"With --maps-to: id of the fieldMap effect carrying the mapping (created with --target when absent)"});target=p.String("--target",{description:"With --maps-to: the party effect a new fieldMap writes ($p.kind)"});async execute(){if(this.mapsTo===void 0&&(this.fieldMap!==void 0||this.target!==void 0))throw new Error("offer form field set: --fieldmap/--target only with --maps-to");let[,n]=this.withForm(this.dir,this.form,(t,r)=>{this.mapsTo!==void 0&&zv(t.smartforms[r],{key:this.key,mapsTo:this.mapsTo,...this.fieldMap!==void 0?{fieldMap:this.fieldMap}:{},...this.target!==void 0?{target:this.target}:{}}),EM(t.smartforms[r],{key:this.key,...this.type!==void 0?{type:this.type}:{},...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.required!==void 0?{required:this.required}:{},...this.reviewRequired!==void 0?{reviewRequired:this.reviewRequired}:{},...this.visibleIf!==void 0?{visibleIf:this.visibleIf}:{},...this.requiredIf!==void 0?{requiredIf:this.requiredIf}:{},...this.defaultValue!==void 0?{defaultValue:this.defaultValue}:{},...this.disabledIf!==void 0?{disabledIf:this.disabledIf}:{},...this.bucket!==void 0?{bucket:this.bucket}:{},...this.placeholder!==void 0?{placeholder:this.placeholder}:{},...this.placeholderEn!==void 0?{placeholderEn:this.placeholderEn}:{},...this.helpText!==void 0?{helpText:this.helpText}:{},...this.helpTextEn!==void 0?{helpTextEn:this.helpTextEn}:{},...this.notice!==void 0?{notice:this.notice}:{},...this.noticeEn!==void 0?{noticeEn:this.noticeEn}:{},...this.enumOpts!==void 0?{enum:fn(this.enumOpts)}:{},...this.enumListKey!==void 0?{enumListKey:this.enumListKey}:{},...this.multiple!==void 0?{multiple:this.multiple}:{},...this.presentation!==void 0?{presentation:this.presentation}:{},...this.requiredFor!==void 0?{requiredFor:fn(this.requiredFor)}:{},...this.docMime!==void 0?{docMime:fn(this.docMime)}:{},...this.docMaxSize!==void 0?{docMaxSize:Number(this.docMaxSize)}:{},...this.docMultiple!==void 0?{docMultiple:this.docMultiple}:{},...this.docMinFiles!==void 0?{docMinFiles:this.docMinFiles===""?null:Number(this.docMinFiles)}:{},...this.consentKey!==void 0?{consentTextKey:this.consentKey}:{},...this.consentVersion!==void 0?{consentVersion:this.consentVersion}:{},...this.declarationUrl!==void 0?{declarationUrl:this.declarationUrl}:{},...this.declarationLabel!==void 0?{declarationLabel:this.declarationLabel}:{},...this.declarationLabelEn!==void 0?{declarationLabelEn:this.declarationLabelEn}:{}})});return this.print({form:n,field:this.key,updated:!0},t=>[{key:"form",value:t.form},{key:"field",value:t.field}]),0}},Sc=class extends qe{static{s(this,"OfferFormFieldExportCommand")}static paths=[["offer","form","field","export"]];static usage=T.Usage({category:"Offer",description:"Export a form field (or take the export back) and re-stamp the workflow's formExports in the same write",details:"An exported field becomes a leaf of the form node's result \u2014 `$node.<formNode>.admission.<key>` \u2014 that a contract node may bind (`node set-input`). An entered field exports as its own type (a docRef or a multi-select has no single value and is refused); a computed field needs its type, --type string|number|boolean|date. A field in a repeated block is refused (a row value is no per-application leaf). The same write re-stamps every form node's formExports from the edited form, so the address checks of `offer validate` see the new leaf at once.",examples:[["Export the school start date","$0 offer form field export --dir ./bundle --key kind.einschulung"],["Export a computed field","$0 offer form field export --dir ./bundle --key kind.geschwisterZahl --type number"],["Take the export back","$0 offer form field export --dir ./bundle --key kind.einschulung --off"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key (dotted, e.g. kind.einschulung)"});off=p.Boolean("--off",!1,{description:"Take the export back"});type=p.String("--type",{description:"Computed field only: the leaf's type (string|number|boolean|date)"});async execute(){let n,t=[],[,r]=this.withForm(this.dir,this.form,(i,o)=>{n=V0(i.smartforms[o],{key:this.key,on:!this.off,...this.type!==void 0?{type:this.type}:{}}),i.workflow!==void 0&&(t=Pm(i).filter(a=>a.form===o).flatMap(a=>a.after))});return this.print({form:r,field:this.key,...n,formExports:t},i=>[{key:"form",value:i.form},{key:"field",value:`${i.field} (${i.kind})`},{key:"exported",value:`${i.before?"yes":"no"} \u2192 ${i.after?"yes":"no"}`},{key:"formExports",value:i.formExports.join(", ")||"\u2014"}]),0}},Ac=class extends qe{static{s(this,"OfferFormFieldAttachCommand")}static paths=[["offer","form","field","attach"]];static usage=T.Usage({category:"Offer",description:"Attach a tenant library file (plexus-cli files) to a field by key",details:"The field names the file by key only; label, file name and type come from the library, so replacing the file (`files put`) needs no form edit. The key must exist in the target tenant's library when the offer is published."});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key"});fileKey=p.String("--file-key",{required:!0,description:"Tenant library file key"});render=p.String("--render",{description:"download (default) | inlineLink"});label=p.String("--label",{description:"The field's own phrase (required for inlineLink)"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label"});async execute(){if(this.render!==void 0&&this.render!=="download"&&this.render!=="inlineLink")throw new Error(`offer form field attach: --render must be download|inlineLink (got "${this.render}")`);let n=this.render,[,t]=this.withForm(this.dir,this.form,(r,i)=>{OM(r.smartforms[i],{key:this.key,fileKey:this.fileKey,...n?{renderAs:n}:{},...this.label?{label:this.label}:{},...this.labelEn?{labelEn:this.labelEn}:{}})});return this.print({form:t,field:this.key,fileKey:this.fileKey},r=>[{key:"form",value:r.form},{key:"field",value:r.field},{key:"fileKey",value:r.fileKey}]),0}},Ec=class extends qe{static{s(this,"OfferFormFieldDetachCommand")}static paths=[["offer","form","field","detach"]];static usage=T.Usage({category:"Offer",description:"Remove a tenant library file attachment from a field"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key"});fileKey=p.String("--file-key",{required:!0,description:"Tenant library file key"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{PM(t.smartforms[r],this.key,this.fileKey)});return this.print({form:n,field:this.key,detached:this.fileKey},t=>[{key:"form",value:t.form},{key:"field",value:t.field},{key:"detached",value:t.detached}]),0}},Tc=class extends qe{static{s(this,"OfferFormFieldMoveCommand")}static paths=[["offer","form","field","move"]];static usage=T.Usage({category:"Offer",description:"Reorder a field within its section, or move it into another section (--section)",details:"With --section the field moves unchanged (same key, so values and every address naming it stay valid); --before/--after then name a field of the TARGET section. A section left empty is not removed \u2014 `offer form section rm` does that.",examples:[["Move a field into another section, after the photo","$0 offer form field move --dir ./b --key kind.proofOfIdentity --section section.kind --after kind.photo"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key to move"});section=p.String("--section",{description:"Target section id (default: the field's own section)"});before=p.String("--before",{description:"Place before this field key"});after=p.String("--after",{description:"Place after this field key"});toTop=p.Boolean("--to-top",!1,{description:"Move to first in (target) section"});toBottom=p.Boolean("--to-bottom",!1,{description:"Move to last in (target) section"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{$M(t.smartforms[r],this.key,Mm(this.before,this.after,this.toTop,this.toBottom),this.section)});return this.print({form:n,field:this.key,section:this.section??null,moved:!0},t=>[{key:"form",value:t.form},{key:"field",value:t.field},...t.section?[{key:"section",value:t.section}]:[]]),0}},$c=class extends qe{static{s(this,"OfferFormFieldRemoveCommand")}static paths=[["offer","form","field","delete"],["offer","form","field","rm"]];static usage=T.Usage({category:"Offer",description:"Remove a field from a SmartForm"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});key=p.String("--key",{required:!0,description:"Field key to remove"});async execute(){let[,n]=this.withForm(this.dir,this.form,(t,r)=>{IM(t.smartforms[r],this.key)});return this.print({form:n,removed:this.key},t=>[{key:"form",value:t.form},{key:"removed",value:t.removed}]),this.context.stderr.write(`warning: removing field "${this.key}" \u2014 re-publishing this form over an already-published version will be rejected by the field-key stability gate (adding fields is allowed, removing is not).
@@ -10834,19 +10839,19 @@ Platzhalter: ${i||"\u2014"}
10834
10839
  `):f.severity==="warning"&&u(f.message)&&e.write(` \u26A0 ${f.area}: ${f.message}
10835
10840
  `);if(c.length>0){for(let f of c)e.write(` \u2716 ${f.area}: ${f.message}
10836
10841
  `);return e.write(` \u2192 NOT written (fix the ${r})
10837
- `),null}return Tt(l),l}s(Ji,"writeIfNoNewErrors");function tq(e,n,t){let{signing:r,assign:i,...o}=e,{[ft]:a,...l}=i??{};if(n==="scan")return{...o,assign:l};let d=t??i?.[ft]??i?.countersign;return{...o,signing:n,assign:d===void 0?l:{...l,[ft]:d}}}s(tq,"withCountersignSigning");function a3(e){let n=$d(e);return{de:`${n.de} freigeben`,en:`Release ${n.en}`}}s(a3,"defaultApproveTitle");function rq(e,n,t){if(e.production==="none"&&n==="release"&&le("CONFLICT",{de:`Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben.`,en:`Node "${e.id}" has production 'none' \u2014 without a document there is nothing to release.`}),n==="none"){let{releaseApproval:o,...a}=e.assign??{},{approve:l,...d}=e.titles??{},c={...e,approval:"none"};return e.assign!==void 0&&(Object.keys(a).length>0?c.assign=a:delete c.assign),e.titles!==void 0&&(c.titles=d),c}let{confirmBeforeIssue:r,...i}=e;return{...i,approval:"release",titles:{...e.titles,approve:t??e.titles?.approve??a3(e)}}}s(rq,"withApprovalMode");function iq(e,n){let{confirmBeforeIssue:t,...r}=e;return n?((e.production==="none"||e.approval!=="none")&&le("CONFLICT",{de:`Knoten "${e.id}" (production '${e.production}', approval '${e.approval}') \u2014 die R\xFCckfrage geh\xF6rt zu \u201EBereitstellen", das es nur mit Dokument und approval 'none' gibt; mit Freigabe ist die Freigabe selbst die Pr\xFCfung.`,en:`Node "${e.id}" (production '${e.production}', approval '${e.approval}') \u2014 the confirmation prompt belongs to \u201CIssue document\u201D, which only exists with a document and approval 'none'; with an approval, the approval itself is the check.`}),{...r,confirmBeforeIssue:!0}):r}s(iq,"withConfirmBeforeIssue");function oq(e,n){aq(e);let{confirmContractTerms:t,contractTermsQuestionText:r,...i}=e;return n?r===void 0?i:{...i,contractTermsQuestionText:r}:{...i,confirmContractTerms:!1}}s(oq,"withConfirmContractTerms");function sq(e,n){aq(e);let{contractTermsQuestionText:t,...r}=e;return n===null?r:(e.confirmContractTerms===!1&&le("CONFLICT",{de:`Knoten "${e.id}" fragt nicht nach den Vertragsbedingungen (confirmContractTerms: false) \u2014 erst die Best\xE4tigung einschalten, dann die Frage umformulieren.`,en:`Node "${e.id}" does not ask about the contract terms (confirmContractTerms: false) \u2014 switch the confirmation on first, then reword the question.`}),(n.de.trim()===""||n.en.trim()==="")&&le("INVALID",{de:`[i18n/missingTranslation] Knoten "${e.id}": die Frage nach den Vertragsbedingungen braucht einen deutschen UND einen englischen Text.`,en:`[i18n/missingTranslation] Node "${e.id}": the question about the contract terms needs a German AND an English text.`}),{...r,contractTermsQuestionText:{de:n.de.trim(),en:n.en.trim()}})}s(sq,"withContractTermsQuestion");function aq(e){Rd(e)||le("CONFLICT",{de:`Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') nimmt keine unterschriebene Fassung entgegen \u2014 die Best\xE4tigung der Vertragsbedingungen gibt es nur mit 'signedUpload' oder 'signedUploadChecked'.`,en:`Node "${e.id}" (responseStrategy '${e.responseStrategy}') does not accept a signed copy \u2014 confirming the contract terms only exists with 'signedUpload' or 'signedUploadChecked'.`})}s(aq,"assertReturnsSignedCopy");function lq(e,n){let{[ui]:t,...r}=e.inputs??{},i={...e,inputs:r};return n===null?((e.templateStamp?.fields??[]).some(o=>o.processSource==="responseDueInDays")&&le("CONFLICT",{de:`Knoten "${e.id}" druckt die Antwortfrist in seiner Vorlage \u2014 erst das Feld entfernen, dann die Frist.`,en:`Node "${e.id}" prints the response deadline in its template \u2014 remove the field first, then the deadline.`}),i):(Ed(n)||le("INVALID",{de:`Antwortfrist ${n} \u2014 erlaubt ist eine ganze Zahl von ${Ko} bis ${jo} Tagen.`,en:`Response deadline ${n} \u2014 a whole number from ${Ko} to ${jo} days is allowed.`}),{...e,inputs:{...r,[ui]:{kind:"literal",value:n}}})}s(lq,"withResponseDueInDays");var Xv=["signedUploadChecked","eSignature"];function dq(e,n,t){e.production!=="resolver"&&le("CONFLICT",{de:`Knoten "${e.id}" erzeugt keinen Vertrag (production '${e.production}') \u2014 zwischen Papier und elektronischer Unterschrift w\xE4hlt nur ein Vertragsknoten mit production 'resolver'.`,en:`Node "${e.id}" does not produce a contract (production '${e.production}') \u2014 only a contract node with production 'resolver' chooses between paper and electronic signature.`});let{signingRecovery:r,...i}=e.assign??{};if(n==="signedUploadChecked")return{...e,responseStrategy:n,assign:i};let o=t??e.assign?.signingRecovery??e.assign?.responseCheck;return{...e,responseStrategy:n,assign:o===void 0?i:{...i,signingRecovery:o}}}s(dq,"withResponseStrategy");function Gr(e){let n=e.workflow?.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow: the bundle carries no workflow graph with nodes");return n}s(Gr,"workflowGraphOf");function l3(e,n){return Iy(e,n).map(t=>Ue(e,t.address,"de"))}s(l3,"visibleAddressLines");function Ea(e,n,t,r,i){let o=l3(e,n);throw new kn(`${t} "${r}": ${i}
10842
+ `),null}return Tt(l),l}s(Ji,"writeIfNoNewErrors");function tq(e,n,t){let{signing:r,assign:i,...o}=e,{[ft]:a,...l}=i??{};if(n==="scan")return{...o,assign:l};let d=t??i?.[ft]??i?.countersign;return{...o,signing:n,assign:d===void 0?l:{...l,[ft]:d}}}s(tq,"withCountersignSigning");function a5(e){let n=$d(e);return{de:`${n.de} freigeben`,en:`Release ${n.en}`}}s(a5,"defaultApproveTitle");function rq(e,n,t){if(e.production==="none"&&n==="release"&&le("CONFLICT",{de:`Knoten "${e.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben.`,en:`Node "${e.id}" has production 'none' \u2014 without a document there is nothing to release.`}),n==="none"){let{releaseApproval:o,...a}=e.assign??{},{approve:l,...d}=e.titles??{},c={...e,approval:"none"};return e.assign!==void 0&&(Object.keys(a).length>0?c.assign=a:delete c.assign),e.titles!==void 0&&(c.titles=d),c}let{confirmBeforeIssue:r,...i}=e;return{...i,approval:"release",titles:{...e.titles,approve:t??e.titles?.approve??a5(e)}}}s(rq,"withApprovalMode");function iq(e,n){let{confirmBeforeIssue:t,...r}=e;return n?((e.production==="none"||e.approval!=="none")&&le("CONFLICT",{de:`Knoten "${e.id}" (production '${e.production}', approval '${e.approval}') \u2014 die R\xFCckfrage geh\xF6rt zu \u201EBereitstellen", das es nur mit Dokument und approval 'none' gibt; mit Freigabe ist die Freigabe selbst die Pr\xFCfung.`,en:`Node "${e.id}" (production '${e.production}', approval '${e.approval}') \u2014 the confirmation prompt belongs to \u201CIssue document\u201D, which only exists with a document and approval 'none'; with an approval, the approval itself is the check.`}),{...r,confirmBeforeIssue:!0}):r}s(iq,"withConfirmBeforeIssue");function oq(e,n){aq(e);let{confirmContractTerms:t,contractTermsQuestionText:r,...i}=e;return n?r===void 0?i:{...i,contractTermsQuestionText:r}:{...i,confirmContractTerms:!1}}s(oq,"withConfirmContractTerms");function sq(e,n){aq(e);let{contractTermsQuestionText:t,...r}=e;return n===null?r:(e.confirmContractTerms===!1&&le("CONFLICT",{de:`Knoten "${e.id}" fragt nicht nach den Vertragsbedingungen (confirmContractTerms: false) \u2014 erst die Best\xE4tigung einschalten, dann die Frage umformulieren.`,en:`Node "${e.id}" does not ask about the contract terms (confirmContractTerms: false) \u2014 switch the confirmation on first, then reword the question.`}),(n.de.trim()===""||n.en.trim()==="")&&le("INVALID",{de:`[i18n/missingTranslation] Knoten "${e.id}": die Frage nach den Vertragsbedingungen braucht einen deutschen UND einen englischen Text.`,en:`[i18n/missingTranslation] Node "${e.id}": the question about the contract terms needs a German AND an English text.`}),{...r,contractTermsQuestionText:{de:n.de.trim(),en:n.en.trim()}})}s(sq,"withContractTermsQuestion");function aq(e){Rd(e)||le("CONFLICT",{de:`Knoten "${e.id}" (responseStrategy '${e.responseStrategy}') nimmt keine unterschriebene Fassung entgegen \u2014 die Best\xE4tigung der Vertragsbedingungen gibt es nur mit 'signedUpload' oder 'signedUploadChecked'.`,en:`Node "${e.id}" (responseStrategy '${e.responseStrategy}') does not accept a signed copy \u2014 confirming the contract terms only exists with 'signedUpload' or 'signedUploadChecked'.`})}s(aq,"assertReturnsSignedCopy");function lq(e,n){let{[ui]:t,...r}=e.inputs??{},i={...e,inputs:r};return n===null?((e.templateStamp?.fields??[]).some(o=>o.processSource==="responseDueInDays")&&le("CONFLICT",{de:`Knoten "${e.id}" druckt die Antwortfrist in seiner Vorlage \u2014 erst das Feld entfernen, dann die Frist.`,en:`Node "${e.id}" prints the response deadline in its template \u2014 remove the field first, then the deadline.`}),i):(Ed(n)||le("INVALID",{de:`Antwortfrist ${n} \u2014 erlaubt ist eine ganze Zahl von ${Ko} bis ${jo} Tagen.`,en:`Response deadline ${n} \u2014 a whole number from ${Ko} to ${jo} days is allowed.`}),{...e,inputs:{...r,[ui]:{kind:"literal",value:n}}})}s(lq,"withResponseDueInDays");var Xv=["signedUploadChecked","eSignature"];function dq(e,n,t){e.production!=="resolver"&&le("CONFLICT",{de:`Knoten "${e.id}" erzeugt keinen Vertrag (production '${e.production}') \u2014 zwischen Papier und elektronischer Unterschrift w\xE4hlt nur ein Vertragsknoten mit production 'resolver'.`,en:`Node "${e.id}" does not produce a contract (production '${e.production}') \u2014 only a contract node with production 'resolver' chooses between paper and electronic signature.`});let{signingRecovery:r,...i}=e.assign??{};if(n==="signedUploadChecked")return{...e,responseStrategy:n,assign:i};let o=t??e.assign?.signingRecovery??e.assign?.responseCheck;return{...e,responseStrategy:n,assign:o===void 0?i:{...i,signingRecovery:o}}}s(dq,"withResponseStrategy");function Gr(e){let n=e.workflow?.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow: the bundle carries no workflow graph with nodes");return n}s(Gr,"workflowGraphOf");function l5(e,n){return Iy(e,n).map(t=>Ue(e,t.address,"de"))}s(l5,"visibleAddressLines");function Ea(e,n,t,r,i){let o=l5(e,n);throw new kn(`${t} "${r}": ${i}
10838
10843
  An \u201E${Oe(e,n,"de")}" (${n}) lesbar:
10839
10844
  `+(o.length>0?o.map(a=>` ${a}
10840
10845
  `).join(""):` \u2014 nichts
10841
- `)+` Ein Formularfeld ist <Formular-Adresse>.<Feldschl\xFCssel>, z. B. '$node.form.${it}.kind.vorname'. Adressen in einfache Anf\xFChrungszeichen setzen \u2014 sonst ersetzt die Shell $node.`)}s(Ea,"refuseAddress");function mt(e,n,t,r){let i=r.trim();i===""&&Ea(e,n,t,r,"leer \u2014 eine Adresse nennt ihren Erzeuger."),i.startsWith("$")||Ea(e,n,t,r,i.startsWith(".")?"die Shell hat das $\u2026 ersetzt \u2014 die Adresse in einfache Anf\xFChrungszeichen setzen.":"ein nackter Schl\xFCssel \u2014 eine Lese nennt ihren Erzeuger mit voller Adresse ($node.\u2026, $task.\u2026, $env.\u2026, $derived.\u2026).");let o=Qr(i);return o===null&&Ea(e,n,t,r,"keine g\xFCltige Adresse."),o}s(mt,"parseAddressArg");function ex(e,n,t,r){return qm(r).map(i=>mt(e,n,t,i))}s(ex,"parseAddressList");function qm(e){return(e??[]).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean)}s(qm,"splitList");function nx(e,n){let t=e.trim(),r=n.trim();if(!fr.test(t))throw new kn(`--from "${e}": keine Knoten-ID (${fr.source})`);if(!po(r))throw new kn(`--field "${n}": kein Feldpfad (Segmente mit Punkt getrennt)`);return{scope:"node",owner:t,key:it,path:r}}s(nx,"formFieldAddress");function Vc(e,n){if(!we(e))throw new Error(`${n}: ${JSON.stringify(e)} ist keine Adresse \u2014 ein B\xFCndel aus der Zeit vor den Adressen neu exportieren`);return se(e)}s(Vc,"storedAddressSpelling");var d3={written:"geschrieben",evidence:"mitgelesen: Beleg der Schreib-Aufgabe",derivedSource:"mitgelesen: Quelle des abgeleiteten Preises",priceCheck:"mitgelesen: Preispr\xFCfung"};function cq(e){return d3[e]}s(cq,"originLabel");function c3(e,n){switch(n.scope){case"node":return`Knoten \u201E${Oe(e,n.owner,"de")}" (${n.owner})`;case"task":{let t=Fr(e,n.owner,n.key),r=t===null?"auf keinem Knoten \u2014 die Aufgabe schreibt den Wert nicht":`auf \u201E${Oe(e,t,"de")}" (${t})`;return`Aufgabe \u201E${vo(e,n.owner,"de")}" (${n.owner}) ${r}`}case"env":return"die Anmeldung (kein Erzeuger)";case"derived":return"abgeleiteter Preis (aus seinen Quellen)"}}s(c3,"producerOf");function uq(e,n){let t=Gr(e),r=t.nodes.find(i=>i.id===n);if(!r)throw new kn(`offer workflow node reads: no node "${n}" (nodes: ${t.nodes.map(i=>i.id).join(", ")})`);return bo(t,r).map(i=>({address:se(i.address),display:Ue(t,i.address,"de"),origin:i.origin,at:i.field.at,producer:c3(t,i.address),via:i.via===void 0?"":se(i.via)}))}s(uq,"nodeReadRows");function fq(e,n){let t=Gr(e),r=qI(t,n);if(r.length!==0)throw new kn(`offer workflow node rm: \u201E${Oe(t,n,"de")}" (${n}) wird noch gelesen \u2014 zuerst diese Stellen \xE4ndern:
10846
+ `)+` Ein Formularfeld ist <Formular-Adresse>.<Feldschl\xFCssel>, z. B. '$node.form.${it}.kind.vorname'. Adressen in einfache Anf\xFChrungszeichen setzen \u2014 sonst ersetzt die Shell $node.`)}s(Ea,"refuseAddress");function mt(e,n,t,r){let i=r.trim();i===""&&Ea(e,n,t,r,"leer \u2014 eine Adresse nennt ihren Erzeuger."),i.startsWith("$")||Ea(e,n,t,r,i.startsWith(".")?"die Shell hat das $\u2026 ersetzt \u2014 die Adresse in einfache Anf\xFChrungszeichen setzen.":"ein nackter Schl\xFCssel \u2014 eine Lese nennt ihren Erzeuger mit voller Adresse ($node.\u2026, $task.\u2026, $env.\u2026, $derived.\u2026).");let o=Qr(i);return o===null&&Ea(e,n,t,r,"keine g\xFCltige Adresse."),o}s(mt,"parseAddressArg");function ex(e,n,t,r){return qm(r).map(i=>mt(e,n,t,i))}s(ex,"parseAddressList");function qm(e){return(e??[]).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean)}s(qm,"splitList");function nx(e,n){let t=e.trim(),r=n.trim();if(!fr.test(t))throw new kn(`--from "${e}": keine Knoten-ID (${fr.source})`);if(!po(r))throw new kn(`--field "${n}": kein Feldpfad (Segmente mit Punkt getrennt)`);return{scope:"node",owner:t,key:it,path:r}}s(nx,"formFieldAddress");function Vc(e,n){if(!we(e))throw new Error(`${n}: ${JSON.stringify(e)} ist keine Adresse \u2014 ein B\xFCndel aus der Zeit vor den Adressen neu exportieren`);return se(e)}s(Vc,"storedAddressSpelling");var d5={written:"geschrieben",evidence:"mitgelesen: Beleg der Schreib-Aufgabe",derivedSource:"mitgelesen: Quelle des abgeleiteten Preises",priceCheck:"mitgelesen: Preispr\xFCfung"};function cq(e){return d5[e]}s(cq,"originLabel");function c5(e,n){switch(n.scope){case"node":return`Knoten \u201E${Oe(e,n.owner,"de")}" (${n.owner})`;case"task":{let t=Fr(e,n.owner,n.key),r=t===null?"auf keinem Knoten \u2014 die Aufgabe schreibt den Wert nicht":`auf \u201E${Oe(e,t,"de")}" (${t})`;return`Aufgabe \u201E${vo(e,n.owner,"de")}" (${n.owner}) ${r}`}case"env":return"die Anmeldung (kein Erzeuger)";case"derived":return"abgeleiteter Preis (aus seinen Quellen)"}}s(c5,"producerOf");function uq(e,n){let t=Gr(e),r=t.nodes.find(i=>i.id===n);if(!r)throw new kn(`offer workflow node reads: no node "${n}" (nodes: ${t.nodes.map(i=>i.id).join(", ")})`);return bo(t,r).map(i=>({address:se(i.address),display:Ue(t,i.address,"de"),origin:i.origin,at:i.field.at,producer:c5(t,i.address),via:i.via===void 0?"":se(i.via)}))}s(uq,"nodeReadRows");function fq(e,n){let t=Gr(e),r=qI(t,n);if(r.length!==0)throw new kn(`offer workflow node rm: \u201E${Oe(t,n,"de")}" (${n}) wird noch gelesen \u2014 zuerst diese Stellen \xE4ndern:
10842
10847
  `+r.map(i=>` ${i.at}: ${se(i.address)}
10843
- `).join(""))}s(fq,"refuseWhileNamed");var pq=["add","remove","replace"],Km=["form","decision","review","setFlag","waitlist","roleAssign","join","collectPayment","completenessCheck","countersign","engagePush","if","end"],tx="process";function u3(e){return Km.includes(e)}s(u3,"isSupported");function or(e){if(!e.workflow)throw new Error("offer workflow node: bundle carries no workflow.json");let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow node: workflow.graph has no nodes array");return n}s(or,"graphOf");function f3(e){let n=Uo[e];if(!n)throw new Error(`offer workflow node: no spec registered for type "${e}"`);return n}s(f3,"specFor");function mq(e,n){let t=e.inputs;return typeof t!="function"?[]:t(n)}s(mq,"specInputSlots");function jm(e){let n=e.workflow?.progressLayout;if(!n||!Array.isArray(n.buses))throw new Error("offer workflow node: workflow.progressLayout is missing or malformed");let t=n.buses.find(r=>r.key===tx);if(!t)throw new Error(`offer workflow node: progress layout has no "${tx}" bus`);return{layout:n,bus:t}}s(jm,"processBus");function p3(e){let n=e.boards??[];if(n.length===0)throw new Error(`offer workflow node: "${tx}" bus has no board to add columns to`);return n.find(t=>t.id==="prozess")??n[0]}s(p3,"processBoard");function rx(e,n){let t=e.inputs?.[n];if(t&&t.kind==="literal"&&t.value!=null)return String(t.value)}s(rx,"nodeInputLiteral");function m3(e){return e.nodes.find(n=>n.type==="end")}s(m3,"findEndNode");function ox(e){return or(e).nodes.map(t=>({id:t.id,type:t.type,label:t.label??null,outcomes:(t.outcomes??[]).map(r=>r.id),next:Object.entries(t.next??{}).map(([r,i])=>({outcome:r,target:i.to})),reads:Array.isArray(t.reads)?t.reads.map((r,i)=>Vc(r,`nodes.${t.id}.reads.${i}`)):[],reviewForm:t.type==="review"&&t.form!==void 0?Vc(t.form,`nodes.${t.id}.form`):null,notifications:Object.entries(t.notifications??{}).map(([r,i])=>({event:r,templateId:i.templateId,disabled:i.disabled===!0}))}))}s(ox,"listGraphNodes");function hq(e,n){let t=or(e),r=t.nodes.find(a=>a.id===n.id);if(!r)throw new Error(`offer workflow node set-notification: node "${n.id}" not found. Nodes: ${t.nodes.map(a=>a.id).join(", ")}`);if(!n.event)throw new Error("offer workflow node set-notification: --event is required (the node type's event id)");if(!n.templateId)throw new Error("offer workflow node set-notification: --template is required (the letter's registry key)");let i={templateId:n.templateId,...n.args&&Object.keys(n.args).length>0?{args:n.args}:{},...n.disabled===!0?{disabled:!0}:{}},o=r.notifications?.[n.event]!==void 0;return r.notifications={...r.notifications??{},[n.event]:i},{bundle:e,nodeId:n.id,event:n.event,binding:i,replaced:o}}s(hq,"setNodeNotification");function gq(e,n,t){let r=or(e),i=r.nodes.find(l=>l.id===n);if(!i)throw new Error(`offer workflow node clear-notification: node "${n}" not found. Nodes: ${r.nodes.map(l=>l.id).join(", ")}`);let o=i.notifications?.[t];if(o===void 0)throw new Error(`offer workflow node clear-notification: node "${n}" binds no letter at event "${t}" (bound: ${Object.keys(i.notifications??{}).join(", ")||"none"})`);let a={...i.notifications};return delete a[t],Object.keys(a).length===0?delete i.notifications:i.notifications=a,{bundle:e,nodeId:n,event:t,templateId:o.templateId}}s(gq,"clearNodeNotification");function Ho(e){let n=qm(e.field);if(e.from!==void 0&&n.length===0)throw new kn("--from names the form node \u2014 add --field <path> (the field of its form)");let t=e.from===void 0?n:n.map(r=>nx(e.from,r));return[...qm(e.address),...t]}s(Ho,"keyListAddresses");var h3={field:"reads",verb:"read"},g3={field:"requires",verb:"require"};function yq(e,n,t){if(or(e).nodes.find(i=>i.id===n)?.type==="review"&&t.op!=="clear")throw new Error(`offer workflow node ${t.op}-reads: a review node has no reads \u2014 it checks the fields its form marks review-required (SmartForm field "reviewRequired"); name the form with \`offer workflow node set --node ${n} --form '$node.<formNode>.admission'\``);return kq(e,n,t,h3)}s(yq,"editNodeReads");function wq(e,n,t){let r=or(e).nodes.find(i=>i.id===n);if(r&&r.type!=="completenessCheck")throw new Error(`offer workflow node ${t.op}-requires: only a completenessCheck node carries \`requires\` ("${n}" is "${r.type}") \u2014 for the fields a person reads before acting use *-reads`);return kq(e,n,t,g3)}s(wq,"editNodeRequires");function kq(e,n,t,r){let{field:i,verb:o}=r,a=or(e),l=a.nodes.find(g=>g.id===n);if(!l)throw new Error(`offer workflow node ${i}: node "${n}" not found. Nodes: ${a.nodes.map(g=>g.id).join(", ")}`);let d=l[i];if(d!==void 0&&(!Array.isArray(d)||d.some(g=>!we(g))))throw new Error(`offer workflow node ${i}: node "${n}" carries a malformed \`${i}\` (${JSON.stringify(d)}) \u2014 every entry is an address; a bundle exported before addresses carries bare keys: export it again`);let c=[...d??[]];if(t.op!=="clear"&&t.addresses.length===0)throw new Error(`offer workflow node ${t.op}-${i}: name at least one --address (or --from <formNode> --field <path>)`);let u=`--address (${i})`,f=t.op==="clear"?[]:t.addresses.flatMap(g=>typeof g=="string"?ex(Gr(e),n,u,[g]):[g]),m=s((g,b)=>g.some(A=>se(A)===se(b)),"has"),y,k=[];switch(t.op){case"set":y=xq(f);break;case"add":y=[...c];for(let g of f)m(y,g)?k.push(g):y.push(g);break;case"remove":{let g=f.filter(b=>!m(c,b));if(g.length>0)throw new Error(`offer workflow node remove-${i}: node "${n}" does not ${o} ${g.map(se).join(", ")} (${i}: ${c.map(se).join(", ")||"nothing"})`);y=c.filter(b=>!m(f,b));break}case"clear":y=[];break}return y.length===0?delete l[i]:l[i]=y,{bundle:e,nodeId:n,before:c.map(se),after:y.map(se),added:y.filter(g=>!m(c,g)).map(se),removed:c.filter(g=>!m(y,g)).map(se),unchanged:k.map(se)}}s(kq,"editNodeKeyList");function bq(e,n){if(!u3(n.type))throw new Error(`offer workflow node add: unknown/unsupported type "${n.type}". Supported: ${Km.join(", ")}.`);let t=n.type==="decision"||n.type==="review";if(n.after!==void 0&&n.onEdge!==void 0)throw new Error("offer workflow node add: --after or --on-edge, not both");if(n.onEdge!==void 0&&(n.type==="end"||n.type==="join"))throw new Error(`offer workflow node add: --on-edge splices a node into a chain \u2014 not an "${n.type}" node`);if(n.decisionOutcomes?.length&&!t)throw new Error(`offer workflow node add: --decision-outcomes is only valid on a decision node (got "${n.type}")`);if(!t){if(n.assignDecision)throw new Error(`offer workflow node add: --assign-decision is only valid on a decision node (got "${n.type}")`);if(n.commentRequired?.length)throw new Error(`offer workflow node add: --comment-required is only valid on a decision node (got "${n.type}")`);if(n.decisionAsTask)throw new Error(`offer workflow node add: --decision-as-task is only valid on a decision node (got "${n.type}")`)}let r=n.type==="completenessCheck";if(r||b3(n,"offer workflow node add",n.type),n.type!=="engagePush"&&(n.engageTarget!==void 0||n.engageContractFields!==void 0||n.engageConfig!==void 0))throw new Error(`offer workflow node add: --engage-target/--engage-contract-fields/--engage-config are only valid on an engagePush node (got "${n.type}")`);if(n.condition!==void 0&&n.type!=="if")throw new Error(`offer workflow node add: --condition is only valid on an if node (got "${n.type}")`);if(n.target!==void 0&&n.type!=="setFlag")throw new Error(`offer workflow node add: --target is only valid on a setFlag node (got "${n.type}")`);if(n.contract!==void 0&&n.type!=="countersign"&&n.type!=="engagePush")throw new Error(`offer workflow node add: --contract is only valid on a countersign or engagePush node (got "${n.type}")`);if(n.payment!==void 0&&n.type!=="engagePush")throw new Error(`offer workflow node add: --payment is only valid on an engagePush node (got "${n.type}")`);if(n.whenNothingOwed!==void 0&&n.type!=="review")throw new Error(`offer workflow node add: --when-nothing-owed is only valid on a review node (got "${n.type}")`);if(n.formSource!==void 0&&n.type!=="engagePush"&&n.type!=="review")throw new Error(`offer workflow node add: --form as an address is only valid on an engagePush or review node (got "${n.type}")`);if(n.type!=="countersign"&&(n.assignTeam!==void 0&&n.type!=="engagePush"||n.titleDe!==void 0||n.titleEn!==void 0||n.dueInDays!==void 0))throw new Error(`offer workflow node add: --assign-team/--title/--title-en/--due-in-days are only valid on a countersign node (got "${n.type}")`);if(n.tasks?.length){for(let I of n.tasks)if(I.params?.onReject==="spawnRevision"&&!I.params.revisionGroup)throw new Error(`offer workflow node add: task "${I.key}" has params.onReject 'spawnRevision' but no revisionGroup \u2014 append it as the 5th field of --task (\u2026:<revisionGroup>).`)}let i=or(e),o=f3(n.type);if(n.adoptForm!==void 0&&n.type!=="form")throw new Error(`offer workflow node add: --adopt-form is only valid on a form node (got "${n.type}")`);if(n.type==="form"&&n.adoptForm!==void 0&&n.formSlug)throw new Error("offer workflow node add: --adopt-form continues the named form's instance \u2014 it takes no --form ([form.adopt-xor-create])");if(n.type==="form"&&n.adoptForm===void 0){if(!n.formSlug)throw new Error("offer workflow node add: --type form needs --form <slug> (bind an existing form), --new-form --label <l> (scaffold + bind in one step) or --adopt-form '$node.<formNode>.admission' (continue that form's instance)");if(!e.smartforms?.[n.formSlug])throw new Error(`offer workflow node add: no smartform "${n.formSlug}" in this bundle \u2014 create it with \`offer form add\` or pass --new-form.`)}let a=n.onEdge?.from??n.after,l=a?i.nodes.find(I=>I.id===a):m3(i);if(n.onEdge&&!l)throw new Error(`offer workflow node add: --on-edge node "${n.onEdge.from}" not found. Nodes: ${i.nodes.map(I=>I.id).join(", ")}`);if(n.onEdge&&l&&l.next?.[n.onEdge.outcome]===void 0)throw new Error(`offer workflow node add: --on-edge "${l.id}" has no edge "${n.onEdge.outcome}" (edges: ${Object.keys(l.next??{}).join(", ")||"none"})`);if(n.after&&!l)throw new Error(`offer workflow node add: --after node "${n.after}" not found. Nodes: ${i.nodes.map(I=>I.id).join(", ")}`);if(!l)throw new Error("offer workflow node add: graph has no end node to insert before, and no --after given");let d=n.id??gs(n.type,i.nodes.map(I=>I.id));if(i.nodes.some(I=>I.id===d))throw new Error(`offer workflow node add: node id "${d}" already exists`);let c=n.type==="form"?(Object.keys(n.outcomeTargets??{}).length?Object.keys(n.outcomeTargets):["standard"]).map(I=>({id:I,label:I==="standard"?{de:"Standard",en:"Standard"}:{de:I,en:""}})):t&&n.decisionOutcomes?.length?n.decisionOutcomes.map(I=>({id:I.id,label:I.label,semantic:I.semantic})):o.outcomes??[],u=v3(n,l),f={},m=n.outcomeTargets??{};if(n.type!=="end")if(c.length===0)if(Object.keys(m).length>0)for(let[I,v]of Object.entries(m))f[I]={to:v};else u&&(f.done={to:u});else{for(let I of c){let v=m[I.id]??u;v&&(f[I.id]={to:v})}for(let[I,v]of Object.entries(m))I in f||(f[I]={to:v})}let y=un(n.label,n.labelEn,"offer workflow node add"),k={id:d,type:n.type,label:y,...c.length>0?{outcomes:c.map(I=>({...I}))}:{},...Object.keys(f).length>0?{next:f}:{}},g={};if(n.type==="end"){let I=Sq(n);g.applicationOutcome={kind:"literal",value:I},g.dataDecision={kind:"literal",value:Aq(n.dataDecision)}}else if(!r){if(n.type==="roleAssign"){let I=Tq(n);if(n.person===void 0||n.person==="")throw new Error("offer workflow node add: --type roleAssign needs --person '<address>' \u2014 the party that gets the role, e.g. --person '$node.form.admission.beneficiary'. It is never defaulted.");g.roleKey={kind:"literal",value:I},g.mode={kind:"literal",value:Eq(n)}}else if(n.type==="form"&&n.formSlug)g.smartForm={kind:"literal",value:n.formSlug};else if(n.type!=="form"){if(n.type!=="engagePush"){if(n.type!=="collectPayment"){if(n.type==="review")g[Qt]=Dq("offer workflow node add",n.whenNothingOwed??"park");else if(n.type!=="setFlag"){if(n.type==="waitlist"){if(n.waitlistOrder===void 0)throw new Error(`offer workflow node add: --type waitlist needs --waitlist-order (${Yt.join("|")}) \u2014 the queue's order. It is not defaulted.`);if(!Yt.includes(n.waitlistOrder))throw new Error(`offer workflow node add: --waitlist-order must be one of ${Yt.join("|")} (got "${n.waitlistOrder}")`);g.waitlistOrder={kind:"literal",value:n.waitlistOrder}}else for(let I of mq(o,{id:d,type:n.type}))if(!(!I.required||I.inspector!=="literal-only"))throw new Error(`offer workflow node add: type "${n.type}" has a required literal-only input "${I.id}" that the CLI cannot author \u2014 add this node by hand. See playbooks/add-workflow-node.md.`)}}}}}if(Object.keys(g).length>0&&(k.inputs=g),t&&(n.assignDecision&&(k.assign={decision:n.assignDecision}),n.commentRequired?.length&&(k.commentRequired=Object.fromEntries(n.commentRequired.map(I=>[I,!0]))),n.decisionAsTask&&(k.decisionAsTask=n.decisionAsTask)),n.artifacts?.length&&(k.artifacts=n.artifacts),n.tasks?.length&&(k.tasks=n.tasks),n.type==="setFlag"){if(!n.flagKey)throw new Error("offer workflow node add: --flag-key is required for a setFlag node");if(!n.target)throw new Error("offer workflow node add: --target '$node.<formNode>.admission' is required for a setFlag node (the form the flag is raised on)");k.inputs={...k.inputs??{},flagKey:{kind:"literal",value:n.flagKey},...n.flagValue!==void 0?{value:{kind:"literal",value:n.flagValue}}:{}}}if(n.type==="countersign"){if(!n.assignTeam)throw new Error("offer workflow node add: --type countersign needs --assign-team <permissionGroupKey> (who countersigns)");if(!n.contract)throw new Error("offer workflow node add: --type countersign needs --contract '$node.<contractNode>.contract' (the contract it countersigns)");k.assign={countersign:n.assignTeam},(n.titleDe!==void 0||n.titleEn!==void 0)&&(k.titles={countersign:un(n.titleDe,n.titleEn,"offer workflow node add","--title")}),n.dueInDays!==void 0&&(k.inputs={...k.inputs??{},dueInDays:{kind:"literal",value:n.dueInDays}})}if(n.type==="engagePush"){if(!n.assignTeam)throw new Error("offer workflow node add: --type engagePush needs --assign-team <permissionGroupKey> (who checks a stopped transfer)");let I=Fq("offer workflow node add",n.type,n.engageTarget);if(n.engageConfig===void 0)throw new Error("offer workflow node add: --type engagePush needs --engage-config <mapping.json>");if(!n.formSource)throw new Error("offer workflow node add: --type engagePush needs --form '$node.<formNode>.admission' (the form it maps)");let v=n.engageContractFields??"off";if(v!=="on"&&v!=="off")throw new Error("offer workflow node add: --engage-contract-fields is on|off");k.assign={engagePush:n.assignTeam},k.inputs={...k.inputs??{},target:I,contractFields:{kind:"literal",value:v}},k.engage=n.engageConfig}if(n.type==="if"&&(k.condition=vq(n.condition,"offer workflow node add")),r){if((n.requires??[]).length===0)throw new Error("offer workflow node add: a completenessCheck needs at least one --require '<address>' (the fields that must be there, e.g. '$node.form.admission.kind.masernschutz')");k.deadline=Iq(n,"offer workflow node add",!0),Oq(n.guestRole,n.person,"offer workflow node add"),n.guestRole!==void 0&&n.guestRole!==""&&(k.inputs={...k.inputs??{},guestRole:{kind:"literal",value:n.guestRole}})}for(let[I,v]of Object.entries(n.notifications??{}))k.notifications={...k.notifications??{},[I]:{templateId:v}};if(n.type==="collectPayment"){let I=ix(n.settlement,"offer workflow node add");k.inputs={...k.inputs??{},[Ni]:{kind:"literal",value:Rq(n.article,"offer workflow node add")},[Ht]:{kind:"literal",value:I},...$q(I,n.payee,"offer workflow node add")},n.reason&&(k.inputs[Ci]={kind:"literal",value:n.reason})}else if(n.settlement!==void 0||n.article!==void 0||n.payee!==void 0)throw new Error(`offer workflow node add: --article/--settlement/--payee are only valid on a collectPayment node (got "${n.type}")`);let b=i.nodes.findIndex(I=>I.id===l.id);if(n.type==="end"||n.type==="join"&&!n.after)i.nodes.splice(b,0,k);else if(n.onEdge){let I=l.next[n.onEdge.outcome];l.next[n.onEdge.outcome]={...I,to:d},i.nodes.splice(b+1,0,k)}else if(n.after){if(l.next)for(let[I,v]of Object.entries(l.next))v.to===u&&(l.next[I]={...v,to:d});i.nodes.splice(b+1,0,k)}else{for(let I of i.nodes)if(I.next)for(let[v,R]of Object.entries(I.next))R.to===l.id&&(I.next[v]={...R,to:d});i.nodes.splice(b,0,k)}if(n.type==="join"&&n.joinFrom?.length)for(let{nodeId:I,outcome:v}of n.joinFrom){let R=i.nodes.find(Y=>Y.id===I);if(!R)throw new Error(`offer workflow node add: --from source "${I}" not found. Nodes: ${i.nodes.map(Y=>Y.id).join(", ")}`);let K=(R.outcomes??[]).map(Y=>Y.id),N=new Set(K.length?K:[js]);if(!N.has(v))throw new Error(`offer workflow node add: --from ${I}:${v} \u2014 "${v}" is not a declared outcome of "${I}" (valid: ${[...N].join(", ")})`);R.next={...R.next??{},[v]:{to:d}}}y3(e,k,n);let $=Cd({id:d,type:n.type,label:y},o),O=x3(e,n.type,$,n.progress??{});S3(e,O.states,O.mappings,O.columns,O.terminalSemantics),n.type==="end"&&Mq(e,k);let E=[];if(r){let I=["rejected","absage"].filter(v=>m[v]===void 0);I.length>0&&u&&E.push(`node "${d}": ${I.join(", ")} not routed with --outcomes \u2014 they go to "${u}" (route them to the rejection/withdrawal path, e.g. --outcomes rejected:<discard>,absage:<discard.absage>)`)}return{bundle:e,nodeId:d,events:$.states.map(I=>I.id.slice(d.length+1)),warnings:E}}s(bq,"addGraphNode");function vq(e,n){if(e===void 0||e.trim()==="")throw new Error(`${n}: an if node needs --condition '<expression>' \u2014 one DSL expression over $env, e.g. --condition '$env.staffInput.staffApplication' (declare the input with \`offer workflow staff-input set\`)`);return e.trim()}s(vq,"requireCondition");function y3(e,n,t){let r=Gr(e);t.person!==void 0&&(n.inputs={...n.inputs??{},person:{kind:"binding",address:mt(r,n.id,"--person",t.person)}}),t.target!==void 0&&(n.inputs={...n.inputs??{},target:{kind:"binding",address:mt(r,n.id,"--target",t.target)}});for(let[i,o,a]of w3){let l=t[o];l!==void 0&&(n[a]=mt(r,n.id,i,l))}for(let[i,o,a]of k3){let l=t[o];l!==void 0&&l.length>0&&(n[a]=xq(ex(r,n.id,i,l)))}}s(y3,"resolveNodeAddresses");var w3=[["--adopt-form","adoptForm","adoptForm"],["--form","formSource","form"],["--contract","contract","contract"],["--payment","payment","payment"]],k3=[["--require","requires","requires"]];function xq(e){let n=new Set;return e.filter(t=>{let r=se(t);return n.has(r)?!1:(n.add(r),!0)})}s(xq,"dedupe");function Sq(e){let n=e.outcome??"approved";if(!xo(n))throw new Error(`offer workflow node: --outcome "${n}" is not an end-node outcome (${oi.join(", ")})`);return n}s(Sq,"resolveEndOutcome");function Aq(e){if(e===void 0)throw new Error(`offer workflow node: an end node needs --data-decision (${Fi.join("|")}) \u2014 whether the application's data is kept or discarded is stated, never derived from --outcome`);if(!Pf(e))throw new Error(`offer workflow node: --data-decision "${e}" invalid (${Fi.join(", ")})`);return e}s(Aq,"resolveDataDecision");function Eq(e){let n=e.mode??"add";if(!pq.includes(n))throw new Error(`offer workflow node: --mode "${n}" invalid (${pq.join(", ")})`);return n}s(Eq,"resolveRoleMode");function Tq(e){if(!e.role||e.role.trim()==="")throw new Error("offer workflow node: --type roleAssign needs --role <key> (the role granted)");return e.role}s(Tq,"resolveRoleKey");function ix(e,n){if(!xf(e))throw new Error(`${n}: --settlement is required for a collectPayment node \u2014 one of ${Os.join(", ")} (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); got ${JSON.stringify(e)}`);return e}s(ix,"requireSettlement");function $q(e,n,t){let r=n?.trim()??"";if(e!=="online"){if(n!==void 0)throw new Error(`${t}: --payee only applies to --settlement online (a separate fee moves no money through Plexus)`);return{}}if(r==="")throw new Error(`${t}: --settlement online needs --payee <Tr\xE4ger key> \u2014 whose Stripe account takes the money (foundation.legalEntities[].key)`);return{[Jt]:{kind:"literal",value:r}}}s($q,"payeeCellFor");function Rq(e,n){if(typeof e!="string"||e.trim()==="")throw new Error(`${n}: --article is required for a collectPayment node \u2014 the key of a one-time article assigned to the offer's program (Finanzen \u2192 Artikel, billing_item_definitions.configKey)`);return e.trim()}s(Rq,"requireArticle");function b3(e,n,t){if(e.requires?.length)throw new Error(`${n}: --require is only valid on a completenessCheck node (got "${t}")`);if(e.deadlineDays!==void 0||e.deadlineUntil!==void 0)throw new Error(`${n}: --deadline-days/--deadline-until are only valid on a completenessCheck node (got "${t}")`);if(e.guestRole!==void 0)throw new Error(`${n}: --guest-role is only valid on a completenessCheck node (got "${t}")`)}s(b3,"assertNoCompletenessFlags");function Iq(e,n,t){if(e.deadlineDays!==void 0&&e.deadlineUntil!==void 0)throw new Error(`${n}: --deadline-days and --deadline-until exclude each other (a check has ONE deadline)`);if(e.deadlineDays!==void 0)return{inDays:e.deadlineDays};if(e.deadlineUntil!==void 0)return{until:e.deadlineUntil};if(t)throw new Error(`${n}: a completenessCheck needs a deadline: --deadline-days <n> or --deadline-until <YYYY-MM-DD>`)}s(Iq,"resolveCompletenessDeadline");function Oq(e,n,t){if(e!==void 0&&e!==""&&(n===void 0||n===""))throw new Error(`${t}: --guest-role needs --person '<address>' \u2014 the party the role is granted to (the beneficiary of a form: --person '$node.form.admission.beneficiary'). It is never defaulted.`);if(n!==void 0&&(e===void 0||e===""))throw new Error(`${t}: --person on a completenessCheck needs --guest-role (a bound person nothing is granted to does nothing)`)}s(Oq,"assertGuestRolePairing");function v3(e,n){return e.onEdge?n.next[e.onEdge.outcome].to:e.after?Object.values(n.next??{}).map(r=>r.to)[0]:n.id}s(v3,"resolveDefaultTarget");function x3(e,n,t,r){let i=Object.entries(r);if(i.length===0)return t;let o=t.mappings.map(c=>c.event),a=new Set(jm(e).bus.states.map(c=>c.id)),l=new Set,d=t.mappings.map(c=>{let u=r[c.event];return u===void 0?c:(l.add(c.state),{...c,state:u})});for(let[c,u]of i){if(!o.includes(c))throw new Error(`offer workflow node add: a ${n} node emits no progress event "${c}" (it emits: ${o.join(", ")||"none"})`);if(!a.has(u))throw new Error(`offer workflow node add: --progress ${c}=${u}: no state "${u}" on the process board (states: ${[...a].join(", ")})`)}return{...t,states:t.states.filter(c=>!l.has(c.id)),mappings:d,columns:t.columns.map(c=>({...c,states:c.states.filter(u=>!l.has(u))})).filter(c=>c.states.length>0),terminalSemantics:Object.fromEntries(Object.entries(t.terminalSemantics).filter(([c])=>!l.has(c)))}}s(x3,"mapProgressOntoExistingStates");function S3(e,n,t,r,i){let{bus:o}=jm(e),a=p3(o);o.states.push(...n),Object.keys(i).length>0&&(o.terminalSemantics={...o.terminalSemantics??{},...i});let l=Cm(i);l.length>0&&(o.holdsSeat=[...new Set([...o.holdsSeat??[],...l])],o.commitsSeat!==void 0&&(o.commitsSeat=[...new Set([...o.commitsSeat,...l])]));let d=e.workflow.progressWiring;if(!d||!Array.isArray(d.mappings))throw new Error("offer workflow node: workflow.progressWiring is missing or malformed");d.mappings.push(...t);let c=or(e),u=a.columns,f=[];for(let y of r){let k=u.find(g=>g.id===y.id);if(k){let g=new Set([...k.states,...y.states]);k.states=[...g],y.optional||delete k.optional}else f.push(y)}if(f.length===0)return;let m=X0([...u,...f],{nodeOrder:A3(c),columnNodeId:s(y=>E3(y,d),"columnNodeId"),terminalStateIds:new Set(Object.keys(o.terminalSemantics??{}))});u.length=0,u.push(...m)}s(S3,"mergeProgress");function A3(e){let n=new Map(e.nodes.map(a=>[a.id,a])),t=e.nodes.find(a=>a.type==="eventTrigger")??e.nodes[0],r=new Map,i=t?[t.id]:[],o=0;for(;i.length>0;){let a=i.shift();if(!r.has(a)){r.set(a,o++);for(let l of Object.values(n.get(a)?.next??{}))r.has(l.to)||i.push(l.to)}}for(let a of e.nodes)r.has(a.id)||r.set(a.id,o++);return r}s(A3,"nodeTopoOrder");function E3(e,n){let t=new Set(e.states??[]),i=n.mappings.find(o=>t.has(o.state))?.match;return i&&"nodeId"in i?i.nodeId:void 0}s(E3,"wiringNodeIdForColumn");function Pq(e,n){let t=or(e),r=t.nodes.find(c=>c.id===n.id);if(!r)throw new Error(`offer workflow node set: node "${n.id}" not found. Nodes: ${t.nodes.map(c=>c.id).join(", ")}`);let i=[];if((n.label!==void 0||n.labelEn!==void 0)&&(wn(r,"label",{de:n.label,en:n.labelEn},`offer workflow node set: node "${n.id}"`),i.push("label")),n.assignDecision!==void 0||n.commentRequired!==void 0||n.requiresOneOf!==void 0){if(r.type!=="decision")throw new Error(`offer workflow node set: --assign-decision/--comment-required/--requires-one-of only valid on a decision node ("${n.id}" is "${r.type}")`);if(n.assignDecision!==void 0){if(n.assignDecision.length===0)throw new Error("offer workflow node set: --assign-decision cannot be empty");r.assign={decision:n.assignDecision},i.push("assign.decision")}n.commentRequired!==void 0&&(r.commentRequired=Object.fromEntries(n.commentRequired.map(c=>[c,!0])),i.push("commentRequired")),n.requiresOneOf!==void 0&&(n.requiresOneOf.length===0?delete r.requiresOneOf:r.requiresOneOf=n.requiresOneOf,i.push("requiresOneOf"))}if(n.artifacts!==void 0&&(r.artifacts=n.artifacts,i.push("artifacts")),n.tasks!==void 0){for(let c of n.tasks)if(c.params?.onReject==="spawnRevision"&&!c.params.revisionGroup)throw new Error(`offer workflow node set: task "${c.key}" has params.onReject 'spawnRevision' but no revisionGroup.`);r.tasks=n.tasks,i.push("tasks")}let a=Gr(e),l=s((c,u)=>mt(a,r.id,c,u),"address");if(n.flagKey!==void 0||n.flagValue!==void 0||n.target!==void 0){if(r.type!=="setFlag")throw new Error(`offer workflow node set: --flag-key/--flag-value/--target only valid on a setFlag node ("${n.id}" is "${r.type}")`);let c=["target","flagKey","value"].filter(u=>u in r);if(c.length>0)throw new Error(`offer workflow node set: setFlag node "${n.id}" still carries ${c.join(", ")} as node properties (an export from before they became inputs) \u2014 export the offer again after the migration moveSetFlagConfigToInputsInGraphs ran; publish refuses this shape ([graph/retiredField]).`);if(n.target!==void 0&&(r.inputs={...r.inputs??{},target:{kind:"binding",address:l("--target",n.target)}},i.push("inputs.target")),n.flagKey!==void 0){if(n.flagKey==="")throw new Error("offer workflow node set: --flag-key needs a flag key");r.inputs={...r.inputs??{},flagKey:{kind:"literal",value:n.flagKey}},i.push("inputs.flagKey")}n.flagValue!==void 0&&(r.inputs={...r.inputs??{},value:{kind:"literal",value:n.flagValue}},i.push("inputs.value"))}if(n.form!==void 0){if(r.type==="form"){if(!e.smartforms?.[n.form])throw new Error(`offer workflow node set: no smartform "${n.form}" in this bundle \u2014 create it with \`offer form add\` first.`);r.inputs={...r.inputs??{},smartForm:{kind:"literal",value:n.form}}}else if(r.type==="governedDocument"&&r.production==="resolver"||r.type==="engagePush"||r.type==="review")r.form=l("--form",n.form);else throw new Error(`offer workflow node set: --form only valid on a form node (slug), a resolver governedDocument, an engagePush or a review node (address) ("${n.id}" is "${r.type}")`);i.push("form")}if(n.contract!==void 0){if(r.type!=="countersign"&&r.type!=="engagePush")throw new Error(`offer workflow node set: --contract only valid on a countersign or engagePush node ("${n.id}" is "${r.type}")`);r.contract=l("--contract",n.contract),i.push("contract")}if(n.payment!==void 0){if(r.type!=="engagePush")throw new Error(`offer workflow node set: --payment only valid on an engagePush node ("${n.id}" is "${r.type}")`);r.payment=l("--payment",n.payment),i.push("payment")}if(n.engageTarget!==void 0&&(r.inputs={...r.inputs??{},target:Fq("offer workflow node set",r.type,n.engageTarget)},i.push("inputs.target")),n.whenNothingOwed!==void 0){if(r.type!=="review")throw new Error(`offer workflow node set: --when-nothing-owed only valid on a review node ("${n.id}" is "${r.type}")`);r.inputs={...r.inputs??{},[Qt]:Dq("offer workflow node set",n.whenNothingOwed)},i.push(`inputs.${Qt}`)}if(n.condition!==void 0){if(r.type!=="if")throw new Error(`offer workflow node set: --condition only valid on an if node ("${n.id}" is "${r.type}")`);r.condition=vq(n.condition,"offer workflow node set"),i.push("condition")}if(n.outcomeSemantics!==void 0){if(r.type!=="decision"&&r.type!=="review")throw new Error(`offer workflow node set: --outcome-semantics only valid on a decision or review node ("${n.id}" is "${r.type}")`);let c=r.outcomes??[];for(let[u,f]of Object.entries(n.outcomeSemantics)){let m=c.find(y=>y.id===u);if(m===void 0)throw new Error(`offer workflow node set: --outcome-semantics names "${u}", which is no outcome of "${n.id}" (${c.map(y=>y.id).join(", ")})`);m.semantic=f}i.push("outcomes.semantic")}if(n.outcome!==void 0||n.dataDecision!==void 0){if(r.type!=="end")throw new Error(`offer workflow node set: --outcome/--data-decision only valid on an end node ("${n.id}" is "${r.type}")`);let c=Sq({outcome:n.outcome??rx(r,"applicationOutcome")});r.inputs={...r.inputs??{},applicationOutcome:{kind:"literal",value:c},dataDecision:{kind:"literal",value:Aq(n.dataDecision??rx(r,"dataDecision"))}},Mq(e,r),i.push("outcome")}if(n.deadlineDays!==void 0||n.deadlineUntil!==void 0||n.guestRole!==void 0||n.person!==void 0&&r.type==="completenessCheck"){if(r.type!=="completenessCheck")throw new Error(`offer workflow node set: --deadline-days/--deadline-until/--guest-role only valid on a completenessCheck node ("${n.id}" is "${r.type}")`);let c=Iq(n,"offer workflow node set",!1);c!==void 0&&(r.deadline=c,i.push("deadline"));let u={...r.inputs??{}},f=u.person,m=f?.kind==="binding"?se(f.address):void 0;if(n.guestRole===""){if(n.person!==void 0)throw new Error('offer workflow node set: --guest-role "" drops the role and its person \u2014 do not pass --person with it');delete u.guestRole,delete u.person,i.push("inputs.guestRole","inputs.person")}else{let y=u.guestRole,k=n.guestRole??(y?.kind==="literal"&&typeof y.value=="string"?y.value:void 0),g=n.person??m;Oq(k,g,"offer workflow node set"),n.guestRole!==void 0&&(u.guestRole={kind:"literal",value:n.guestRole},i.push("inputs.guestRole")),n.person!==void 0&&(u.person={kind:"binding",address:l("--person",n.person)},i.push("inputs.person"))}r.inputs=u}if(n.role!==void 0||n.mode!==void 0||n.person!==void 0&&r.type!=="completenessCheck"){if(r.type!=="roleAssign")throw new Error(`offer workflow node set: --role/--mode only valid on a roleAssign node, --person on a roleAssign or completenessCheck node ("${n.id}" is "${r.type}")`);if(r.inputs={...r.inputs??{}},n.role!==void 0&&(r.inputs.roleKey={kind:"literal",value:Tq({role:n.role})},i.push("role")),n.mode!==void 0&&(r.inputs.mode={kind:"literal",value:Eq({mode:n.mode})},i.push("mode")),n.person!==void 0){if(n.person==="")throw new Error("offer workflow node set: --person cannot be empty on a roleAssign node (e.g. '$node.form.admission.beneficiary')");r.inputs.person={kind:"binding",address:l("--person",n.person)},i.push("person")}}if(n.signing!==void 0&&r.type==="countersign"){if(!Id.includes(n.signing))throw new Error(`offer workflow node set: --signing "${n.signing}" on a countersign node \u2014 expected one of ${Id.join(", ")}`);let c=tq(r,n.signing);for(let u of Object.keys(r))delete r[u];Object.assign(r,c),i.push("signing")}if(n.approval!==void 0||n.approveTitle!==void 0||n.confirmIssue!==void 0||n.confirmTerms!==void 0||n.termsQuestion!==void 0||n.responseDueDays!==void 0||n.signing!==void 0&&r.type!=="countersign"){if(r.type!=="governedDocument")throw new Error(`offer workflow node set: --approval/--approve-title/--confirm-issue/--confirm-terms/--terms-question-*/--response-due-days/--signing only valid on a governedDocument node ("${n.id}" is "${r.type}")`);let c=r;if(n.signing!==void 0){if(!Xv.includes(n.signing))throw new Error(`offer workflow node set: --signing "${n.signing}" \u2014 expected one of ${Xv.join(", ")}`);c=dq(c,n.signing),i.push("responseStrategy")}if(n.approval!==void 0||n.approveTitle!==void 0){let u=n.approval??c.approval;if(!Bo.includes(u))throw new Error(`offer workflow node set: --approval "${u}" \u2014 expected one of ${Bo.join(", ")}`);if(n.approveTitle!==void 0&&u!=="release")throw new Error("offer workflow node set: --approve-title needs --approval release (the title belongs to the Freigabe task)");c=rq(c,u,n.approveTitle!==void 0?{de:n.approveTitle,en:n.approveTitle}:void 0),i.push("approval")}n.confirmIssue!==void 0&&(c=iq(c,n.confirmIssue),i.push("confirmBeforeIssue")),n.confirmTerms!==void 0&&(c=oq(c,n.confirmTerms),i.push("confirmContractTerms")),n.termsQuestion!==void 0&&(c=sq(c,n.termsQuestion),i.push("contractTermsQuestionText")),n.responseDueDays!==void 0&&(c=lq(c,n.responseDueDays),i.push("responseDueInDays"));for(let u of Object.keys(r))delete r[u];Object.assign(r,c)}if(n.settlement!==void 0||n.article!==void 0||n.reason!==void 0||n.payee!==void 0){if(r.type!=="collectPayment")throw new Error(`offer workflow node set: --article/--settlement/--reason/--payee only valid on a collectPayment node ("${n.id}" is "${r.type}")`);if(n.reason!==void 0&&(r.inputs={...r.inputs??{},[Ci]:{kind:"literal",value:n.reason}},i.push(Ci)),n.settlement!==void 0||n.payee!==void 0){let c=r.inputs?.[Ht],u=n.settlement!==void 0?ix(n.settlement,"offer workflow node set"):c?.kind==="literal"?String(c.value):ix(void 0,"offer workflow node set"),f=r.inputs?.[Jt],m=n.payee??(u==="online"&&f?.kind==="literal"?String(f.value):void 0),{[Jt]:y,...k}=r.inputs??{};r.inputs={...k,[Ht]:{kind:"literal",value:u},...$q(u,m,"offer workflow node set")},n.settlement!==void 0&&i.push("settlement"),(n.payee!==void 0||f!==void 0&&u!=="online")&&i.push(Jt)}n.article!==void 0&&(r.inputs={...r.inputs??{},[Ni]:{kind:"literal",value:Rq(n.article,"offer workflow node set")}},i.push("article"))}if(n.traeger!==void 0){if(r.type!=="governedDocument"||r.production!=="resolver")throw new Error(`offer workflow node set: --traeger only valid on a generated contract (governedDocument, production resolver) ("${n.id}" is "${r.type}")`);let c=n.traeger.trim();if(c==="")throw new Error("offer workflow node set: --traeger needs a legal entity key (foundation.legalEntities[].key)");r.inputs={...r.inputs??{},[qt]:{kind:"literal",value:c}},i.push(qt)}if(n.outcomeTargets&&Object.keys(n.outcomeTargets).length>0&&T3(t,r,n.outcomeTargets,i),i.length===0)throw new Error("offer workflow node set: nothing to change \u2014 pass --label/--label-en/--assign-decision/--form/--target/--contract/--payment/--outcomes/--approval/--confirm-issue/--confirm-terms/--terms-question-de+en/--response-due-days/--signing/--deadline-days/--deadline-until/--guest-role/--settlement/--payee/--article/--traeger/--condition/--engage-target/--when-nothing-owed");return{bundle:e,nodeId:n.id,changed:i}}s(Pq,"setGraphNode");function T3(e,n,t,r){let i=new Set(e.nodes.map(l=>l.id)),o=(n.outcomes??[]).map(l=>l.id),a=new Set(o.length?o:[js]);n.next={...n.next??{}};for(let[l,d]of Object.entries(t)){if(!a.has(l))throw new Error(`offer workflow node set: outcome "${l}" is not a declared outcome of "${n.id}" (valid: ${[...a].join(", ")})`);if(!i.has(d))throw new Error(`offer workflow node set: routing target "${d}" is not an existing node id (nodes: ${[...i].join(", ")})`);n.next[l]={...n.next[l]??{},to:d},r.push(`next.${l}`)}}s(T3,"rewriteRouting");function _q(e,n){let t=or(e),r=t.nodes.find(l=>l.id===n);if(!r)throw new Error(`offer workflow node rm: node "${n}" not found. Nodes: ${t.nodes.map(l=>l.id).join(", ")}`);if(r.type==="eventTrigger")throw new Error(`offer workflow node rm: refusing to remove the start node "${n}"`);if(r.type==="end")throw new Error(`offer workflow node rm: refusing to remove the end node "${n}"`);fq(e,n);let i=[...new Set(Object.values(r.next??{}).map(l=>l.to))];if(i.length>1)throw new Error(`offer workflow node rm: node "${n}" has multiple successors (${i.join(", ")}); splice-removal needs a single successor. Edit the bundle manually.`);let o=i[0];for(let l of t.nodes)if(l.next)for(let[d,c]of Object.entries(l.next))c.to===n&&(o?l.next[d]={...c,to:o}:delete l.next[d]);t.nodes=t.nodes.filter(l=>l.id!==n);let a=$3(e,n);return{bundle:e,removedStates:a}}s(_q,"removeGraphNode");function $3(e,n){let t=jm(e).bus,r=e.workflow.progressWiring,i=r&&Array.isArray(r.mappings)?r.mappings:[],o=s(c=>"nodeId"in c.match&&c.match.nodeId===n,"isOwn"),a=new Set(i.filter(c=>!o(c)).map(c=>c.state)),l=[...new Set(i.filter(o).map(c=>c.state))].filter(c=>!a.has(c)),d=new Set(l);if(t.states=t.states.filter(c=>!d.has(c.id)),t.terminalSemantics)for(let c of l)delete t.terminalSemantics[c];for(let c of t.boards??[])c.columns=c.columns.map(u=>({...u,states:u.states.filter(f=>!d.has(f))})).filter(u=>u.states.length>0);return r&&(r.mappings=i.filter(c=>!o(c))),l}s($3,"stripProgress");function Nq(e){if(e.from===void 0!=(e.field===void 0))throw new Error("offer workflow node set-input: --from and --field go together (the field of that node's form)");if([e.address!==void 0,e.from!==void 0,e.literal!==void 0,e.clear===!0].filter(Boolean).length!==1)throw new Error("offer workflow node set-input: name exactly one of --address, --from/--field, --literal or --clear");if(e.clear===!0)return null;if(e.address!==void 0)return{kind:"address",raw:e.address};if(e.from!==void 0)return{kind:"binding",address:nx(e.from,e.field)};let t;try{t=JSON.parse(e.literal)}catch{throw new Error(`offer workflow node set-input: --literal is JSON \u2014 a text needs its quotes ('"de"'), got ${e.literal}`)}if(!(t===null||["string","number","boolean"].includes(typeof t))&&!Ii(t))throw new Error('offer workflow node set-input: --literal must be a scalar or a priced item ({"itemKey":\u2026,"grantKeys":[\u2026]})');return{kind:"literal",value:t}}s(Nq,"parseInputCell");function Cq(e,n,t,r){let i=or(e),o=i.nodes.find(m=>m.id===n);if(!o)throw new Error(`offer workflow node set-input: no node "${n}" (nodes: ${i.nodes.map(m=>m.id).join(", ")})`);if(t.trim()==="")throw new Error("offer workflow node set-input: --input is empty");let a=r?.kind==="address"?{kind:"binding",address:mt(Gr(e),n,"--address",r.raw)}:r;if(o.type==="end"&&a!==null)throw new Error(`offer workflow node set-input: "${n}" is an end node \u2014 its outcome cells are set with \`offer workflow node set --outcome|--data-decision\``);let l=Uo[o.type];if(!l)throw new Error(`offer workflow node set-input: no spec for node type "${o.type}"`);let d=mq(l,o),c=d.find(m=>m.id===t);if(c===void 0&&a!==null){let m=ei(o),y=m===null?null:`${m.kind}:${m.key}`,k=o.generatorStamp,g="`plexus-cli --env <env> --tenant <slug> offer workflow restamp-pins --dir <dir>`",b=mr(o),A=o.templateStamp;throw new Error(`offer workflow node set-input: "${n}" (${o.type}) has no input slot "${t}" (slots: ${d.map($=>$.id).join(", ")||"none"})`+(b!==null&&o.production==="template"?A===void 0?` \u2014 the parameters of template ${b} are on its record, not stamped here yet: run ${g} first`:` \u2014 template ${b} declares no parameter "${t}" (as stamped); declare it on the record (catalog documentTemplates[].parameters), then run ${g}`:y===null?"":k?.inputSchema===void 0?` \u2014 its generator ${y} is not stamped, so its parameters are unknown offline: run ${g} first`:` \u2014 the stamp of ${y} lists its parameters as they were when stamped; if the generator or package changed since, run ${g}`))}if(t===Kn)throw new Error(`offer workflow node set-input: "${Kn}" names the node's generator \u2014 set it with \`offer workflow node set-generator --node ${n} --generator|--package <key>\``);if(c!==void 0&&a?.kind==="literal"){let m=kl(a.value,c);if(m!==null)throw new Error(`offer workflow node set-input: ${n}.${t}: ${m}`)}let u={...o.inputs??{}},f=u[t];if(a===null){if(f===void 0)throw new Error(`offer workflow node set-input: node "${n}" has no input "${t}" to clear (inputs: ${Object.keys(u).join(", ")||"none"})`);delete u[t]}else u[t]=a;return Object.keys(u).length===0?delete o.inputs:o.inputs=u,{bundle:e,before:f,after:a??void 0}}s(Cq,"setNodeInput");function Dq(e,n){if(!mw(n))throw new Error(`${e}: --when-nothing-owed "${n}" \u2014 expected one of ${Eo.join(", ")}`);return{kind:"literal",value:n}}s(Dq,"reviewModeInput");function Fq(e,n,t){if(n!=="engagePush")throw new Error(`${e}: --engage-target is only valid on an engagePush node (got "${n}")`);if(t!=="sandbox"&&t!=="production"){let r=t===void 0?"nothing":`"${t}"`;throw new Error(`${e}: --engage-target sandbox|production is required on an engagePush node (got ${r})`)}return{kind:"literal",value:t}}s(Fq,"engageTargetInput");function Lq(e,n,t){let r=or(e),i=r.nodes.find(a=>a.id===n);if(!i)throw new Error(`offer workflow node set-engage: no node "${n}" (nodes: ${r.nodes.map(a=>a.id).join(", ")})`);if(i.type!=="engagePush")throw new Error(`offer workflow node set-engage: "${n}" is a ${i.type} node, not engagePush`);let o=i.engage;return i.engage=t,{bundle:e,before:o}}s(Lq,"setNodeEngageConfig");function Mq(e,n){let t=rx(n,"applicationOutcome");if(typeof t!="string"||!xo(t))return;let r=Ls[t],o=e.workflow.progressWiring?.mappings.find(d=>d.event===r&&"nodeId"in d.match&&d.match.nodeId===n.id);if(o===void 0)return;let{bus:a}=jm(e),l=a.terminalSemantics?.[o.state];if(!(l===void 0||l.outcome===t)){if(o.state!==`${n.id}.${r}`)throw new Error(`offer workflow node: end "${n.id}" (${t}) reaches the shared state "${o.state}", which seals "${String(l.outcome)}" \u2014 map its "${r}" event onto a state that seals "${t}"`);a.terminalSemantics={...a.terminalSemantics??{},[o.state]:{...l,outcome:t}}}}s(Mq,"alignEndTerminal");var R3="offer workflow node optional-action";function vn(e,n){throw new kn(`${R3} ${e}: ${n}`)}s(vn,"refuse");function Kq(e,n,t){let r=e.workflow?.graph;e.workflow||vn(t,"das B\xFCndel enth\xE4lt keine workflow.json."),(!r||!Array.isArray(r.nodes))&&vn(t,"workflow.graph hat keine Knotenliste.");let i=r.nodes,o=i.find(a=>a.id===n);return o||vn(t,`Knoten \u201E${n}" gibt es nicht. Knoten: ${i.map(a=>a.id).join(", ")}.`),o.optionalActions!==void 0&&!Array.isArray(o.optionalActions)&&vn(t,`Knoten \u201E${n}" tr\xE4gt eine fehlerhafte \`optionalActions\`-Liste \u2014 workflow.json zuerst reparieren.`),o}s(Kq,"findNode");function Bm(e,n,t){let r=n.trim();r||vn(e,"darf nicht leer sein.");let i=t?.trim();return t!==void 0&&!i&&vn(`${e}-en`,"darf nicht leer sein."),{de:r,en:i||r}}s(Bm,"bilingual");function I3(e){let n=e.split(",").map(t=>t.trim()).filter(Boolean);return n.length===0&&vn("--tasks","leere Liste \u2014 mindestens einen Aufgabenschl\xFCssel des Knotens nennen."),n}s(I3,"parseTasks");function qq(e){return{key:e.key,action:e.action,label:e.label,...e.description!==void 0?{description:e.description}:{},...e.trigger!==void 0?{trigger:e.trigger}:{},tasks:e.tasks,...e.repeatable===!0?{repeatable:!0}:{}}}s(qq,"ordered");function jq(e,n,t,r){let i=Kq(e,n,"set");t.trim()||vn("set","--key darf nicht leer sein.");let o=i.optionalActions??[],a=o.findIndex(u=>u.key===t),l=a<0?null:structuredClone(o[a]);l!==null&&l.action!=="spawnTasks"&&vn("set",`\u201E${t}" auf ${n} ist keine spawnTasks-Aktion (${String(l.action)}).`),l===null&&(r.label===void 0&&vn("set","--label ist Pflicht f\xFCr eine neue Aktion (der Eintrag im Men\xFC \u201EWeiteres\u201C)."),r.tasks===void 0&&vn("set","--tasks ist Pflicht f\xFCr eine neue Aktion (Aufgabenschl\xFCssel des Knotens, a,b)."),(r.clearDescription||r.clearTrigger)&&vn("set","--clear-* gibt es nur beim \xC4ndern \u2014 eine neue Aktion hat nichts zu entfernen.")),r.description!==void 0&&r.clearDescription&&vn("set","--description und --clear-description schlie\xDFen einander aus."),r.trigger!==void 0&&r.clearTrigger&&vn("set","--trigger und --clear-trigger schlie\xDFen einander aus.");let d=l===null?{key:t,action:"spawnTasks"}:structuredClone(l);if(r.label!==void 0?d.label=Bm("--label",r.label,r.labelEn):r.labelEn!==void 0&&(d.label={...d.label,en:Bm("--label",d.label.de,r.labelEn).en}),r.clearDescription&&(d.description===void 0&&vn("set",`\u201E${t}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete d.description),r.description!==void 0?d.description=Bm("--description",r.description,r.descriptionEn):r.descriptionEn!==void 0&&(d.description===void 0&&vn("set","--description-en braucht --description."),d.description={...d.description,en:Bm("--description",d.description.de,r.descriptionEn).en}),r.tasks!==void 0&&(d.tasks=I3(r.tasks)),r.clearTrigger&&(d.trigger===void 0&&vn("set",`\u201E${t}" hat kein --trigger \u2014 --clear-trigger hat nichts zu entfernen.`),delete d.trigger),r.trigger!==void 0){let u=r.trigger.trim();u||vn("--trigger","darf nicht leer sein (Schl\xFCssel einer Berechtigungsgruppe)."),d.trigger=u}r.repeatable===!0?d.repeatable=!0:r.repeatable===!1&&delete d.repeatable;let c=qq(d);return l!==null&&JSON.stringify(qq(l))===JSON.stringify(c)&&vn("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aktion \u201E${t}".`),i.optionalActions=a<0?[...o,c]:o.map((u,f)=>f===a?c:u),{bundle:e,nodeId:n,key:t,before:l,after:c}}s(jq,"setOptionalAction");function Bq(e,n,t){let r=Kq(e,n,"remove"),i=r.optionalActions??[],o=i.find(l=>l.key===t);o||vn("remove",`Knoten \u201E${n}" hat keine optionale Aktion \u201E${t}" (Aktionen: ${i.map(l=>l.key).join(", ")||"keine"}).`),r.requiresOneOf?.includes(t)===!0&&vn("remove",`\u201E${t}" steht in 'requiresOneOf' von ${n} \u2014 zuerst die Regel \xE4ndern (node set --requires-one-of \u2026).`);let a=i.filter(l=>l.key!==t);return a.length===0?delete r.optionalActions:r.optionalActions=a,{bundle:e,nodeId:n,key:t,before:o,after:null}}s(Bq,"removeOptionalAction");function Um(e){if(!e.workflow)throw new Error("offer workflow channels: bundle carries no workflow.json");let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow channels: workflow.graph has no nodes array");return n}s(Um,"graphOf");function Uq(e,n){let t=Um(e),{channels:r,...i}=t,o=n.length>0?{...i,channels:n}:i;return{...e,workflow:{...e.workflow,graph:o}}}s(Uq,"withChannels");function Vq(e){let n=Um(e),t=PP(n).map(i=>({key:Hf(i),label:i,members:[Hf(i)],source:"derived"})),r=Hs(n).map(i=>({key:i.key,label:_e(i.label),members:[...i.members],source:"authored"}));return[...t,...r]}s(Vq,"listChannels");function Gq(e,n){let t=Hs(Um(e)),r="offer workflow channels add",i={de:"--label",en:"--label-en"},o=n.key===void 0?void 0:t.find(f=>f.key===n.key),a=o===void 0?Hn({de:n.label,en:n.labelEn},r,i):Xt(o.label,{de:n.label,en:n.labelEn},r,i)??o.label,l=n.key??_P(a.de,new Set(t.map(f=>f.key))),d={key:l,label:a,members:n.teams.map(f=>f.startsWith("team:")?f:Hf(f))},c=t.findIndex(f=>f.key===l),u=[...t];return c>=0?u[c]=d:u.push(d),{bundle:Uq(e,u),channel:d,replaced:c>=0}}s(Gq,"upsertChannel");function zq(e,n){let t=Hs(Um(e)),r=t.find(i=>i.key===n);if(r===void 0){let i=t.map(o=>o.key).join(", ")||"\u2014";throw new Error(`offer workflow channels: no authored channel "${n}" (authored: ${i}). Derived team channels cannot be removed \u2014 they follow the teams the process assigns.`)}return{bundle:Uq(e,t.filter(i=>i.key!==n)),removed:r}}s(zq,"removeChannel");var Jo="offer workflow staff-input";function Wq(e){if(!e.workflow)throw new Error(`${Jo}: bundle carries no workflow.json`);let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error(`${Jo}: workflow.graph has no nodes array`);return n}s(Wq,"graphOf");function sx(e){let n=Wq(e).staffInputs;if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`${Jo}: workflow.graph.staffInputs is not a list (${JSON.stringify(n)}) \u2014 fix workflow.json`);return n}s(sx,"declared");function Yq(e,n){let{staffInputs:t,...r}=Wq(e),i=n.length>0?{...r,staffInputs:n}:r;return{...e,workflow:{...e.workflow,graph:i}}}s(Yq,"withStaffInputs");function Hq(e){return sx(e).map(n=>({key:n.key,type:n.type,label:n.label,reads:_R(n.key)}))}s(Hq,"listStaffInputs");function Jq(e,n){if(!sl.test(n.key))throw new Error(`${Jo} set: key "${n.key}" \u2014 a key starts with a lower-case letter and holds only letters and digits (it is read as one identifier: $env.staffInput.<key>)`);let t=sx(e),r=t.findIndex(c=>c.key===n.key),i={de:"--label",en:"--label-en"},o=r>=0?t[r]:void 0,a=o===void 0?Hn({de:n.label,en:n.labelEn},`${Jo} set`,i):Xt(o.label,{de:n.label,en:n.labelEn},`${Jo} set`,i)??o.label,l={key:n.key,type:"boolean",label:a},d=[...t];return r>=0?d[r]=l:d.push(l),{bundle:Yq(e,d),input:l,replaced:r>=0}}s(Jq,"setStaffInput");function Qq(e,n){let t=sx(e),r=t.find(i=>i.key===n);if(r===void 0)throw new Error(`${Jo} remove: no staff input "${n}" (declared: ${t.map(i=>i.key).join(", ")||"none"})`);return{bundle:Yq(e,t.filter(i=>i.key!==n)),removed:r}}s(Qq,"removeStaffInput");var Zq=["task","approval"],Xq=["respawn","stayClosed"],O3="offer workflow node task";function ce(e,n){throw new kn(`${O3} ${e}: ${n}`)}s(ce,"refuse");function lx(e,n){let t=e.workflow?.graph;return e.workflow||ce(n,"das B\xFCndel enth\xE4lt keine workflow.json."),(!t||!Array.isArray(t.nodes))&&ce(n,"workflow.graph hat keine Knotenliste."),t.nodes}s(lx,"graphNodes");function dx(e,n,t){let r=lx(e,t),i=r.find(o=>o.id===n);return i||ce(t,`Knoten \u201E${n}" gibt es nicht. Knoten: ${r.map(o=>o.id).join(", ")}.`),i.tasks!==void 0&&!Array.isArray(i.tasks)&&ce(t,`Knoten \u201E${n}" tr\xE4gt eine fehlerhafte \`tasks\`-Liste \u2014 workflow.json zuerst reparieren.`),i}s(dx,"findNode");function P3(e,n){let t=e.trim(),r=t.lastIndexOf(":"),i=r<0?n:t.slice(0,r).trim(),o=r<0?t:t.slice(r+1).trim();return(!i||!o)&&ce("--blocks",`\u201E${e}" ist kein Ziel \u2014 erwartet <knotenId>:<templateKey> oder nur <templateKey> f\xFCr denselben Knoten.`),i===n?{templateKey:o}:{node:i,templateKey:o}}s(P3,"parseBlocksTarget");function ax(e,n){let t=e.split(",").map(r=>r.trim()).filter(Boolean);return t.length===0&&ce(n,"leere Liste \u2014 mindestens einen Eintrag nennen oder die Option weglassen."),t}s(ax,"parseList");function _3(e,n){let t=e.indexOf("="),r=t<0?"":e.slice(0,t).trim(),i=t<0?"":e.slice(t+1),o=i.indexOf("|"),a=(o<0?i:i.slice(0,o)).trim(),l=o<0?a:i.slice(o+1).trim();return(!r||!a||!l)&&ce(n,`\u201E${e}" ist fehlerhaft \u2014 erwartet <schl\xFCssel>=<Bezeichnung> oder <schl\xFCssel>=<Bezeichnung>|<English>.`),{key:r,label:{de:a,en:l}}}s(_3,"parseKeyedLabel");function N3(e){return _3(e,"--option")}s(N3,"parseResultOption");function C3(e,n,t){let r;try{r=JSON.parse(e)}catch{ce("--field",`\u201E${e}" ist kein JSON-Objekt \u2014 erwartet z. B. {"key":"rang","type":"number","label":{"de":"Rang","en":"Rank"},"writes":"rang"}.`)}(typeof r!="object"||r===null||Array.isArray(r))&&ce("--field",`\u201E${e}" ist kein JSON-Objekt.`);let i=r,o=i.suggest;if(o?.kind==="form"){let a=o.address;typeof a=="string"?i.suggest={kind:"form",address:mt(n,t,"--field suggest.address",a)}:(typeof a!="object"||a===null)&&Ea(n,t,"--field suggest",JSON.stringify(o),'ein Formular-Vorschlag nennt seine Adresse \u2014 {"kind":"form","address":"$node.<Formular>.admission.<Export>"}.')}return i}s(C3,"parseRecordField");function D3(e){let n=Number(e);return(!/^\s*\d+\s*$/.test(e)||!Number.isInteger(n)||n<=0)&&ce("--due-in-days",`\u201E${e}" ist keine positive ganze Zahl von Tagen.`),n}s(D3,"parseDueInDays");function F3(e){return!Oi(e)&&e!=="appointment"&&ce("--result",`unbekannter Ergebnistyp \u201E${e}" \u2014 erlaubt: ${[...bs,"appointment"].map(n=>`${n} (${ni[n].label.de})`).join(", ")}.`),e}s(F3,"parseResultType");function L3(e,n,t,r,i){let o=`'$task.${r}.<schl\xFCssel>'`;i.trim().startsWith("$")||ce(e,`--writes \u201E${i}": ein nackter Schl\xFCssel \u2014 --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${o}.`);let a=mt(n,t,"--writes",i);return(a.scope!=="task"||a.owner!==r)&&ce(e,`--writes \u201E${i}": --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${o}.`),a.path!==void 0&&ce(e,`--writes \u201E${i}": eine Aufgabe schreibt ihren Wert als Ganzes \u2014 ${o} ohne Pfad.`),a.key}s(L3,"parseWritesArg");function M3(e,n,t,r){let i="'$derived.<schl\xFCssel>' ohne Pfad";r.trim().startsWith("$")||ce(e,`--prices \u201E${r}": ein nackter Schl\xFCssel \u2014 --prices nennt einen abgeleiteten Preis \u2014 ${i}.`);let o=mt(n,t,"--prices",r);return(o.scope!=="derived"||o.path!==void 0)&&ce(e,`--prices \u201E${r}": --prices nennt einen abgeleiteten Preis \u2014 ${i}.`),o.key}s(M3,"parsePricesArg");function q3(e,n,t){let r=n.resultLabel?.trim()??t?.de;(r===void 0||r.length===0)&&ce(e,"--result-label nennt den Namen des Werts (deutsch, nicht leer), z. B. \u201ESchulgeld mit Erm\xE4\xDFigung\u201C."),n.resultLabelEn!==void 0&&n.resultLabelEn.trim().length===0&&ce(e,"--result-label-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Name auch im Englischen.");let i=n.resultLabelEn?.trim()??(n.resultLabel!==void 0?r:t?.en??r);return{de:r,en:i}}s(q3,"resultLabelOf");function K3(e){let n=Number(e);return(!/^\s*\d+\s*$/.test(e)||!Number.isInteger(n)||n<So||n>Ao)&&ce("--duration",`\u201E${e}" ist keine Dauer \u2014 erwartet ganze Minuten von ${So} bis ${Ao}.`),n}s(K3,"parseDuration");function j3(e){let n=e.trim();return n==="external"&&ce("--chat",'\u201Eexternal" ist kein Ziel \u2014 ein Aufgabenergebnis erreicht die Familie nie. Erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.'),Ss(n)===null&&ce("--chat",`\u201E${e}" ist kein Ziel \u2014 erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.`),n}s(j3,"checkChat");function Tn(e,n,t,r,i,o){let a=s(l=>{let d=n[l];return Array.isArray(d)?d.length>0:d!==void 0&&d!==!1},"has");a(t)&&a(r)&&ce(e,`${i} und ${o} schlie\xDFen einander aus.`)}s(Tn,"exclusive");function eK(e,n,t,r,i,o){Tn(e,o,"blocks","clearBlocks","--blocks","--clear-blocks"),Tn(e,o,"result","clearResult","--result","--clear-result"),Tn(e,o,"options","clearResult","--option","--clear-result"),Tn(e,o,"chat","clearResult","--chat","--clear-result"),Tn(e,o,"textRequired","clearResult","--text-required","--clear-result"),Tn(e,o,"duration","clearResult","--duration","--clear-result"),Tn(e,o,"resultTitle","clearResult","--result-title","--clear-result"),Tn(e,o,"resultTitleEn","clearResult","--result-title-en","--clear-result"),Tn(e,o,"writes","clearResult","--writes","--clear-result"),Tn(e,o,"prices","clearResult","--prices","--clear-result"),Tn(e,o,"item","clearResult","--item","--clear-result"),Tn(e,o,"resultLabel","clearResult","--result-label","--clear-result"),Tn(e,o,"resultLabelEn","clearResult","--result-label-en","--clear-result"),Tn(e,o,"when","clearWhen","--when","--clear-when"),Tn(e,o,"onConditionReturn","clearWhen","--on-condition-return","--clear-when"),Tn(e,o,"reads","clearReads","--reads","--clear-reads"),Tn(e,o,"documents","clearDocuments","--documents","--clear-documents"),Tn(e,o,"description","clearDescription","--description","--clear-description"),Tn(e,o,"descriptionEn","clearDescription","--description-en","--clear-description");let a=[],l=structuredClone(i??{key:r});if(o.kind!==void 0?(Zq.includes(o.kind)||ce(e,`--kind \u201E${o.kind}" ist unbekannt \u2014 erlaubt: ${Zq.join(", ")}.`),l.kind=o.kind):i===null&&(l.kind="task"),o.title!==void 0){let f=o.title.trim();f||ce(e,"--title darf nicht leer sein."),l.title={de:f,en:o.titleEn?.trim()||f}}else if(o.titleEn!==void 0){i===null&&ce(e,"--title-en braucht --title.");let f=o.titleEn.trim();f||ce(e,"--title-en darf nicht leer sein."),l.title={...l.title,en:f}}if(o.team!==void 0){let f=o.team.trim();f||ce(e,"--team darf nicht leer sein (Schl\xFCssel einer Berechtigungsgruppe)."),l.assign={...l.assign??{},group:f}}o.dueInDays!==void 0&&(l.params={...l.params??{},dueInDays:D3(o.dueInDays)}),o.clearBlocks&&(l.blocks===void 0&&ce(e,`Aufgabe \u201E${r}" blockiert nichts \u2014 --clear-blocks hat nichts zu entfernen.`),delete l.blocks),o.blocks!==void 0&&(l.blocks?.except!==void 0&&a.push("blocks.except"),l.blocks=P3(o.blocks,t)),o.clearResult&&(l.result===void 0&&ce(e,`Aufgabe \u201E${r}" hat kein Ergebnis \u2014 --clear-result hat nichts zu entfernen.`),delete l.result);let d=(o.options?.length??0)>0||(o.fields?.length??0)>0||o.writes!==void 0||o.prices!==void 0||o.item!==void 0||o.resultLabel!==void 0||o.resultLabelEn!==void 0||o.textRequired!==void 0||o.chat!==void 0,c=o.duration!==void 0||o.resultTitle!==void 0||o.resultTitleEn!==void 0;if(o.result!==void 0||d||c){let f=o.result!==void 0?F3(o.result):l.result?.kind;if(f===void 0&&ce(e,`--option, --text-required, --chat, --writes, --prices, --item, --result-label, --duration und --result-title brauchen ein Ergebnis \u2014 --result ${[...bs,"appointment"].join("|")} angeben.`),f==="appointment"){d&&ce(e,"--option, --text-required, --chat, --writes, --prices, --item und --result-label gelten nicht f\xFCr einen Termin \u2014 ein Termin-Ergebnis nimmt keinen Text und tr\xE4gt keinen Wert.");let m=l.result?.kind==="appointment"?l.result:void 0;l.result!==void 0&&m===void 0&&a.push("result (vorheriger Ergebnistyp)");let y=o.resultTitle?.trim()??m?.title.de;(y===void 0||y.length===0)&&ce(e,"--result appointment braucht --result-title (neutraler Titel des Termins \u2014 steht im Familienbrief und in der Kalenderdatei).");let k=o.duration!==void 0?K3(o.duration):m?.durationMinutes;k===void 0&&ce(e,"--result appointment braucht --duration <Minuten> (vorbelegte Dauer im Termin-Dialog)."),o.resultTitleEn!==void 0&&o.resultTitleEn.trim().length===0&&ce(e,"--result-title-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Titel auch im Englischen.");let g=o.resultTitleEn?.trim()??(o.resultTitle!==void 0?y:m?.title.en??y);l.result={kind:"appointment",title:{de:y,en:g},durationMinutes:k}}else{c&&ce(e,`--duration und --result-title gelten nur f\xFCr --result appointment \u2014 hier: ${f} (${ni[f].label.de}).`);let m=l.result!==void 0&&xs(l.result)?l.result:void 0;l.result?.kind==="appointment"&&a.push("result (Termin)");let y={kind:f};m?.chat!==void 0&&(y.chat=m.chat),m?.textRequired!==void 0&&(f==="freetext"?a.push("result.textRequired"):y.textRequired=m.textRequired),m?.options!==void 0&&(f==="choice"?y.options=m.options:a.push("result.options")),m?.fields!==void 0&&(f==="record"?y.fields=m.fields:a.push("result.fields"));let k=ni[f].valueType!==null;m?.writes!==void 0&&(k?y.writes=m.writes:a.push("result.writes")),m?.label!==void 0&&(k?y.label=m.label:a.push("result.label")),m?.prices!==void 0&&(f==="reduction"?y.prices=m.prices:a.push("result.prices")),m?.item!==void 0&&(f==="pricedItem"?y.item=m.item:a.push("result.item"));let g=bs.filter(A=>ni[A].valueType!==null).join(", "),b=`hier: ${f} (${ni[f].label.de})`;if(o.writes!==void 0&&(k||ce(e,`--writes gibt es nur bei Ergebnissen mit Wert (${g}) \u2014 ${b}.`),y.writes=L3(e,n,t,r,o.writes)),o.prices!==void 0&&(f!=="reduction"&&ce(e,`--prices gibt es nur beim Ergebnistyp reduction \u2014 ${b}.`),y.prices=M3(e,n,t,o.prices)),o.item!==void 0){f!=="pricedItem"&&ce(e,`--item gibt es nur beim Ergebnistyp pricedItem \u2014 ${b}.`);let A=o.item.trim();A.length===0&&ce(e,"--item darf nicht leer sein (der Schl\xFCssel des Artikels, z. B. tuition)."),y.item=A}(o.resultLabel!==void 0||o.resultLabelEn!==void 0)&&(k||ce(e,`--result-label gibt es nur bei Ergebnissen mit Wert (${g}) \u2014 ${b}.`),y.label=q3(e,o,y.label)),(o.fields?.length??0)>0&&(f!=="record"&&ce(e,`--field gibt es nur beim Ergebnistyp record (Erfassung) \u2014 hier: ${f} (${ni[f].label.de}).`),y.fields=o.fields.map(A=>C3(A,n,t))),(o.options?.length??0)>0&&(f!=="choice"&&ce(e,`--option gibt es nur beim Ergebnistyp choice (Auswahl) \u2014 hier: ${f} (${ni[f].label.de}).`),y.options=o.options.map(N3)),o.textRequired!==void 0&&(f==="freetext"&&ce(e,"--text-required/--no-text-required gibt es beim Freitext nicht \u2014 sein Text ist immer Pflicht."),o.textRequired?y.textRequired=!0:delete y.textRequired),o.chat!==void 0&&(y.chat=j3(o.chat)),l.result=y}}if(o.clearWhen&&(l.when===void 0&&l.onConditionReturn===void 0&&ce(e,`Aufgabe \u201E${r}" hat keine Bedingung \u2014 --clear-when hat nichts zu entfernen.`),delete l.when,delete l.onConditionReturn),o.when!==void 0&&(l.when=mt(n,t,"--when",o.when)),o.onConditionReturn!==void 0&&(Xq.includes(o.onConditionReturn)||ce(e,`--on-condition-return \u201E${o.onConditionReturn}" ist unbekannt \u2014 erlaubt: ${Xq.join(", ")}.`),l.when===void 0&&ce(e,"--on-condition-return braucht eine Bedingung (--when)."),l.onConditionReturn=o.onConditionReturn),o.clearReads&&(l.reads===void 0&&ce(e,`Aufgabe \u201E${r}" liest keine Felder \u2014 --clear-reads hat nichts zu entfernen.`),delete l.reads),o.reads!==void 0&&(l.reads=ax(o.reads,"--reads").map(f=>mt(n,t,"--reads",f))),o.clearDocuments&&(l.documents===void 0&&ce(e,`Aufgabe \u201E${r}" verweist auf keine Dokumente \u2014 --clear-documents hat nichts zu entfernen.`),delete l.documents),o.documents!==void 0&&(l.documents=ax(o.documents,"--documents").map(f=>{try{return a_(f)}catch(m){Ea(n,t,"--documents",f,m instanceof Error?m.message:String(m))}})),o.locksEvidence&&o.clearLocksEvidence&&ce(e,"--locks-evidence und --clear-locks-evidence schlie\xDFen sich aus."),o.clearLocksEvidence&&(l.locksEvidence===void 0&&ce(e,`Aufgabe \u201E${r}" sperrt keine Belege \u2014 --clear-locks-evidence hat nichts zu entfernen.`),delete l.locksEvidence),o.locksEvidence&&(l.locksEvidence=!0),o.clearDescription&&(l.description===void 0&&ce(e,`Aufgabe \u201E${r}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete l.description),o.description!==void 0){let f=o.description.trim();f||ce(e,"--description darf nicht leer sein (entfernen mit --clear-description)."),l.description={de:f,en:o.descriptionEn?.trim()||f}}else if(o.descriptionEn!==void 0){l.description===void 0&&ce(e,"--description-en braucht --description.");let f=o.descriptionEn.trim();f||ce(e,"--description-en darf nicht leer sein."),l.description={...l.description,en:f}}if(o.clearOptional&&((o.optional!==void 0||o.optionalEn!==void 0)&&ce(e,"--clear-optional schlie\xDFt --optional und --optional-en aus."),l.optional===void 0&&ce(e,`Aufgabe \u201E${r}" ist nicht optional \u2014 --clear-optional hat nichts zu entfernen.`),delete l.optional),o.optional!==void 0){let f=o.optional.trim();f||ce(e,"--optional braucht die Worte des Knopfs (z. B. \u201EKeine Einsch\xE4tzung abgeben\u201C)."),l.optional={skipLabel:{de:f,en:o.optionalEn?.trim()||f}}}else if(o.optionalEn!==void 0){l.optional===void 0&&ce(e,"--optional-en braucht --optional.");let f=o.optionalEn.trim();f||ce(e,"--optional-en darf nicht leer sein."),l.optional={skipLabel:{...l.optional.skipLabel,en:f}}}if(o.clearAppointment&&((o.appointmentOf!==void 0||o.dueDaysAfterEnd!==void 0)&&ce(e,"--clear-appointment schlie\xDFt --appointment-of und --due-days-after-end aus."),l.appointment===void 0&&ce(e,`Aufgabe \u201E${r}" ist keine Terminaufgabe \u2014 --clear-appointment hat nichts zu entfernen.`),delete l.appointment),o.appointmentOf!==void 0||o.dueDaysAfterEnd!==void 0){let f=o.appointmentOf?.trim()??l.appointment?.of;f||ce(e,"--due-days-after-end braucht --appointment-of (die Aufgabe, die den Termin bucht).");let m=o.dueDaysAfterEnd?.trim();m!==void 0&&!/^\d+$/.test(m)&&ce(e,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(o.dueDaysAfterEnd)}.`);let y=m!==void 0?Number(m):l.appointment?.dueDaysAfterEnd;y===void 0&&ce(e,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(o.dueDaysAfterEnd)}.`),l.appointment={of:f,dueDaysAfterEnd:y}}let u=o.familyRequestFields!==void 0||o.familyRequestFrom!==void 0;if(Tn(e,o,"familyRequestFields","familyRequestFrom","--family-request-fields","--family-request-from"),o.clearFamilyRequest&&(u&&ce(e,"--clear-family-request schlie\xDFt die \xFCbrigen --family-request-*-Flags aus."),l.familyRequest===void 0&&ce(e,`Aufgabe \u201E${r}" fordert nichts bei der Familie an \u2014 --clear-family-request hat nichts zu entfernen.`),delete l.familyRequest),o.familyRequestFields!==void 0){let f=ax(o.familyRequestFields,"--family-request-fields").map(m=>mt(n,t,"--family-request-fields",m));l.familyRequest={fields:f}}return o.familyRequestFrom!==void 0&&(l.familyRequest={from:mt(n,t,"--family-request-from",o.familyRequestFrom)}),{next:U3(l),dropped:a}}s(eK,"applyFlags");var B3=["key","kind","title","description","assign","params","blocks","result","when","onConditionReturn","reads","locksEvidence","documents","familyRequest","optional","appointment"];function U3(e){let n=e,t={};for(let r of B3)n[r]!==void 0&&(t[r]=n[r]);for(let[r,i]of Object.entries(n))!(r in t)&&i!==void 0&&(t[r]=i);return t}s(U3,"normalizeOrder");var V3=[["kind",e=>e.kind],["title",e=>e.title],["description",e=>e.description],["assign.group",e=>e.assign?.group],["params.dueInDays",e=>e.params?.dueInDays],["blocks",e=>e.blocks?{...e.blocks}:void 0],["result",e=>e.result],["when",e=>e.when],["onConditionReturn",e=>e.onConditionReturn],["reads",e=>e.reads],["locksEvidence",e=>e.locksEvidence],["documents",e=>e.documents],["familyRequest",e=>e.familyRequest],["optional",e=>e.optional],["appointment",e=>e.appointment]];function cx(e,n){let t=[];for(let[r,i]of V3){let o=e?i(e):void 0,a=n?i(n):void 0;JSON.stringify(o)!==JSON.stringify(a)&&t.push({field:r,before:o,after:a})}return t}s(cx,"diffTemplates");function nK(e,n,t,r){let i=dx(e,n,"add");t.trim()||ce("add","--key darf nicht leer sein."),(i.tasks??[]).find(d=>d.key===t)&&ce("add",`Knoten \u201E${n}" hat schon eine Aufgabe \u201E${t}" \u2014 \xE4ndern mit \`task set\`, entfernen mit \`task rm\`.`),r.title===void 0&&ce("add","--title ist Pflicht (deutscher Titel der Aufgabe)."),r.team===void 0&&ce("add","--team ist Pflicht (Schl\xFCssel der Berechtigungsgruppe, die die Aufgabe bekommt).");for(let[d,c]of[["--clear-blocks",r.clearBlocks],["--clear-result",r.clearResult],["--clear-when",r.clearWhen],["--clear-reads",r.clearReads],["--clear-documents",r.clearDocuments],["--clear-locks-evidence",r.clearLocksEvidence],["--clear-description",r.clearDescription],["--clear-optional",r.clearOptional],["--clear-appointment",r.clearAppointment]])c&&ce("add",`${d} gibt es nur bei \`task set\` \u2014 eine neue Aufgabe hat nichts zu entfernen.`);let{next:a,dropped:l}=eK("add",Gr(e),n,t,null,r);return i.tasks=[...i.tasks??[],a],{bundle:e,nodeId:n,key:t,before:null,after:a,changes:cx(null,a),dropped:l}}s(nK,"addNodeTask");function tK(e,n,t,r){let i=dx(e,n,"set"),o=i.tasks??[],a=o.findIndex(f=>f.key===t);a<0&&ce("set",`Knoten \u201E${n}" hat keine Aufgabe \u201E${t}" (Aufgaben: ${o.map(f=>f.key).join(", ")||"keine"}).`);let l=o[a],{next:d,dropped:c}=eK("set",Gr(e),n,t,l,r),u=cx(l,d);return u.length===0&&ce("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aufgabe \u201E${t}".`),i.tasks=o.map((f,m)=>m===a?d:f),{bundle:e,nodeId:n,key:t,before:structuredClone(l),after:d,changes:u,dropped:c}}s(tK,"setNodeTask");function G3(e,n,t){let r=[];for(let o of lx(e,"rm"))for(let a of Array.isArray(o.tasks)?o.tasks:[]){if(o.id===n&&a.key===t)continue;let l=a.blocks;l&&l.templateKey===t&&(l.node??o.id)===n&&r.push(`Aufgabe \u201E${a.key}" auf ${o.id} (blocks)`)}let i=lx(e,"rm").find(o=>o.id===n);for(let o of i?.optionalActions??[])Array.isArray(o.tasks)&&o.tasks.includes(t)&&r.push(`optionale Aktion \u201E${o.key??"?"}" auf ${n}`);return r}s(G3,"nodeTaskDependents");function rK(e,n,t){let r=dx(e,n,"rm"),i=r.tasks??[],o=i.find(d=>d.key===t);o||ce("rm",`Knoten \u201E${n}" hat keine Aufgabe \u201E${t}" (Aufgaben: ${i.map(d=>d.key).join(", ")||"keine"}).`);let a=G3(e,n,t);a.length>0&&ce("rm",`\u201E${t}" auf ${n} wird noch gebraucht von: ${a.join("; ")}. Zuerst dort das Ziel \xE4ndern (task set --blocks \u2026 / --clear-blocks) oder die Aktion anpassen.`);let l=i.filter(d=>d.key!==t);return l.length===0?delete r.tasks:r.tasks=l,{bundle:e,nodeId:n,key:t,before:o,after:null,changes:cx(o,null),dropped:[]}}s(rK,"removeNodeTask");function Gc(e){if(e===void 0)return"\u2014";if(typeof e=="string"||typeof e=="number")return String(e);let n=e;return n&&typeof n=="object"&&"de"in n&&"en"in n&&Object.keys(n).length===2?n.de===n.en?String(n.de):`${String(n.de)} | ${String(n.en)}`:JSON.stringify(e)}s(Gc,"renderTaskValue");var Vm=s(e=>({de:e,en:e}),"germanInBothLocales");function z3(e){let n=e.lastIndexOf(":"),t=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(n<=0||t===""||r==="")throw new Error(`offer workflow node add: --on-edge "${e}" must be <fromNodeId>:<outcome>`);return{from:t,outcome:r}}s(z3,"parseEdge");function W3(e){let n={};for(let t of e){let r=t.indexOf("="),i=t.slice(0,r).trim(),o=t.slice(r+1).trim();if(r<=0||i===""||o==="")throw new Error(`offer workflow node add: --progress "${t}" must be <event>=<stateId>`);if(i in n)throw new Error(`offer workflow node add: --progress names "${i}" twice`);n[i]=o}return n}s(W3,"parseProgressPairs");function Ux(e){if(!e)return{};let n={};for(let t of e.split(",")){let r=t.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed pair "${r}" (expected key:value)`);let o=r.slice(0,i).trim(),a=r.slice(i+1).trim().replace(/^["']|["']$/g,"");if(!o||!a)throw new Error(`offer workflow node: malformed pair "${r}" (empty key/value)`);n[o]=a}return n}s(Ux,"parsePairs");function Y3(e){let n=s(t=>t.replace(/^["']|["']$/g,""),"unquote");return e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>{let r=t.indexOf(":"),i=r<0?t:t.slice(0,r).trim(),{id:o,de:a,en:l}=nD(r<0?"":t.slice(r+1));if(!i||!Ri(o)||!a||l===void 0||n(l)==="")throw new Error(`offer workflow node: malformed --decision-outcomes entry "${t}" (expected <id>:<${bt.join("|")}>:<Deutsch>:<English> \u2014 meaning and both languages are required)`);return{id:i,semantic:o,label:{de:n(a),en:n(l)}}})}s(Y3,"parseDecisionOutcomes");function H3(e){let n={};for(let[t,r]of Object.entries(Ux(e))){if(!Ri(r))throw new Error(`offer workflow node set: --outcome-semantics "${t}:${r}" \u2014 the meaning is one of ${bt.join("|")}`);n[t]=r}return n}s(H3,"parseOutcomeSemantics");function J3(e){if(!e)return[];let n=[];for(let t of e.split(",")){let r=t.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed --from "${r}" (expected <nodeId>:<outcome>)`);let o=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(!o||!a)throw new Error(`offer workflow node: malformed --from "${r}" (empty nodeId/outcome)`);n.push({nodeId:o,outcome:a})}return n}s(J3,"parseJoinFrom");function Vx(e){return e.split(":").map(n=>n.trim())}s(Vx,"fields");function Gm(e){return e?e.split(",").map(n=>n.trim()).filter(Boolean):[]}s(Gm,"parseIdList");function aK(e,n){if(e===void 0||e==="")return;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error(`offer workflow node: malformed ${n} dueInDays "${e}" (expected a positive integer)`);return t}s(aK,"parseDueInDays");function lK(e,n){if(!n||n.length===0)return e;for(let t of n){let[r,i,...o]=Vx(t);if(!r||!i)throw new Error(`offer workflow node: malformed --task-blocks "${t}" (expected <taskKey>:<target>)`);let a=e.find(d=>d.key===r);if(a===void 0)throw new Error(`offer workflow node: --task-blocks "${t}" names task "${r}", which is not among the --task entries (${e.map(d=>d.key).join(", ")||"none"})`);let l=o.filter(d=>d.length>0);if(l.length>0)throw new Error(`offer workflow node: malformed --task-blocks "${t}" \u2014 a blocker holds its target's whole action group; there is no third field (got ${l.map(d=>JSON.stringify(d)).join(", ")})`);a.blocks={templateKey:i}}return e}s(lK,"applyTaskBlocks");function dK(e,n){if(!e)return[];let t=n!==void 0;if(t&&n!=="spawnRevision")throw new Error(`offer workflow node: --task-on-reject must be 'spawnRevision' (got "${n}")`);return e.map(r=>{let i=Vx(r),[o,a,l,d]=i;if(!o||!a||!l)throw new Error(`offer workflow node: malformed --task "${r}" (expected key:kind:title:group[\u2026] \u2014 kind task|approval)`);if(a==="task"){let c=aK(i[4],"--task");return{key:o,kind:a,title:Vm(l),...d?{assign:{group:d}}:{},...c!==void 0?{params:{dueInDays:c}}:{}}}if(a==="approval"){let[,,,,c]=i,u={};return t&&(u.onReject="spawnRevision"),c&&(u.revisionGroup=c),{key:o,kind:a,title:Vm(l),...d?{assign:{group:d}}:{},...Object.keys(u).length>0?{params:u}:{}}}throw new Error(`offer workflow node: malformed --task "${r}" \u2014 kind must be 'task' | 'approval' (got "${a}")`)})}s(dK,"parseTasks");function cK(e){return e?e.map(n=>{let[t,r,i,...o]=Vx(n),a=o.join(":");if(!t||!r||!i)throw new Error(`offer workflow node: malformed --artifact "${n}" (expected key:type:visibility:label)`);if(i!=="internal"&&i!=="external")throw new Error(`offer workflow node: --artifact "${n}" \u2014 visibility must be 'internal' | 'external' (got "${i}")`);if(!Df(r))throw new Error(`offer workflow node: --artifact "${n}" \u2014 type must be one of ${Ks.join(" | ")} (got "${r}")`);return{key:t,type:r,visibility:i,...a?{label:Vm(a)}:{}}}):[]}s(cK,"parseArtifacts");function iK(e){if(e===void 0)return;let n=e.split(":"),t=n[n.length-1],r=n.length>1&&/^\d+$/.test(t)?Number(t):void 0,i=r!==void 0?n.slice(0,-1).join(":"):e;if(!i)throw new Error(`offer workflow node: malformed --decision-as-task "${e}" (expected title[:dueInDays])`);return{title:Vm(i),...r!==void 0?{dueInDays:r}:{}}}s(iK,"parseDecisionAsTask");function Q3(e){let n={};for(let t of e??[]){let r=t.indexOf("=");if(r<=0)throw new Error(`offer workflow node: malformed --literal "${t}" (expected <param>=<value>)`);let i=t.slice(0,r).trim(),o=t.slice(r+1);if(!i)throw new Error(`offer workflow node: malformed --literal "${t}" (empty parameter)`);n[i]=o==="true"?{literal:!0}:o==="false"?{literal:!1}:/^-?\d+(\.\d+)?$/.test(o.trim())?{literal:Number(o.trim())}:{literal:o}}return n}s(Q3,"parseNotificationLiterals");function uK(e){if(e!==void 0){if(!/^\d+$/.test(e.trim()))throw new Error(`offer workflow node: malformed --deadline-days "${e}" (expected whole days, e.g. 14)`);return Number(e.trim())}}s(uK,"parseDeadlineDays");function Z3(e){if(!e||e.length===0)return;let n={};for(let t of e){let r=t.indexOf("="),i=r>0?t.slice(0,r).trim():"",o=r>0?t.slice(r+1).trim():"";if(!i||!o)throw new Error(`offer workflow node: malformed --notification "${t}" (expected <event>=<templateId>)`);if(i in n)throw new Error(`offer workflow node: --notification names event "${i}" twice`);n[i]=o}return n}s(Z3,"parseNotificationBindings");function oK(e,n){if(n==="true")return!0;if(n==="false")return!1;throw new Error(`offer workflow node: ${e} must be 'true' | 'false' (got "${n}")`)}s(oK,"parseBoolOption");function ux(e){if(e!==void 0){if(e==="true")return!0;if(e==="false")return!1;throw new Error(`offer workflow node: --flag-value must be 'true' | 'false' (got "${e}")`)}}s(ux,"parseFlagValue");function mi(e,n,t=` \u2192 NOT written (fix validation errors)
10848
+ `).join(""))}s(fq,"refuseWhileNamed");var pq=["add","remove","replace"],Km=["form","decision","review","setFlag","waitlist","roleAssign","join","collectPayment","completenessCheck","countersign","engagePush","if","end"],tx="process";function u5(e){return Km.includes(e)}s(u5,"isSupported");function or(e){if(!e.workflow)throw new Error("offer workflow node: bundle carries no workflow.json");let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow node: workflow.graph has no nodes array");return n}s(or,"graphOf");function f5(e){let n=Uo[e];if(!n)throw new Error(`offer workflow node: no spec registered for type "${e}"`);return n}s(f5,"specFor");function mq(e,n){let t=e.inputs;return typeof t!="function"?[]:t(n)}s(mq,"specInputSlots");function jm(e){let n=e.workflow?.progressLayout;if(!n||!Array.isArray(n.buses))throw new Error("offer workflow node: workflow.progressLayout is missing or malformed");let t=n.buses.find(r=>r.key===tx);if(!t)throw new Error(`offer workflow node: progress layout has no "${tx}" bus`);return{layout:n,bus:t}}s(jm,"processBus");function p5(e){let n=e.boards??[];if(n.length===0)throw new Error(`offer workflow node: "${tx}" bus has no board to add columns to`);return n.find(t=>t.id==="prozess")??n[0]}s(p5,"processBoard");function rx(e,n){let t=e.inputs?.[n];if(t&&t.kind==="literal"&&t.value!=null)return String(t.value)}s(rx,"nodeInputLiteral");function m5(e){return e.nodes.find(n=>n.type==="end")}s(m5,"findEndNode");function ox(e){return or(e).nodes.map(t=>({id:t.id,type:t.type,label:t.label??null,outcomes:(t.outcomes??[]).map(r=>r.id),next:Object.entries(t.next??{}).map(([r,i])=>({outcome:r,target:i.to})),reads:Array.isArray(t.reads)?t.reads.map((r,i)=>Vc(r,`nodes.${t.id}.reads.${i}`)):[],reviewForm:t.type==="review"&&t.form!==void 0?Vc(t.form,`nodes.${t.id}.form`):null,notifications:Object.entries(t.notifications??{}).map(([r,i])=>({event:r,templateId:i.templateId,disabled:i.disabled===!0}))}))}s(ox,"listGraphNodes");function hq(e,n){let t=or(e),r=t.nodes.find(a=>a.id===n.id);if(!r)throw new Error(`offer workflow node set-notification: node "${n.id}" not found. Nodes: ${t.nodes.map(a=>a.id).join(", ")}`);if(!n.event)throw new Error("offer workflow node set-notification: --event is required (the node type's event id)");if(!n.templateId)throw new Error("offer workflow node set-notification: --template is required (the letter's registry key)");let i={templateId:n.templateId,...n.args&&Object.keys(n.args).length>0?{args:n.args}:{},...n.disabled===!0?{disabled:!0}:{}},o=r.notifications?.[n.event]!==void 0;return r.notifications={...r.notifications??{},[n.event]:i},{bundle:e,nodeId:n.id,event:n.event,binding:i,replaced:o}}s(hq,"setNodeNotification");function gq(e,n,t){let r=or(e),i=r.nodes.find(l=>l.id===n);if(!i)throw new Error(`offer workflow node clear-notification: node "${n}" not found. Nodes: ${r.nodes.map(l=>l.id).join(", ")}`);let o=i.notifications?.[t];if(o===void 0)throw new Error(`offer workflow node clear-notification: node "${n}" binds no letter at event "${t}" (bound: ${Object.keys(i.notifications??{}).join(", ")||"none"})`);let a={...i.notifications};return delete a[t],Object.keys(a).length===0?delete i.notifications:i.notifications=a,{bundle:e,nodeId:n,event:t,templateId:o.templateId}}s(gq,"clearNodeNotification");function Ho(e){let n=qm(e.field);if(e.from!==void 0&&n.length===0)throw new kn("--from names the form node \u2014 add --field <path> (the field of its form)");let t=e.from===void 0?n:n.map(r=>nx(e.from,r));return[...qm(e.address),...t]}s(Ho,"keyListAddresses");var h5={field:"reads",verb:"read"},g5={field:"requires",verb:"require"};function yq(e,n,t){if(or(e).nodes.find(i=>i.id===n)?.type==="review"&&t.op!=="clear")throw new Error(`offer workflow node ${t.op}-reads: a review node has no reads \u2014 it checks the fields its form marks review-required (SmartForm field "reviewRequired"); name the form with \`offer workflow node set --node ${n} --form '$node.<formNode>.admission'\``);return kq(e,n,t,h5)}s(yq,"editNodeReads");function wq(e,n,t){let r=or(e).nodes.find(i=>i.id===n);if(r&&r.type!=="completenessCheck")throw new Error(`offer workflow node ${t.op}-requires: only a completenessCheck node carries \`requires\` ("${n}" is "${r.type}") \u2014 for the fields a person reads before acting use *-reads`);return kq(e,n,t,g5)}s(wq,"editNodeRequires");function kq(e,n,t,r){let{field:i,verb:o}=r,a=or(e),l=a.nodes.find(g=>g.id===n);if(!l)throw new Error(`offer workflow node ${i}: node "${n}" not found. Nodes: ${a.nodes.map(g=>g.id).join(", ")}`);let d=l[i];if(d!==void 0&&(!Array.isArray(d)||d.some(g=>!we(g))))throw new Error(`offer workflow node ${i}: node "${n}" carries a malformed \`${i}\` (${JSON.stringify(d)}) \u2014 every entry is an address; a bundle exported before addresses carries bare keys: export it again`);let c=[...d??[]];if(t.op!=="clear"&&t.addresses.length===0)throw new Error(`offer workflow node ${t.op}-${i}: name at least one --address (or --from <formNode> --field <path>)`);let u=`--address (${i})`,f=t.op==="clear"?[]:t.addresses.flatMap(g=>typeof g=="string"?ex(Gr(e),n,u,[g]):[g]),m=s((g,b)=>g.some(A=>se(A)===se(b)),"has"),y,k=[];switch(t.op){case"set":y=xq(f);break;case"add":y=[...c];for(let g of f)m(y,g)?k.push(g):y.push(g);break;case"remove":{let g=f.filter(b=>!m(c,b));if(g.length>0)throw new Error(`offer workflow node remove-${i}: node "${n}" does not ${o} ${g.map(se).join(", ")} (${i}: ${c.map(se).join(", ")||"nothing"})`);y=c.filter(b=>!m(f,b));break}case"clear":y=[];break}return y.length===0?delete l[i]:l[i]=y,{bundle:e,nodeId:n,before:c.map(se),after:y.map(se),added:y.filter(g=>!m(c,g)).map(se),removed:c.filter(g=>!m(y,g)).map(se),unchanged:k.map(se)}}s(kq,"editNodeKeyList");function bq(e,n){if(!u5(n.type))throw new Error(`offer workflow node add: unknown/unsupported type "${n.type}". Supported: ${Km.join(", ")}.`);let t=n.type==="decision"||n.type==="review";if(n.after!==void 0&&n.onEdge!==void 0)throw new Error("offer workflow node add: --after or --on-edge, not both");if(n.onEdge!==void 0&&(n.type==="end"||n.type==="join"))throw new Error(`offer workflow node add: --on-edge splices a node into a chain \u2014 not an "${n.type}" node`);if(n.decisionOutcomes?.length&&!t)throw new Error(`offer workflow node add: --decision-outcomes is only valid on a decision node (got "${n.type}")`);if(!t){if(n.assignDecision)throw new Error(`offer workflow node add: --assign-decision is only valid on a decision node (got "${n.type}")`);if(n.commentRequired?.length)throw new Error(`offer workflow node add: --comment-required is only valid on a decision node (got "${n.type}")`);if(n.decisionAsTask)throw new Error(`offer workflow node add: --decision-as-task is only valid on a decision node (got "${n.type}")`)}let r=n.type==="completenessCheck";if(r||b5(n,"offer workflow node add",n.type),n.type!=="engagePush"&&(n.engageTarget!==void 0||n.engageContractFields!==void 0||n.engageConfig!==void 0))throw new Error(`offer workflow node add: --engage-target/--engage-contract-fields/--engage-config are only valid on an engagePush node (got "${n.type}")`);if(n.condition!==void 0&&n.type!=="if")throw new Error(`offer workflow node add: --condition is only valid on an if node (got "${n.type}")`);if(n.target!==void 0&&n.type!=="setFlag")throw new Error(`offer workflow node add: --target is only valid on a setFlag node (got "${n.type}")`);if(n.contract!==void 0&&n.type!=="countersign"&&n.type!=="engagePush")throw new Error(`offer workflow node add: --contract is only valid on a countersign or engagePush node (got "${n.type}")`);if(n.payment!==void 0&&n.type!=="engagePush")throw new Error(`offer workflow node add: --payment is only valid on an engagePush node (got "${n.type}")`);if(n.whenNothingOwed!==void 0&&n.type!=="review")throw new Error(`offer workflow node add: --when-nothing-owed is only valid on a review node (got "${n.type}")`);if(n.formSource!==void 0&&n.type!=="engagePush"&&n.type!=="review")throw new Error(`offer workflow node add: --form as an address is only valid on an engagePush or review node (got "${n.type}")`);if(n.type!=="countersign"&&(n.assignTeam!==void 0&&n.type!=="engagePush"||n.titleDe!==void 0||n.titleEn!==void 0||n.dueInDays!==void 0))throw new Error(`offer workflow node add: --assign-team/--title/--title-en/--due-in-days are only valid on a countersign node (got "${n.type}")`);if(n.tasks?.length){for(let I of n.tasks)if(I.params?.onReject==="spawnRevision"&&!I.params.revisionGroup)throw new Error(`offer workflow node add: task "${I.key}" has params.onReject 'spawnRevision' but no revisionGroup \u2014 append it as the 5th field of --task (\u2026:<revisionGroup>).`)}let i=or(e),o=f5(n.type);if(n.adoptForm!==void 0&&n.type!=="form")throw new Error(`offer workflow node add: --adopt-form is only valid on a form node (got "${n.type}")`);if(n.type==="form"&&n.adoptForm!==void 0&&n.formSlug)throw new Error("offer workflow node add: --adopt-form continues the named form's instance \u2014 it takes no --form ([form.adopt-xor-create])");if(n.type==="form"&&n.adoptForm===void 0){if(!n.formSlug)throw new Error("offer workflow node add: --type form needs --form <slug> (bind an existing form), --new-form --label <l> (scaffold + bind in one step) or --adopt-form '$node.<formNode>.admission' (continue that form's instance)");if(!e.smartforms?.[n.formSlug])throw new Error(`offer workflow node add: no smartform "${n.formSlug}" in this bundle \u2014 create it with \`offer form add\` or pass --new-form.`)}let a=n.onEdge?.from??n.after,l=a?i.nodes.find(I=>I.id===a):m5(i);if(n.onEdge&&!l)throw new Error(`offer workflow node add: --on-edge node "${n.onEdge.from}" not found. Nodes: ${i.nodes.map(I=>I.id).join(", ")}`);if(n.onEdge&&l&&l.next?.[n.onEdge.outcome]===void 0)throw new Error(`offer workflow node add: --on-edge "${l.id}" has no edge "${n.onEdge.outcome}" (edges: ${Object.keys(l.next??{}).join(", ")||"none"})`);if(n.after&&!l)throw new Error(`offer workflow node add: --after node "${n.after}" not found. Nodes: ${i.nodes.map(I=>I.id).join(", ")}`);if(!l)throw new Error("offer workflow node add: graph has no end node to insert before, and no --after given");let d=n.id??gs(n.type,i.nodes.map(I=>I.id));if(i.nodes.some(I=>I.id===d))throw new Error(`offer workflow node add: node id "${d}" already exists`);let c=n.type==="form"?(Object.keys(n.outcomeTargets??{}).length?Object.keys(n.outcomeTargets):["standard"]).map(I=>({id:I,label:I==="standard"?{de:"Standard",en:"Standard"}:{de:I,en:""}})):t&&n.decisionOutcomes?.length?n.decisionOutcomes.map(I=>({id:I.id,label:I.label,semantic:I.semantic})):o.outcomes??[],u=v5(n,l),f={},m=n.outcomeTargets??{};if(n.type!=="end")if(c.length===0)if(Object.keys(m).length>0)for(let[I,v]of Object.entries(m))f[I]={to:v};else u&&(f.done={to:u});else{for(let I of c){let v=m[I.id]??u;v&&(f[I.id]={to:v})}for(let[I,v]of Object.entries(m))I in f||(f[I]={to:v})}let y=un(n.label,n.labelEn,"offer workflow node add"),k={id:d,type:n.type,label:y,...c.length>0?{outcomes:c.map(I=>({...I}))}:{},...Object.keys(f).length>0?{next:f}:{}},g={};if(n.type==="end"){let I=Sq(n);g.applicationOutcome={kind:"literal",value:I},g.dataDecision={kind:"literal",value:Aq(n.dataDecision)}}else if(!r){if(n.type==="roleAssign"){let I=Tq(n);if(n.person===void 0||n.person==="")throw new Error("offer workflow node add: --type roleAssign needs --person '<address>' \u2014 the party that gets the role, e.g. --person '$node.form.admission.beneficiary'. It is never defaulted.");g.roleKey={kind:"literal",value:I},g.mode={kind:"literal",value:Eq(n)}}else if(n.type==="form"&&n.formSlug)g.smartForm={kind:"literal",value:n.formSlug};else if(n.type!=="form"){if(n.type!=="engagePush"){if(n.type!=="collectPayment"){if(n.type==="review")g[Qt]=Dq("offer workflow node add",n.whenNothingOwed??"park");else if(n.type!=="setFlag"){if(n.type==="waitlist"){if(n.waitlistOrder===void 0)throw new Error(`offer workflow node add: --type waitlist needs --waitlist-order (${Yt.join("|")}) \u2014 the queue's order. It is not defaulted.`);if(!Yt.includes(n.waitlistOrder))throw new Error(`offer workflow node add: --waitlist-order must be one of ${Yt.join("|")} (got "${n.waitlistOrder}")`);g.waitlistOrder={kind:"literal",value:n.waitlistOrder}}else for(let I of mq(o,{id:d,type:n.type}))if(!(!I.required||I.inspector!=="literal-only"))throw new Error(`offer workflow node add: type "${n.type}" has a required literal-only input "${I.id}" that the CLI cannot author \u2014 add this node by hand. See playbooks/add-workflow-node.md.`)}}}}}if(Object.keys(g).length>0&&(k.inputs=g),t&&(n.assignDecision&&(k.assign={decision:n.assignDecision}),n.commentRequired?.length&&(k.commentRequired=Object.fromEntries(n.commentRequired.map(I=>[I,!0]))),n.decisionAsTask&&(k.decisionAsTask=n.decisionAsTask)),n.artifacts?.length&&(k.artifacts=n.artifacts),n.tasks?.length&&(k.tasks=n.tasks),n.type==="setFlag"){if(!n.flagKey)throw new Error("offer workflow node add: --flag-key is required for a setFlag node");if(!n.target)throw new Error("offer workflow node add: --target '$node.<formNode>.admission' is required for a setFlag node (the form the flag is raised on)");k.inputs={...k.inputs??{},flagKey:{kind:"literal",value:n.flagKey},...n.flagValue!==void 0?{value:{kind:"literal",value:n.flagValue}}:{}}}if(n.type==="countersign"){if(!n.assignTeam)throw new Error("offer workflow node add: --type countersign needs --assign-team <permissionGroupKey> (who countersigns)");if(!n.contract)throw new Error("offer workflow node add: --type countersign needs --contract '$node.<contractNode>.contract' (the contract it countersigns)");k.assign={countersign:n.assignTeam},(n.titleDe!==void 0||n.titleEn!==void 0)&&(k.titles={countersign:un(n.titleDe,n.titleEn,"offer workflow node add","--title")}),n.dueInDays!==void 0&&(k.inputs={...k.inputs??{},dueInDays:{kind:"literal",value:n.dueInDays}})}if(n.type==="engagePush"){if(!n.assignTeam)throw new Error("offer workflow node add: --type engagePush needs --assign-team <permissionGroupKey> (who checks a stopped transfer)");let I=Fq("offer workflow node add",n.type,n.engageTarget);if(n.engageConfig===void 0)throw new Error("offer workflow node add: --type engagePush needs --engage-config <mapping.json>");if(!n.formSource)throw new Error("offer workflow node add: --type engagePush needs --form '$node.<formNode>.admission' (the form it maps)");let v=n.engageContractFields??"off";if(v!=="on"&&v!=="off")throw new Error("offer workflow node add: --engage-contract-fields is on|off");k.assign={engagePush:n.assignTeam},k.inputs={...k.inputs??{},target:I,contractFields:{kind:"literal",value:v}},k.engage=n.engageConfig}if(n.type==="if"&&(k.condition=vq(n.condition,"offer workflow node add")),r){if((n.requires??[]).length===0)throw new Error("offer workflow node add: a completenessCheck needs at least one --require '<address>' (the fields that must be there, e.g. '$node.form.admission.kind.masernschutz')");k.deadline=Iq(n,"offer workflow node add",!0),Oq(n.guestRole,n.person,"offer workflow node add"),n.guestRole!==void 0&&n.guestRole!==""&&(k.inputs={...k.inputs??{},guestRole:{kind:"literal",value:n.guestRole}})}for(let[I,v]of Object.entries(n.notifications??{}))k.notifications={...k.notifications??{},[I]:{templateId:v}};if(n.type==="collectPayment"){let I=ix(n.settlement,"offer workflow node add");k.inputs={...k.inputs??{},[Ni]:{kind:"literal",value:Rq(n.article,"offer workflow node add")},[Ht]:{kind:"literal",value:I},...$q(I,n.payee,"offer workflow node add")},n.reason&&(k.inputs[Ci]={kind:"literal",value:n.reason})}else if(n.settlement!==void 0||n.article!==void 0||n.payee!==void 0)throw new Error(`offer workflow node add: --article/--settlement/--payee are only valid on a collectPayment node (got "${n.type}")`);let b=i.nodes.findIndex(I=>I.id===l.id);if(n.type==="end"||n.type==="join"&&!n.after)i.nodes.splice(b,0,k);else if(n.onEdge){let I=l.next[n.onEdge.outcome];l.next[n.onEdge.outcome]={...I,to:d},i.nodes.splice(b+1,0,k)}else if(n.after){if(l.next)for(let[I,v]of Object.entries(l.next))v.to===u&&(l.next[I]={...v,to:d});i.nodes.splice(b+1,0,k)}else{for(let I of i.nodes)if(I.next)for(let[v,R]of Object.entries(I.next))R.to===l.id&&(I.next[v]={...R,to:d});i.nodes.splice(b,0,k)}if(n.type==="join"&&n.joinFrom?.length)for(let{nodeId:I,outcome:v}of n.joinFrom){let R=i.nodes.find(Y=>Y.id===I);if(!R)throw new Error(`offer workflow node add: --from source "${I}" not found. Nodes: ${i.nodes.map(Y=>Y.id).join(", ")}`);let K=(R.outcomes??[]).map(Y=>Y.id),N=new Set(K.length?K:[js]);if(!N.has(v))throw new Error(`offer workflow node add: --from ${I}:${v} \u2014 "${v}" is not a declared outcome of "${I}" (valid: ${[...N].join(", ")})`);R.next={...R.next??{},[v]:{to:d}}}y5(e,k,n);let $=Cd({id:d,type:n.type,label:y},o),O=x5(e,n.type,$,n.progress??{});S5(e,O.states,O.mappings,O.columns,O.terminalSemantics),n.type==="end"&&Mq(e,k);let E=[];if(r){let I=["rejected","absage"].filter(v=>m[v]===void 0);I.length>0&&u&&E.push(`node "${d}": ${I.join(", ")} not routed with --outcomes \u2014 they go to "${u}" (route them to the rejection/withdrawal path, e.g. --outcomes rejected:<discard>,absage:<discard.absage>)`)}return{bundle:e,nodeId:d,events:$.states.map(I=>I.id.slice(d.length+1)),warnings:E}}s(bq,"addGraphNode");function vq(e,n){if(e===void 0||e.trim()==="")throw new Error(`${n}: an if node needs --condition '<expression>' \u2014 one DSL expression over $env, e.g. --condition '$env.staffInput.staffApplication' (declare the input with \`offer workflow staff-input set\`)`);return e.trim()}s(vq,"requireCondition");function y5(e,n,t){let r=Gr(e);t.person!==void 0&&(n.inputs={...n.inputs??{},person:{kind:"binding",address:mt(r,n.id,"--person",t.person)}}),t.target!==void 0&&(n.inputs={...n.inputs??{},target:{kind:"binding",address:mt(r,n.id,"--target",t.target)}});for(let[i,o,a]of w5){let l=t[o];l!==void 0&&(n[a]=mt(r,n.id,i,l))}for(let[i,o,a]of k5){let l=t[o];l!==void 0&&l.length>0&&(n[a]=xq(ex(r,n.id,i,l)))}}s(y5,"resolveNodeAddresses");var w5=[["--adopt-form","adoptForm","adoptForm"],["--form","formSource","form"],["--contract","contract","contract"],["--payment","payment","payment"]],k5=[["--require","requires","requires"]];function xq(e){let n=new Set;return e.filter(t=>{let r=se(t);return n.has(r)?!1:(n.add(r),!0)})}s(xq,"dedupe");function Sq(e){let n=e.outcome??"approved";if(!xo(n))throw new Error(`offer workflow node: --outcome "${n}" is not an end-node outcome (${oi.join(", ")})`);return n}s(Sq,"resolveEndOutcome");function Aq(e){if(e===void 0)throw new Error(`offer workflow node: an end node needs --data-decision (${Fi.join("|")}) \u2014 whether the application's data is kept or discarded is stated, never derived from --outcome`);if(!Pf(e))throw new Error(`offer workflow node: --data-decision "${e}" invalid (${Fi.join(", ")})`);return e}s(Aq,"resolveDataDecision");function Eq(e){let n=e.mode??"add";if(!pq.includes(n))throw new Error(`offer workflow node: --mode "${n}" invalid (${pq.join(", ")})`);return n}s(Eq,"resolveRoleMode");function Tq(e){if(!e.role||e.role.trim()==="")throw new Error("offer workflow node: --type roleAssign needs --role <key> (the role granted)");return e.role}s(Tq,"resolveRoleKey");function ix(e,n){if(!xf(e))throw new Error(`${n}: --settlement is required for a collectPayment node \u2014 one of ${Os.join(", ")} (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); got ${JSON.stringify(e)}`);return e}s(ix,"requireSettlement");function $q(e,n,t){let r=n?.trim()??"";if(e!=="online"){if(n!==void 0)throw new Error(`${t}: --payee only applies to --settlement online (a separate fee moves no money through Plexus)`);return{}}if(r==="")throw new Error(`${t}: --settlement online needs --payee <Tr\xE4ger key> \u2014 whose Stripe account takes the money (foundation.legalEntities[].key)`);return{[Jt]:{kind:"literal",value:r}}}s($q,"payeeCellFor");function Rq(e,n){if(typeof e!="string"||e.trim()==="")throw new Error(`${n}: --article is required for a collectPayment node \u2014 the key of a one-time article assigned to the offer's program (Finanzen \u2192 Artikel, billing_item_definitions.configKey)`);return e.trim()}s(Rq,"requireArticle");function b5(e,n,t){if(e.requires?.length)throw new Error(`${n}: --require is only valid on a completenessCheck node (got "${t}")`);if(e.deadlineDays!==void 0||e.deadlineUntil!==void 0)throw new Error(`${n}: --deadline-days/--deadline-until are only valid on a completenessCheck node (got "${t}")`);if(e.guestRole!==void 0)throw new Error(`${n}: --guest-role is only valid on a completenessCheck node (got "${t}")`)}s(b5,"assertNoCompletenessFlags");function Iq(e,n,t){if(e.deadlineDays!==void 0&&e.deadlineUntil!==void 0)throw new Error(`${n}: --deadline-days and --deadline-until exclude each other (a check has ONE deadline)`);if(e.deadlineDays!==void 0)return{inDays:e.deadlineDays};if(e.deadlineUntil!==void 0)return{until:e.deadlineUntil};if(t)throw new Error(`${n}: a completenessCheck needs a deadline: --deadline-days <n> or --deadline-until <YYYY-MM-DD>`)}s(Iq,"resolveCompletenessDeadline");function Oq(e,n,t){if(e!==void 0&&e!==""&&(n===void 0||n===""))throw new Error(`${t}: --guest-role needs --person '<address>' \u2014 the party the role is granted to (the beneficiary of a form: --person '$node.form.admission.beneficiary'). It is never defaulted.`);if(n!==void 0&&(e===void 0||e===""))throw new Error(`${t}: --person on a completenessCheck needs --guest-role (a bound person nothing is granted to does nothing)`)}s(Oq,"assertGuestRolePairing");function v5(e,n){return e.onEdge?n.next[e.onEdge.outcome].to:e.after?Object.values(n.next??{}).map(r=>r.to)[0]:n.id}s(v5,"resolveDefaultTarget");function x5(e,n,t,r){let i=Object.entries(r);if(i.length===0)return t;let o=t.mappings.map(c=>c.event),a=new Set(jm(e).bus.states.map(c=>c.id)),l=new Set,d=t.mappings.map(c=>{let u=r[c.event];return u===void 0?c:(l.add(c.state),{...c,state:u})});for(let[c,u]of i){if(!o.includes(c))throw new Error(`offer workflow node add: a ${n} node emits no progress event "${c}" (it emits: ${o.join(", ")||"none"})`);if(!a.has(u))throw new Error(`offer workflow node add: --progress ${c}=${u}: no state "${u}" on the process board (states: ${[...a].join(", ")})`)}return{...t,states:t.states.filter(c=>!l.has(c.id)),mappings:d,columns:t.columns.map(c=>({...c,states:c.states.filter(u=>!l.has(u))})).filter(c=>c.states.length>0),terminalSemantics:Object.fromEntries(Object.entries(t.terminalSemantics).filter(([c])=>!l.has(c)))}}s(x5,"mapProgressOntoExistingStates");function S5(e,n,t,r,i){let{bus:o}=jm(e),a=p5(o);o.states.push(...n),Object.keys(i).length>0&&(o.terminalSemantics={...o.terminalSemantics??{},...i});let l=Cm(i);l.length>0&&(o.holdsSeat=[...new Set([...o.holdsSeat??[],...l])],o.commitsSeat!==void 0&&(o.commitsSeat=[...new Set([...o.commitsSeat,...l])]));let d=e.workflow.progressWiring;if(!d||!Array.isArray(d.mappings))throw new Error("offer workflow node: workflow.progressWiring is missing or malformed");d.mappings.push(...t);let c=or(e),u=a.columns,f=[];for(let y of r){let k=u.find(g=>g.id===y.id);if(k){let g=new Set([...k.states,...y.states]);k.states=[...g],y.optional||delete k.optional}else f.push(y)}if(f.length===0)return;let m=X0([...u,...f],{nodeOrder:A5(c),columnNodeId:s(y=>E5(y,d),"columnNodeId"),terminalStateIds:new Set(Object.keys(o.terminalSemantics??{}))});u.length=0,u.push(...m)}s(S5,"mergeProgress");function A5(e){let n=new Map(e.nodes.map(a=>[a.id,a])),t=e.nodes.find(a=>a.type==="eventTrigger")??e.nodes[0],r=new Map,i=t?[t.id]:[],o=0;for(;i.length>0;){let a=i.shift();if(!r.has(a)){r.set(a,o++);for(let l of Object.values(n.get(a)?.next??{}))r.has(l.to)||i.push(l.to)}}for(let a of e.nodes)r.has(a.id)||r.set(a.id,o++);return r}s(A5,"nodeTopoOrder");function E5(e,n){let t=new Set(e.states??[]),i=n.mappings.find(o=>t.has(o.state))?.match;return i&&"nodeId"in i?i.nodeId:void 0}s(E5,"wiringNodeIdForColumn");function Pq(e,n){let t=or(e),r=t.nodes.find(c=>c.id===n.id);if(!r)throw new Error(`offer workflow node set: node "${n.id}" not found. Nodes: ${t.nodes.map(c=>c.id).join(", ")}`);let i=[];if((n.label!==void 0||n.labelEn!==void 0)&&(wn(r,"label",{de:n.label,en:n.labelEn},`offer workflow node set: node "${n.id}"`),i.push("label")),n.assignDecision!==void 0||n.commentRequired!==void 0||n.requiresOneOf!==void 0){if(r.type!=="decision")throw new Error(`offer workflow node set: --assign-decision/--comment-required/--requires-one-of only valid on a decision node ("${n.id}" is "${r.type}")`);if(n.assignDecision!==void 0){if(n.assignDecision.length===0)throw new Error("offer workflow node set: --assign-decision cannot be empty");r.assign={decision:n.assignDecision},i.push("assign.decision")}n.commentRequired!==void 0&&(r.commentRequired=Object.fromEntries(n.commentRequired.map(c=>[c,!0])),i.push("commentRequired")),n.requiresOneOf!==void 0&&(n.requiresOneOf.length===0?delete r.requiresOneOf:r.requiresOneOf=n.requiresOneOf,i.push("requiresOneOf"))}if(n.artifacts!==void 0&&(r.artifacts=n.artifacts,i.push("artifacts")),n.tasks!==void 0){for(let c of n.tasks)if(c.params?.onReject==="spawnRevision"&&!c.params.revisionGroup)throw new Error(`offer workflow node set: task "${c.key}" has params.onReject 'spawnRevision' but no revisionGroup.`);r.tasks=n.tasks,i.push("tasks")}let a=Gr(e),l=s((c,u)=>mt(a,r.id,c,u),"address");if(n.flagKey!==void 0||n.flagValue!==void 0||n.target!==void 0){if(r.type!=="setFlag")throw new Error(`offer workflow node set: --flag-key/--flag-value/--target only valid on a setFlag node ("${n.id}" is "${r.type}")`);let c=["target","flagKey","value"].filter(u=>u in r);if(c.length>0)throw new Error(`offer workflow node set: setFlag node "${n.id}" still carries ${c.join(", ")} as node properties (an export from before they became inputs) \u2014 export the offer again after the migration moveSetFlagConfigToInputsInGraphs ran; publish refuses this shape ([graph/retiredField]).`);if(n.target!==void 0&&(r.inputs={...r.inputs??{},target:{kind:"binding",address:l("--target",n.target)}},i.push("inputs.target")),n.flagKey!==void 0){if(n.flagKey==="")throw new Error("offer workflow node set: --flag-key needs a flag key");r.inputs={...r.inputs??{},flagKey:{kind:"literal",value:n.flagKey}},i.push("inputs.flagKey")}n.flagValue!==void 0&&(r.inputs={...r.inputs??{},value:{kind:"literal",value:n.flagValue}},i.push("inputs.value"))}if(n.form!==void 0){if(r.type==="form"){if(!e.smartforms?.[n.form])throw new Error(`offer workflow node set: no smartform "${n.form}" in this bundle \u2014 create it with \`offer form add\` first.`);r.inputs={...r.inputs??{},smartForm:{kind:"literal",value:n.form}}}else if(r.type==="governedDocument"&&r.production==="resolver"||r.type==="engagePush"||r.type==="review")r.form=l("--form",n.form);else throw new Error(`offer workflow node set: --form only valid on a form node (slug), a resolver governedDocument, an engagePush or a review node (address) ("${n.id}" is "${r.type}")`);i.push("form")}if(n.contract!==void 0){if(r.type!=="countersign"&&r.type!=="engagePush")throw new Error(`offer workflow node set: --contract only valid on a countersign or engagePush node ("${n.id}" is "${r.type}")`);r.contract=l("--contract",n.contract),i.push("contract")}if(n.payment!==void 0){if(r.type!=="engagePush")throw new Error(`offer workflow node set: --payment only valid on an engagePush node ("${n.id}" is "${r.type}")`);r.payment=l("--payment",n.payment),i.push("payment")}if(n.engageTarget!==void 0&&(r.inputs={...r.inputs??{},target:Fq("offer workflow node set",r.type,n.engageTarget)},i.push("inputs.target")),n.whenNothingOwed!==void 0){if(r.type!=="review")throw new Error(`offer workflow node set: --when-nothing-owed only valid on a review node ("${n.id}" is "${r.type}")`);r.inputs={...r.inputs??{},[Qt]:Dq("offer workflow node set",n.whenNothingOwed)},i.push(`inputs.${Qt}`)}if(n.condition!==void 0){if(r.type!=="if")throw new Error(`offer workflow node set: --condition only valid on an if node ("${n.id}" is "${r.type}")`);r.condition=vq(n.condition,"offer workflow node set"),i.push("condition")}if(n.outcomeSemantics!==void 0){if(r.type!=="decision"&&r.type!=="review")throw new Error(`offer workflow node set: --outcome-semantics only valid on a decision or review node ("${n.id}" is "${r.type}")`);let c=r.outcomes??[];for(let[u,f]of Object.entries(n.outcomeSemantics)){let m=c.find(y=>y.id===u);if(m===void 0)throw new Error(`offer workflow node set: --outcome-semantics names "${u}", which is no outcome of "${n.id}" (${c.map(y=>y.id).join(", ")})`);m.semantic=f}i.push("outcomes.semantic")}if(n.outcome!==void 0||n.dataDecision!==void 0){if(r.type!=="end")throw new Error(`offer workflow node set: --outcome/--data-decision only valid on an end node ("${n.id}" is "${r.type}")`);let c=Sq({outcome:n.outcome??rx(r,"applicationOutcome")});r.inputs={...r.inputs??{},applicationOutcome:{kind:"literal",value:c},dataDecision:{kind:"literal",value:Aq(n.dataDecision??rx(r,"dataDecision"))}},Mq(e,r),i.push("outcome")}if(n.deadlineDays!==void 0||n.deadlineUntil!==void 0||n.guestRole!==void 0||n.person!==void 0&&r.type==="completenessCheck"){if(r.type!=="completenessCheck")throw new Error(`offer workflow node set: --deadline-days/--deadline-until/--guest-role only valid on a completenessCheck node ("${n.id}" is "${r.type}")`);let c=Iq(n,"offer workflow node set",!1);c!==void 0&&(r.deadline=c,i.push("deadline"));let u={...r.inputs??{}},f=u.person,m=f?.kind==="binding"?se(f.address):void 0;if(n.guestRole===""){if(n.person!==void 0)throw new Error('offer workflow node set: --guest-role "" drops the role and its person \u2014 do not pass --person with it');delete u.guestRole,delete u.person,i.push("inputs.guestRole","inputs.person")}else{let y=u.guestRole,k=n.guestRole??(y?.kind==="literal"&&typeof y.value=="string"?y.value:void 0),g=n.person??m;Oq(k,g,"offer workflow node set"),n.guestRole!==void 0&&(u.guestRole={kind:"literal",value:n.guestRole},i.push("inputs.guestRole")),n.person!==void 0&&(u.person={kind:"binding",address:l("--person",n.person)},i.push("inputs.person"))}r.inputs=u}if(n.role!==void 0||n.mode!==void 0||n.person!==void 0&&r.type!=="completenessCheck"){if(r.type!=="roleAssign")throw new Error(`offer workflow node set: --role/--mode only valid on a roleAssign node, --person on a roleAssign or completenessCheck node ("${n.id}" is "${r.type}")`);if(r.inputs={...r.inputs??{}},n.role!==void 0&&(r.inputs.roleKey={kind:"literal",value:Tq({role:n.role})},i.push("role")),n.mode!==void 0&&(r.inputs.mode={kind:"literal",value:Eq({mode:n.mode})},i.push("mode")),n.person!==void 0){if(n.person==="")throw new Error("offer workflow node set: --person cannot be empty on a roleAssign node (e.g. '$node.form.admission.beneficiary')");r.inputs.person={kind:"binding",address:l("--person",n.person)},i.push("person")}}if(n.signing!==void 0&&r.type==="countersign"){if(!Id.includes(n.signing))throw new Error(`offer workflow node set: --signing "${n.signing}" on a countersign node \u2014 expected one of ${Id.join(", ")}`);let c=tq(r,n.signing);for(let u of Object.keys(r))delete r[u];Object.assign(r,c),i.push("signing")}if(n.approval!==void 0||n.approveTitle!==void 0||n.confirmIssue!==void 0||n.confirmTerms!==void 0||n.termsQuestion!==void 0||n.responseDueDays!==void 0||n.signing!==void 0&&r.type!=="countersign"){if(r.type!=="governedDocument")throw new Error(`offer workflow node set: --approval/--approve-title/--confirm-issue/--confirm-terms/--terms-question-*/--response-due-days/--signing only valid on a governedDocument node ("${n.id}" is "${r.type}")`);let c=r;if(n.signing!==void 0){if(!Xv.includes(n.signing))throw new Error(`offer workflow node set: --signing "${n.signing}" \u2014 expected one of ${Xv.join(", ")}`);c=dq(c,n.signing),i.push("responseStrategy")}if(n.approval!==void 0||n.approveTitle!==void 0){let u=n.approval??c.approval;if(!Bo.includes(u))throw new Error(`offer workflow node set: --approval "${u}" \u2014 expected one of ${Bo.join(", ")}`);if(n.approveTitle!==void 0&&u!=="release")throw new Error("offer workflow node set: --approve-title needs --approval release (the title belongs to the Freigabe task)");c=rq(c,u,n.approveTitle!==void 0?{de:n.approveTitle,en:n.approveTitle}:void 0),i.push("approval")}n.confirmIssue!==void 0&&(c=iq(c,n.confirmIssue),i.push("confirmBeforeIssue")),n.confirmTerms!==void 0&&(c=oq(c,n.confirmTerms),i.push("confirmContractTerms")),n.termsQuestion!==void 0&&(c=sq(c,n.termsQuestion),i.push("contractTermsQuestionText")),n.responseDueDays!==void 0&&(c=lq(c,n.responseDueDays),i.push("responseDueInDays"));for(let u of Object.keys(r))delete r[u];Object.assign(r,c)}if(n.settlement!==void 0||n.article!==void 0||n.reason!==void 0||n.payee!==void 0){if(r.type!=="collectPayment")throw new Error(`offer workflow node set: --article/--settlement/--reason/--payee only valid on a collectPayment node ("${n.id}" is "${r.type}")`);if(n.reason!==void 0&&(r.inputs={...r.inputs??{},[Ci]:{kind:"literal",value:n.reason}},i.push(Ci)),n.settlement!==void 0||n.payee!==void 0){let c=r.inputs?.[Ht],u=n.settlement!==void 0?ix(n.settlement,"offer workflow node set"):c?.kind==="literal"?String(c.value):ix(void 0,"offer workflow node set"),f=r.inputs?.[Jt],m=n.payee??(u==="online"&&f?.kind==="literal"?String(f.value):void 0),{[Jt]:y,...k}=r.inputs??{};r.inputs={...k,[Ht]:{kind:"literal",value:u},...$q(u,m,"offer workflow node set")},n.settlement!==void 0&&i.push("settlement"),(n.payee!==void 0||f!==void 0&&u!=="online")&&i.push(Jt)}n.article!==void 0&&(r.inputs={...r.inputs??{},[Ni]:{kind:"literal",value:Rq(n.article,"offer workflow node set")}},i.push("article"))}if(n.traeger!==void 0){if(r.type!=="governedDocument"||r.production!=="resolver")throw new Error(`offer workflow node set: --traeger only valid on a generated contract (governedDocument, production resolver) ("${n.id}" is "${r.type}")`);let c=n.traeger.trim();if(c==="")throw new Error("offer workflow node set: --traeger needs a legal entity key (foundation.legalEntities[].key)");r.inputs={...r.inputs??{},[qt]:{kind:"literal",value:c}},i.push(qt)}if(n.outcomeTargets&&Object.keys(n.outcomeTargets).length>0&&T5(t,r,n.outcomeTargets,i),i.length===0)throw new Error("offer workflow node set: nothing to change \u2014 pass --label/--label-en/--assign-decision/--form/--target/--contract/--payment/--outcomes/--approval/--confirm-issue/--confirm-terms/--terms-question-de+en/--response-due-days/--signing/--deadline-days/--deadline-until/--guest-role/--settlement/--payee/--article/--traeger/--condition/--engage-target/--when-nothing-owed");return{bundle:e,nodeId:n.id,changed:i}}s(Pq,"setGraphNode");function T5(e,n,t,r){let i=new Set(e.nodes.map(l=>l.id)),o=(n.outcomes??[]).map(l=>l.id),a=new Set(o.length?o:[js]);n.next={...n.next??{}};for(let[l,d]of Object.entries(t)){if(!a.has(l))throw new Error(`offer workflow node set: outcome "${l}" is not a declared outcome of "${n.id}" (valid: ${[...a].join(", ")})`);if(!i.has(d))throw new Error(`offer workflow node set: routing target "${d}" is not an existing node id (nodes: ${[...i].join(", ")})`);n.next[l]={...n.next[l]??{},to:d},r.push(`next.${l}`)}}s(T5,"rewriteRouting");function _q(e,n){let t=or(e),r=t.nodes.find(l=>l.id===n);if(!r)throw new Error(`offer workflow node rm: node "${n}" not found. Nodes: ${t.nodes.map(l=>l.id).join(", ")}`);if(r.type==="eventTrigger")throw new Error(`offer workflow node rm: refusing to remove the start node "${n}"`);if(r.type==="end")throw new Error(`offer workflow node rm: refusing to remove the end node "${n}"`);fq(e,n);let i=[...new Set(Object.values(r.next??{}).map(l=>l.to))];if(i.length>1)throw new Error(`offer workflow node rm: node "${n}" has multiple successors (${i.join(", ")}); splice-removal needs a single successor. Edit the bundle manually.`);let o=i[0];for(let l of t.nodes)if(l.next)for(let[d,c]of Object.entries(l.next))c.to===n&&(o?l.next[d]={...c,to:o}:delete l.next[d]);t.nodes=t.nodes.filter(l=>l.id!==n);let a=$5(e,n);return{bundle:e,removedStates:a}}s(_q,"removeGraphNode");function $5(e,n){let t=jm(e).bus,r=e.workflow.progressWiring,i=r&&Array.isArray(r.mappings)?r.mappings:[],o=s(c=>"nodeId"in c.match&&c.match.nodeId===n,"isOwn"),a=new Set(i.filter(c=>!o(c)).map(c=>c.state)),l=[...new Set(i.filter(o).map(c=>c.state))].filter(c=>!a.has(c)),d=new Set(l);if(t.states=t.states.filter(c=>!d.has(c.id)),t.terminalSemantics)for(let c of l)delete t.terminalSemantics[c];for(let c of t.boards??[])c.columns=c.columns.map(u=>({...u,states:u.states.filter(f=>!d.has(f))})).filter(u=>u.states.length>0);return r&&(r.mappings=i.filter(c=>!o(c))),l}s($5,"stripProgress");function Nq(e){if(e.from===void 0!=(e.field===void 0))throw new Error("offer workflow node set-input: --from and --field go together (the field of that node's form)");if([e.address!==void 0,e.from!==void 0,e.literal!==void 0,e.clear===!0].filter(Boolean).length!==1)throw new Error("offer workflow node set-input: name exactly one of --address, --from/--field, --literal or --clear");if(e.clear===!0)return null;if(e.address!==void 0)return{kind:"address",raw:e.address};if(e.from!==void 0)return{kind:"binding",address:nx(e.from,e.field)};let t;try{t=JSON.parse(e.literal)}catch{throw new Error(`offer workflow node set-input: --literal is JSON \u2014 a text needs its quotes ('"de"'), got ${e.literal}`)}if(!(t===null||["string","number","boolean"].includes(typeof t))&&!Ii(t))throw new Error('offer workflow node set-input: --literal must be a scalar or a priced item ({"itemKey":\u2026,"grantKeys":[\u2026]})');return{kind:"literal",value:t}}s(Nq,"parseInputCell");function Cq(e,n,t,r){let i=or(e),o=i.nodes.find(m=>m.id===n);if(!o)throw new Error(`offer workflow node set-input: no node "${n}" (nodes: ${i.nodes.map(m=>m.id).join(", ")})`);if(t.trim()==="")throw new Error("offer workflow node set-input: --input is empty");let a=r?.kind==="address"?{kind:"binding",address:mt(Gr(e),n,"--address",r.raw)}:r;if(o.type==="end"&&a!==null)throw new Error(`offer workflow node set-input: "${n}" is an end node \u2014 its outcome cells are set with \`offer workflow node set --outcome|--data-decision\``);let l=Uo[o.type];if(!l)throw new Error(`offer workflow node set-input: no spec for node type "${o.type}"`);let d=mq(l,o),c=d.find(m=>m.id===t);if(c===void 0&&a!==null){let m=ei(o),y=m===null?null:`${m.kind}:${m.key}`,k=o.generatorStamp,g="`plexus-cli --env <env> --tenant <slug> offer workflow restamp-pins --dir <dir>`",b=mr(o),A=o.templateStamp;throw new Error(`offer workflow node set-input: "${n}" (${o.type}) has no input slot "${t}" (slots: ${d.map($=>$.id).join(", ")||"none"})`+(b!==null&&o.production==="template"?A===void 0?` \u2014 the parameters of template ${b} are on its record, not stamped here yet: run ${g} first`:` \u2014 template ${b} declares no parameter "${t}" (as stamped); declare it on the record (catalog documentTemplates[].parameters), then run ${g}`:y===null?"":k?.inputSchema===void 0?` \u2014 its generator ${y} is not stamped, so its parameters are unknown offline: run ${g} first`:` \u2014 the stamp of ${y} lists its parameters as they were when stamped; if the generator or package changed since, run ${g}`))}if(t===Kn)throw new Error(`offer workflow node set-input: "${Kn}" names the node's generator \u2014 set it with \`offer workflow node set-generator --node ${n} --generator|--package <key>\``);if(c!==void 0&&a?.kind==="literal"){let m=kl(a.value,c);if(m!==null)throw new Error(`offer workflow node set-input: ${n}.${t}: ${m}`)}let u={...o.inputs??{}},f=u[t];if(a===null){if(f===void 0)throw new Error(`offer workflow node set-input: node "${n}" has no input "${t}" to clear (inputs: ${Object.keys(u).join(", ")||"none"})`);delete u[t]}else u[t]=a;return Object.keys(u).length===0?delete o.inputs:o.inputs=u,{bundle:e,before:f,after:a??void 0}}s(Cq,"setNodeInput");function Dq(e,n){if(!mw(n))throw new Error(`${e}: --when-nothing-owed "${n}" \u2014 expected one of ${Eo.join(", ")}`);return{kind:"literal",value:n}}s(Dq,"reviewModeInput");function Fq(e,n,t){if(n!=="engagePush")throw new Error(`${e}: --engage-target is only valid on an engagePush node (got "${n}")`);if(t!=="sandbox"&&t!=="production"){let r=t===void 0?"nothing":`"${t}"`;throw new Error(`${e}: --engage-target sandbox|production is required on an engagePush node (got ${r})`)}return{kind:"literal",value:t}}s(Fq,"engageTargetInput");function Lq(e,n,t){let r=or(e),i=r.nodes.find(a=>a.id===n);if(!i)throw new Error(`offer workflow node set-engage: no node "${n}" (nodes: ${r.nodes.map(a=>a.id).join(", ")})`);if(i.type!=="engagePush")throw new Error(`offer workflow node set-engage: "${n}" is a ${i.type} node, not engagePush`);let o=i.engage;return i.engage=t,{bundle:e,before:o}}s(Lq,"setNodeEngageConfig");function Mq(e,n){let t=rx(n,"applicationOutcome");if(typeof t!="string"||!xo(t))return;let r=Ls[t],o=e.workflow.progressWiring?.mappings.find(d=>d.event===r&&"nodeId"in d.match&&d.match.nodeId===n.id);if(o===void 0)return;let{bus:a}=jm(e),l=a.terminalSemantics?.[o.state];if(!(l===void 0||l.outcome===t)){if(o.state!==`${n.id}.${r}`)throw new Error(`offer workflow node: end "${n.id}" (${t}) reaches the shared state "${o.state}", which seals "${String(l.outcome)}" \u2014 map its "${r}" event onto a state that seals "${t}"`);a.terminalSemantics={...a.terminalSemantics??{},[o.state]:{...l,outcome:t}}}}s(Mq,"alignEndTerminal");var R5="offer workflow node optional-action";function vn(e,n){throw new kn(`${R5} ${e}: ${n}`)}s(vn,"refuse");function Kq(e,n,t){let r=e.workflow?.graph;e.workflow||vn(t,"das B\xFCndel enth\xE4lt keine workflow.json."),(!r||!Array.isArray(r.nodes))&&vn(t,"workflow.graph hat keine Knotenliste.");let i=r.nodes,o=i.find(a=>a.id===n);return o||vn(t,`Knoten \u201E${n}" gibt es nicht. Knoten: ${i.map(a=>a.id).join(", ")}.`),o.optionalActions!==void 0&&!Array.isArray(o.optionalActions)&&vn(t,`Knoten \u201E${n}" tr\xE4gt eine fehlerhafte \`optionalActions\`-Liste \u2014 workflow.json zuerst reparieren.`),o}s(Kq,"findNode");function Bm(e,n,t){let r=n.trim();r||vn(e,"darf nicht leer sein.");let i=t?.trim();return t!==void 0&&!i&&vn(`${e}-en`,"darf nicht leer sein."),{de:r,en:i||r}}s(Bm,"bilingual");function I5(e){let n=e.split(",").map(t=>t.trim()).filter(Boolean);return n.length===0&&vn("--tasks","leere Liste \u2014 mindestens einen Aufgabenschl\xFCssel des Knotens nennen."),n}s(I5,"parseTasks");function qq(e){return{key:e.key,action:e.action,label:e.label,...e.description!==void 0?{description:e.description}:{},...e.trigger!==void 0?{trigger:e.trigger}:{},tasks:e.tasks,...e.repeatable===!0?{repeatable:!0}:{}}}s(qq,"ordered");function jq(e,n,t,r){let i=Kq(e,n,"set");t.trim()||vn("set","--key darf nicht leer sein.");let o=i.optionalActions??[],a=o.findIndex(u=>u.key===t),l=a<0?null:structuredClone(o[a]);l!==null&&l.action!=="spawnTasks"&&vn("set",`\u201E${t}" auf ${n} ist keine spawnTasks-Aktion (${String(l.action)}).`),l===null&&(r.label===void 0&&vn("set","--label ist Pflicht f\xFCr eine neue Aktion (der Eintrag im Men\xFC \u201EWeiteres\u201C)."),r.tasks===void 0&&vn("set","--tasks ist Pflicht f\xFCr eine neue Aktion (Aufgabenschl\xFCssel des Knotens, a,b)."),(r.clearDescription||r.clearTrigger)&&vn("set","--clear-* gibt es nur beim \xC4ndern \u2014 eine neue Aktion hat nichts zu entfernen.")),r.description!==void 0&&r.clearDescription&&vn("set","--description und --clear-description schlie\xDFen einander aus."),r.trigger!==void 0&&r.clearTrigger&&vn("set","--trigger und --clear-trigger schlie\xDFen einander aus.");let d=l===null?{key:t,action:"spawnTasks"}:structuredClone(l);if(r.label!==void 0?d.label=Bm("--label",r.label,r.labelEn):r.labelEn!==void 0&&(d.label={...d.label,en:Bm("--label",d.label.de,r.labelEn).en}),r.clearDescription&&(d.description===void 0&&vn("set",`\u201E${t}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete d.description),r.description!==void 0?d.description=Bm("--description",r.description,r.descriptionEn):r.descriptionEn!==void 0&&(d.description===void 0&&vn("set","--description-en braucht --description."),d.description={...d.description,en:Bm("--description",d.description.de,r.descriptionEn).en}),r.tasks!==void 0&&(d.tasks=I5(r.tasks)),r.clearTrigger&&(d.trigger===void 0&&vn("set",`\u201E${t}" hat kein --trigger \u2014 --clear-trigger hat nichts zu entfernen.`),delete d.trigger),r.trigger!==void 0){let u=r.trigger.trim();u||vn("--trigger","darf nicht leer sein (Schl\xFCssel einer Berechtigungsgruppe)."),d.trigger=u}r.repeatable===!0?d.repeatable=!0:r.repeatable===!1&&delete d.repeatable;let c=qq(d);return l!==null&&JSON.stringify(qq(l))===JSON.stringify(c)&&vn("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aktion \u201E${t}".`),i.optionalActions=a<0?[...o,c]:o.map((u,f)=>f===a?c:u),{bundle:e,nodeId:n,key:t,before:l,after:c}}s(jq,"setOptionalAction");function Bq(e,n,t){let r=Kq(e,n,"remove"),i=r.optionalActions??[],o=i.find(l=>l.key===t);o||vn("remove",`Knoten \u201E${n}" hat keine optionale Aktion \u201E${t}" (Aktionen: ${i.map(l=>l.key).join(", ")||"keine"}).`),r.requiresOneOf?.includes(t)===!0&&vn("remove",`\u201E${t}" steht in 'requiresOneOf' von ${n} \u2014 zuerst die Regel \xE4ndern (node set --requires-one-of \u2026).`);let a=i.filter(l=>l.key!==t);return a.length===0?delete r.optionalActions:r.optionalActions=a,{bundle:e,nodeId:n,key:t,before:o,after:null}}s(Bq,"removeOptionalAction");function Um(e){if(!e.workflow)throw new Error("offer workflow channels: bundle carries no workflow.json");let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error("offer workflow channels: workflow.graph has no nodes array");return n}s(Um,"graphOf");function Uq(e,n){let t=Um(e),{channels:r,...i}=t,o=n.length>0?{...i,channels:n}:i;return{...e,workflow:{...e.workflow,graph:o}}}s(Uq,"withChannels");function Vq(e){let n=Um(e),t=PP(n).map(i=>({key:Hf(i),label:i,members:[Hf(i)],source:"derived"})),r=Hs(n).map(i=>({key:i.key,label:_e(i.label),members:[...i.members],source:"authored"}));return[...t,...r]}s(Vq,"listChannels");function Gq(e,n){let t=Hs(Um(e)),r="offer workflow channels add",i={de:"--label",en:"--label-en"},o=n.key===void 0?void 0:t.find(f=>f.key===n.key),a=o===void 0?Hn({de:n.label,en:n.labelEn},r,i):Xt(o.label,{de:n.label,en:n.labelEn},r,i)??o.label,l=n.key??_P(a.de,new Set(t.map(f=>f.key))),d={key:l,label:a,members:n.teams.map(f=>f.startsWith("team:")?f:Hf(f))},c=t.findIndex(f=>f.key===l),u=[...t];return c>=0?u[c]=d:u.push(d),{bundle:Uq(e,u),channel:d,replaced:c>=0}}s(Gq,"upsertChannel");function zq(e,n){let t=Hs(Um(e)),r=t.find(i=>i.key===n);if(r===void 0){let i=t.map(o=>o.key).join(", ")||"\u2014";throw new Error(`offer workflow channels: no authored channel "${n}" (authored: ${i}). Derived team channels cannot be removed \u2014 they follow the teams the process assigns.`)}return{bundle:Uq(e,t.filter(i=>i.key!==n)),removed:r}}s(zq,"removeChannel");var Jo="offer workflow staff-input";function Wq(e){if(!e.workflow)throw new Error(`${Jo}: bundle carries no workflow.json`);let n=e.workflow.graph;if(!n||!Array.isArray(n.nodes))throw new Error(`${Jo}: workflow.graph has no nodes array`);return n}s(Wq,"graphOf");function sx(e){let n=Wq(e).staffInputs;if(n===void 0)return[];if(!Array.isArray(n))throw new Error(`${Jo}: workflow.graph.staffInputs is not a list (${JSON.stringify(n)}) \u2014 fix workflow.json`);return n}s(sx,"declared");function Yq(e,n){let{staffInputs:t,...r}=Wq(e),i=n.length>0?{...r,staffInputs:n}:r;return{...e,workflow:{...e.workflow,graph:i}}}s(Yq,"withStaffInputs");function Hq(e){return sx(e).map(n=>({key:n.key,type:n.type,label:n.label,reads:_R(n.key)}))}s(Hq,"listStaffInputs");function Jq(e,n){if(!sl.test(n.key))throw new Error(`${Jo} set: key "${n.key}" \u2014 a key starts with a lower-case letter and holds only letters and digits (it is read as one identifier: $env.staffInput.<key>)`);let t=sx(e),r=t.findIndex(c=>c.key===n.key),i={de:"--label",en:"--label-en"},o=r>=0?t[r]:void 0,a=o===void 0?Hn({de:n.label,en:n.labelEn},`${Jo} set`,i):Xt(o.label,{de:n.label,en:n.labelEn},`${Jo} set`,i)??o.label,l={key:n.key,type:"boolean",label:a},d=[...t];return r>=0?d[r]=l:d.push(l),{bundle:Yq(e,d),input:l,replaced:r>=0}}s(Jq,"setStaffInput");function Qq(e,n){let t=sx(e),r=t.find(i=>i.key===n);if(r===void 0)throw new Error(`${Jo} remove: no staff input "${n}" (declared: ${t.map(i=>i.key).join(", ")||"none"})`);return{bundle:Yq(e,t.filter(i=>i.key!==n)),removed:r}}s(Qq,"removeStaffInput");var Zq=["task","approval"],Xq=["respawn","stayClosed"],O5="offer workflow node task";function ce(e,n){throw new kn(`${O5} ${e}: ${n}`)}s(ce,"refuse");function lx(e,n){let t=e.workflow?.graph;return e.workflow||ce(n,"das B\xFCndel enth\xE4lt keine workflow.json."),(!t||!Array.isArray(t.nodes))&&ce(n,"workflow.graph hat keine Knotenliste."),t.nodes}s(lx,"graphNodes");function dx(e,n,t){let r=lx(e,t),i=r.find(o=>o.id===n);return i||ce(t,`Knoten \u201E${n}" gibt es nicht. Knoten: ${r.map(o=>o.id).join(", ")}.`),i.tasks!==void 0&&!Array.isArray(i.tasks)&&ce(t,`Knoten \u201E${n}" tr\xE4gt eine fehlerhafte \`tasks\`-Liste \u2014 workflow.json zuerst reparieren.`),i}s(dx,"findNode");function P5(e,n){let t=e.trim(),r=t.lastIndexOf(":"),i=r<0?n:t.slice(0,r).trim(),o=r<0?t:t.slice(r+1).trim();return(!i||!o)&&ce("--blocks",`\u201E${e}" ist kein Ziel \u2014 erwartet <knotenId>:<templateKey> oder nur <templateKey> f\xFCr denselben Knoten.`),i===n?{templateKey:o}:{node:i,templateKey:o}}s(P5,"parseBlocksTarget");function ax(e,n){let t=e.split(",").map(r=>r.trim()).filter(Boolean);return t.length===0&&ce(n,"leere Liste \u2014 mindestens einen Eintrag nennen oder die Option weglassen."),t}s(ax,"parseList");function _5(e,n){let t=e.indexOf("="),r=t<0?"":e.slice(0,t).trim(),i=t<0?"":e.slice(t+1),o=i.indexOf("|"),a=(o<0?i:i.slice(0,o)).trim(),l=o<0?a:i.slice(o+1).trim();return(!r||!a||!l)&&ce(n,`\u201E${e}" ist fehlerhaft \u2014 erwartet <schl\xFCssel>=<Bezeichnung> oder <schl\xFCssel>=<Bezeichnung>|<English>.`),{key:r,label:{de:a,en:l}}}s(_5,"parseKeyedLabel");function N5(e){return _5(e,"--option")}s(N5,"parseResultOption");function C5(e,n,t){let r;try{r=JSON.parse(e)}catch{ce("--field",`\u201E${e}" ist kein JSON-Objekt \u2014 erwartet z. B. {"key":"rang","type":"number","label":{"de":"Rang","en":"Rank"},"writes":"rang"}.`)}(typeof r!="object"||r===null||Array.isArray(r))&&ce("--field",`\u201E${e}" ist kein JSON-Objekt.`);let i=r,o=i.suggest;if(o?.kind==="form"){let a=o.address;typeof a=="string"?i.suggest={kind:"form",address:mt(n,t,"--field suggest.address",a)}:(typeof a!="object"||a===null)&&Ea(n,t,"--field suggest",JSON.stringify(o),'ein Formular-Vorschlag nennt seine Adresse \u2014 {"kind":"form","address":"$node.<Formular>.admission.<Export>"}.')}return i}s(C5,"parseRecordField");function D5(e){let n=Number(e);return(!/^\s*\d+\s*$/.test(e)||!Number.isInteger(n)||n<=0)&&ce("--due-in-days",`\u201E${e}" ist keine positive ganze Zahl von Tagen.`),n}s(D5,"parseDueInDays");function F5(e){return!Oi(e)&&e!=="appointment"&&ce("--result",`unbekannter Ergebnistyp \u201E${e}" \u2014 erlaubt: ${[...bs,"appointment"].map(n=>`${n} (${ni[n].label.de})`).join(", ")}.`),e}s(F5,"parseResultType");function L5(e,n,t,r,i){let o=`'$task.${r}.<schl\xFCssel>'`;i.trim().startsWith("$")||ce(e,`--writes \u201E${i}": ein nackter Schl\xFCssel \u2014 --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${o}.`);let a=mt(n,t,"--writes",i);return(a.scope!=="task"||a.owner!==r)&&ce(e,`--writes \u201E${i}": --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${o}.`),a.path!==void 0&&ce(e,`--writes \u201E${i}": eine Aufgabe schreibt ihren Wert als Ganzes \u2014 ${o} ohne Pfad.`),a.key}s(L5,"parseWritesArg");function M5(e,n,t,r){let i="'$derived.<schl\xFCssel>' ohne Pfad";r.trim().startsWith("$")||ce(e,`--prices \u201E${r}": ein nackter Schl\xFCssel \u2014 --prices nennt einen abgeleiteten Preis \u2014 ${i}.`);let o=mt(n,t,"--prices",r);return(o.scope!=="derived"||o.path!==void 0)&&ce(e,`--prices \u201E${r}": --prices nennt einen abgeleiteten Preis \u2014 ${i}.`),o.key}s(M5,"parsePricesArg");function q5(e,n,t){let r=n.resultLabel?.trim()??t?.de;(r===void 0||r.length===0)&&ce(e,"--result-label nennt den Namen des Werts (deutsch, nicht leer), z. B. \u201ESchulgeld mit Erm\xE4\xDFigung\u201C."),n.resultLabelEn!==void 0&&n.resultLabelEn.trim().length===0&&ce(e,"--result-label-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Name auch im Englischen.");let i=n.resultLabelEn?.trim()??(n.resultLabel!==void 0?r:t?.en??r);return{de:r,en:i}}s(q5,"resultLabelOf");function K5(e){let n=Number(e);return(!/^\s*\d+\s*$/.test(e)||!Number.isInteger(n)||n<So||n>Ao)&&ce("--duration",`\u201E${e}" ist keine Dauer \u2014 erwartet ganze Minuten von ${So} bis ${Ao}.`),n}s(K5,"parseDuration");function j5(e){let n=e.trim();return n==="external"&&ce("--chat",'\u201Eexternal" ist kein Ziel \u2014 ein Aufgabenergebnis erreicht die Familie nie. Erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.'),Ss(n)===null&&ce("--chat",`\u201E${e}" ist kein Ziel \u2014 erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.`),n}s(j5,"checkChat");function Tn(e,n,t,r,i,o){let a=s(l=>{let d=n[l];return Array.isArray(d)?d.length>0:d!==void 0&&d!==!1},"has");a(t)&&a(r)&&ce(e,`${i} und ${o} schlie\xDFen einander aus.`)}s(Tn,"exclusive");function eK(e,n,t,r,i,o){Tn(e,o,"blocks","clearBlocks","--blocks","--clear-blocks"),Tn(e,o,"result","clearResult","--result","--clear-result"),Tn(e,o,"options","clearResult","--option","--clear-result"),Tn(e,o,"chat","clearResult","--chat","--clear-result"),Tn(e,o,"textRequired","clearResult","--text-required","--clear-result"),Tn(e,o,"duration","clearResult","--duration","--clear-result"),Tn(e,o,"resultTitle","clearResult","--result-title","--clear-result"),Tn(e,o,"resultTitleEn","clearResult","--result-title-en","--clear-result"),Tn(e,o,"writes","clearResult","--writes","--clear-result"),Tn(e,o,"prices","clearResult","--prices","--clear-result"),Tn(e,o,"item","clearResult","--item","--clear-result"),Tn(e,o,"resultLabel","clearResult","--result-label","--clear-result"),Tn(e,o,"resultLabelEn","clearResult","--result-label-en","--clear-result"),Tn(e,o,"when","clearWhen","--when","--clear-when"),Tn(e,o,"onConditionReturn","clearWhen","--on-condition-return","--clear-when"),Tn(e,o,"reads","clearReads","--reads","--clear-reads"),Tn(e,o,"documents","clearDocuments","--documents","--clear-documents"),Tn(e,o,"description","clearDescription","--description","--clear-description"),Tn(e,o,"descriptionEn","clearDescription","--description-en","--clear-description");let a=[],l=structuredClone(i??{key:r});if(o.kind!==void 0?(Zq.includes(o.kind)||ce(e,`--kind \u201E${o.kind}" ist unbekannt \u2014 erlaubt: ${Zq.join(", ")}.`),l.kind=o.kind):i===null&&(l.kind="task"),o.title!==void 0){let f=o.title.trim();f||ce(e,"--title darf nicht leer sein."),l.title={de:f,en:o.titleEn?.trim()||f}}else if(o.titleEn!==void 0){i===null&&ce(e,"--title-en braucht --title.");let f=o.titleEn.trim();f||ce(e,"--title-en darf nicht leer sein."),l.title={...l.title,en:f}}if(o.team!==void 0){let f=o.team.trim();f||ce(e,"--team darf nicht leer sein (Schl\xFCssel einer Berechtigungsgruppe)."),l.assign={...l.assign??{},group:f}}o.dueInDays!==void 0&&(l.params={...l.params??{},dueInDays:D5(o.dueInDays)}),o.clearBlocks&&(l.blocks===void 0&&ce(e,`Aufgabe \u201E${r}" blockiert nichts \u2014 --clear-blocks hat nichts zu entfernen.`),delete l.blocks),o.blocks!==void 0&&(l.blocks?.except!==void 0&&a.push("blocks.except"),l.blocks=P5(o.blocks,t)),o.clearResult&&(l.result===void 0&&ce(e,`Aufgabe \u201E${r}" hat kein Ergebnis \u2014 --clear-result hat nichts zu entfernen.`),delete l.result);let d=(o.options?.length??0)>0||(o.fields?.length??0)>0||o.writes!==void 0||o.prices!==void 0||o.item!==void 0||o.resultLabel!==void 0||o.resultLabelEn!==void 0||o.textRequired!==void 0||o.chat!==void 0,c=o.duration!==void 0||o.resultTitle!==void 0||o.resultTitleEn!==void 0;if(o.result!==void 0||d||c){let f=o.result!==void 0?F5(o.result):l.result?.kind;if(f===void 0&&ce(e,`--option, --text-required, --chat, --writes, --prices, --item, --result-label, --duration und --result-title brauchen ein Ergebnis \u2014 --result ${[...bs,"appointment"].join("|")} angeben.`),f==="appointment"){d&&ce(e,"--option, --text-required, --chat, --writes, --prices, --item und --result-label gelten nicht f\xFCr einen Termin \u2014 ein Termin-Ergebnis nimmt keinen Text und tr\xE4gt keinen Wert.");let m=l.result?.kind==="appointment"?l.result:void 0;l.result!==void 0&&m===void 0&&a.push("result (vorheriger Ergebnistyp)");let y=o.resultTitle?.trim()??m?.title.de;(y===void 0||y.length===0)&&ce(e,"--result appointment braucht --result-title (neutraler Titel des Termins \u2014 steht im Familienbrief und in der Kalenderdatei).");let k=o.duration!==void 0?K5(o.duration):m?.durationMinutes;k===void 0&&ce(e,"--result appointment braucht --duration <Minuten> (vorbelegte Dauer im Termin-Dialog)."),o.resultTitleEn!==void 0&&o.resultTitleEn.trim().length===0&&ce(e,"--result-title-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Titel auch im Englischen.");let g=o.resultTitleEn?.trim()??(o.resultTitle!==void 0?y:m?.title.en??y);l.result={kind:"appointment",title:{de:y,en:g},durationMinutes:k}}else{c&&ce(e,`--duration und --result-title gelten nur f\xFCr --result appointment \u2014 hier: ${f} (${ni[f].label.de}).`);let m=l.result!==void 0&&xs(l.result)?l.result:void 0;l.result?.kind==="appointment"&&a.push("result (Termin)");let y={kind:f};m?.chat!==void 0&&(y.chat=m.chat),m?.textRequired!==void 0&&(f==="freetext"?a.push("result.textRequired"):y.textRequired=m.textRequired),m?.options!==void 0&&(f==="choice"?y.options=m.options:a.push("result.options")),m?.fields!==void 0&&(f==="record"?y.fields=m.fields:a.push("result.fields"));let k=ni[f].valueType!==null;m?.writes!==void 0&&(k?y.writes=m.writes:a.push("result.writes")),m?.label!==void 0&&(k?y.label=m.label:a.push("result.label")),m?.prices!==void 0&&(f==="reduction"?y.prices=m.prices:a.push("result.prices")),m?.item!==void 0&&(f==="pricedItem"?y.item=m.item:a.push("result.item"));let g=bs.filter(A=>ni[A].valueType!==null).join(", "),b=`hier: ${f} (${ni[f].label.de})`;if(o.writes!==void 0&&(k||ce(e,`--writes gibt es nur bei Ergebnissen mit Wert (${g}) \u2014 ${b}.`),y.writes=L5(e,n,t,r,o.writes)),o.prices!==void 0&&(f!=="reduction"&&ce(e,`--prices gibt es nur beim Ergebnistyp reduction \u2014 ${b}.`),y.prices=M5(e,n,t,o.prices)),o.item!==void 0){f!=="pricedItem"&&ce(e,`--item gibt es nur beim Ergebnistyp pricedItem \u2014 ${b}.`);let A=o.item.trim();A.length===0&&ce(e,"--item darf nicht leer sein (der Schl\xFCssel des Artikels, z. B. tuition)."),y.item=A}(o.resultLabel!==void 0||o.resultLabelEn!==void 0)&&(k||ce(e,`--result-label gibt es nur bei Ergebnissen mit Wert (${g}) \u2014 ${b}.`),y.label=q5(e,o,y.label)),(o.fields?.length??0)>0&&(f!=="record"&&ce(e,`--field gibt es nur beim Ergebnistyp record (Erfassung) \u2014 hier: ${f} (${ni[f].label.de}).`),y.fields=o.fields.map(A=>C5(A,n,t))),(o.options?.length??0)>0&&(f!=="choice"&&ce(e,`--option gibt es nur beim Ergebnistyp choice (Auswahl) \u2014 hier: ${f} (${ni[f].label.de}).`),y.options=o.options.map(N5)),o.textRequired!==void 0&&(f==="freetext"&&ce(e,"--text-required/--no-text-required gibt es beim Freitext nicht \u2014 sein Text ist immer Pflicht."),o.textRequired?y.textRequired=!0:delete y.textRequired),o.chat!==void 0&&(y.chat=j5(o.chat)),l.result=y}}if(o.clearWhen&&(l.when===void 0&&l.onConditionReturn===void 0&&ce(e,`Aufgabe \u201E${r}" hat keine Bedingung \u2014 --clear-when hat nichts zu entfernen.`),delete l.when,delete l.onConditionReturn),o.when!==void 0&&(l.when=mt(n,t,"--when",o.when)),o.onConditionReturn!==void 0&&(Xq.includes(o.onConditionReturn)||ce(e,`--on-condition-return \u201E${o.onConditionReturn}" ist unbekannt \u2014 erlaubt: ${Xq.join(", ")}.`),l.when===void 0&&ce(e,"--on-condition-return braucht eine Bedingung (--when)."),l.onConditionReturn=o.onConditionReturn),o.clearReads&&(l.reads===void 0&&ce(e,`Aufgabe \u201E${r}" liest keine Felder \u2014 --clear-reads hat nichts zu entfernen.`),delete l.reads),o.reads!==void 0&&(l.reads=ax(o.reads,"--reads").map(f=>mt(n,t,"--reads",f))),o.clearDocuments&&(l.documents===void 0&&ce(e,`Aufgabe \u201E${r}" verweist auf keine Dokumente \u2014 --clear-documents hat nichts zu entfernen.`),delete l.documents),o.documents!==void 0&&(l.documents=ax(o.documents,"--documents").map(f=>{try{return a_(f)}catch(m){Ea(n,t,"--documents",f,m instanceof Error?m.message:String(m))}})),o.locksEvidence&&o.clearLocksEvidence&&ce(e,"--locks-evidence und --clear-locks-evidence schlie\xDFen sich aus."),o.clearLocksEvidence&&(l.locksEvidence===void 0&&ce(e,`Aufgabe \u201E${r}" sperrt keine Belege \u2014 --clear-locks-evidence hat nichts zu entfernen.`),delete l.locksEvidence),o.locksEvidence&&(l.locksEvidence=!0),o.clearDescription&&(l.description===void 0&&ce(e,`Aufgabe \u201E${r}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete l.description),o.description!==void 0){let f=o.description.trim();f||ce(e,"--description darf nicht leer sein (entfernen mit --clear-description)."),l.description={de:f,en:o.descriptionEn?.trim()||f}}else if(o.descriptionEn!==void 0){l.description===void 0&&ce(e,"--description-en braucht --description.");let f=o.descriptionEn.trim();f||ce(e,"--description-en darf nicht leer sein."),l.description={...l.description,en:f}}if(o.clearOptional&&((o.optional!==void 0||o.optionalEn!==void 0)&&ce(e,"--clear-optional schlie\xDFt --optional und --optional-en aus."),l.optional===void 0&&ce(e,`Aufgabe \u201E${r}" ist nicht optional \u2014 --clear-optional hat nichts zu entfernen.`),delete l.optional),o.optional!==void 0){let f=o.optional.trim();f||ce(e,"--optional braucht die Worte des Knopfs (z. B. \u201EKeine Einsch\xE4tzung abgeben\u201C)."),l.optional={skipLabel:{de:f,en:o.optionalEn?.trim()||f}}}else if(o.optionalEn!==void 0){l.optional===void 0&&ce(e,"--optional-en braucht --optional.");let f=o.optionalEn.trim();f||ce(e,"--optional-en darf nicht leer sein."),l.optional={skipLabel:{...l.optional.skipLabel,en:f}}}if(o.clearAppointment&&((o.appointmentOf!==void 0||o.dueDaysAfterEnd!==void 0)&&ce(e,"--clear-appointment schlie\xDFt --appointment-of und --due-days-after-end aus."),l.appointment===void 0&&ce(e,`Aufgabe \u201E${r}" ist keine Terminaufgabe \u2014 --clear-appointment hat nichts zu entfernen.`),delete l.appointment),o.appointmentOf!==void 0||o.dueDaysAfterEnd!==void 0){let f=o.appointmentOf?.trim()??l.appointment?.of;f||ce(e,"--due-days-after-end braucht --appointment-of (die Aufgabe, die den Termin bucht).");let m=o.dueDaysAfterEnd?.trim();m!==void 0&&!/^\d+$/.test(m)&&ce(e,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(o.dueDaysAfterEnd)}.`);let y=m!==void 0?Number(m):l.appointment?.dueDaysAfterEnd;y===void 0&&ce(e,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(o.dueDaysAfterEnd)}.`),l.appointment={of:f,dueDaysAfterEnd:y}}let u=o.familyRequestFields!==void 0||o.familyRequestFrom!==void 0;if(Tn(e,o,"familyRequestFields","familyRequestFrom","--family-request-fields","--family-request-from"),o.clearFamilyRequest&&(u&&ce(e,"--clear-family-request schlie\xDFt die \xFCbrigen --family-request-*-Flags aus."),l.familyRequest===void 0&&ce(e,`Aufgabe \u201E${r}" fordert nichts bei der Familie an \u2014 --clear-family-request hat nichts zu entfernen.`),delete l.familyRequest),o.familyRequestFields!==void 0){let f=ax(o.familyRequestFields,"--family-request-fields").map(m=>mt(n,t,"--family-request-fields",m));l.familyRequest={fields:f}}return o.familyRequestFrom!==void 0&&(l.familyRequest={from:mt(n,t,"--family-request-from",o.familyRequestFrom)}),{next:U5(l),dropped:a}}s(eK,"applyFlags");var B5=["key","kind","title","description","assign","params","blocks","result","when","onConditionReturn","reads","locksEvidence","documents","familyRequest","optional","appointment"];function U5(e){let n=e,t={};for(let r of B5)n[r]!==void 0&&(t[r]=n[r]);for(let[r,i]of Object.entries(n))!(r in t)&&i!==void 0&&(t[r]=i);return t}s(U5,"normalizeOrder");var V5=[["kind",e=>e.kind],["title",e=>e.title],["description",e=>e.description],["assign.group",e=>e.assign?.group],["params.dueInDays",e=>e.params?.dueInDays],["blocks",e=>e.blocks?{...e.blocks}:void 0],["result",e=>e.result],["when",e=>e.when],["onConditionReturn",e=>e.onConditionReturn],["reads",e=>e.reads],["locksEvidence",e=>e.locksEvidence],["documents",e=>e.documents],["familyRequest",e=>e.familyRequest],["optional",e=>e.optional],["appointment",e=>e.appointment]];function cx(e,n){let t=[];for(let[r,i]of V5){let o=e?i(e):void 0,a=n?i(n):void 0;JSON.stringify(o)!==JSON.stringify(a)&&t.push({field:r,before:o,after:a})}return t}s(cx,"diffTemplates");function nK(e,n,t,r){let i=dx(e,n,"add");t.trim()||ce("add","--key darf nicht leer sein."),(i.tasks??[]).find(d=>d.key===t)&&ce("add",`Knoten \u201E${n}" hat schon eine Aufgabe \u201E${t}" \u2014 \xE4ndern mit \`task set\`, entfernen mit \`task rm\`.`),r.title===void 0&&ce("add","--title ist Pflicht (deutscher Titel der Aufgabe)."),r.team===void 0&&ce("add","--team ist Pflicht (Schl\xFCssel der Berechtigungsgruppe, die die Aufgabe bekommt).");for(let[d,c]of[["--clear-blocks",r.clearBlocks],["--clear-result",r.clearResult],["--clear-when",r.clearWhen],["--clear-reads",r.clearReads],["--clear-documents",r.clearDocuments],["--clear-locks-evidence",r.clearLocksEvidence],["--clear-description",r.clearDescription],["--clear-optional",r.clearOptional],["--clear-appointment",r.clearAppointment]])c&&ce("add",`${d} gibt es nur bei \`task set\` \u2014 eine neue Aufgabe hat nichts zu entfernen.`);let{next:a,dropped:l}=eK("add",Gr(e),n,t,null,r);return i.tasks=[...i.tasks??[],a],{bundle:e,nodeId:n,key:t,before:null,after:a,changes:cx(null,a),dropped:l}}s(nK,"addNodeTask");function tK(e,n,t,r){let i=dx(e,n,"set"),o=i.tasks??[],a=o.findIndex(f=>f.key===t);a<0&&ce("set",`Knoten \u201E${n}" hat keine Aufgabe \u201E${t}" (Aufgaben: ${o.map(f=>f.key).join(", ")||"keine"}).`);let l=o[a],{next:d,dropped:c}=eK("set",Gr(e),n,t,l,r),u=cx(l,d);return u.length===0&&ce("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aufgabe \u201E${t}".`),i.tasks=o.map((f,m)=>m===a?d:f),{bundle:e,nodeId:n,key:t,before:structuredClone(l),after:d,changes:u,dropped:c}}s(tK,"setNodeTask");function G5(e,n,t){let r=[];for(let o of lx(e,"rm"))for(let a of Array.isArray(o.tasks)?o.tasks:[]){if(o.id===n&&a.key===t)continue;let l=a.blocks;l&&l.templateKey===t&&(l.node??o.id)===n&&r.push(`Aufgabe \u201E${a.key}" auf ${o.id} (blocks)`)}let i=lx(e,"rm").find(o=>o.id===n);for(let o of i?.optionalActions??[])Array.isArray(o.tasks)&&o.tasks.includes(t)&&r.push(`optionale Aktion \u201E${o.key??"?"}" auf ${n}`);return r}s(G5,"nodeTaskDependents");function rK(e,n,t){let r=dx(e,n,"rm"),i=r.tasks??[],o=i.find(d=>d.key===t);o||ce("rm",`Knoten \u201E${n}" hat keine Aufgabe \u201E${t}" (Aufgaben: ${i.map(d=>d.key).join(", ")||"keine"}).`);let a=G5(e,n,t);a.length>0&&ce("rm",`\u201E${t}" auf ${n} wird noch gebraucht von: ${a.join("; ")}. Zuerst dort das Ziel \xE4ndern (task set --blocks \u2026 / --clear-blocks) oder die Aktion anpassen.`);let l=i.filter(d=>d.key!==t);return l.length===0?delete r.tasks:r.tasks=l,{bundle:e,nodeId:n,key:t,before:o,after:null,changes:cx(o,null),dropped:[]}}s(rK,"removeNodeTask");function Gc(e){if(e===void 0)return"\u2014";if(typeof e=="string"||typeof e=="number")return String(e);let n=e;return n&&typeof n=="object"&&"de"in n&&"en"in n&&Object.keys(n).length===2?n.de===n.en?String(n.de):`${String(n.de)} | ${String(n.en)}`:JSON.stringify(e)}s(Gc,"renderTaskValue");var Vm=s(e=>({de:e,en:e}),"germanInBothLocales");function z5(e){let n=e.lastIndexOf(":"),t=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(n<=0||t===""||r==="")throw new Error(`offer workflow node add: --on-edge "${e}" must be <fromNodeId>:<outcome>`);return{from:t,outcome:r}}s(z5,"parseEdge");function W5(e){let n={};for(let t of e){let r=t.indexOf("="),i=t.slice(0,r).trim(),o=t.slice(r+1).trim();if(r<=0||i===""||o==="")throw new Error(`offer workflow node add: --progress "${t}" must be <event>=<stateId>`);if(i in n)throw new Error(`offer workflow node add: --progress names "${i}" twice`);n[i]=o}return n}s(W5,"parseProgressPairs");function Ux(e){if(!e)return{};let n={};for(let t of e.split(",")){let r=t.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed pair "${r}" (expected key:value)`);let o=r.slice(0,i).trim(),a=r.slice(i+1).trim().replace(/^["']|["']$/g,"");if(!o||!a)throw new Error(`offer workflow node: malformed pair "${r}" (empty key/value)`);n[o]=a}return n}s(Ux,"parsePairs");function Y5(e){let n=s(t=>t.replace(/^["']|["']$/g,""),"unquote");return e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>{let r=t.indexOf(":"),i=r<0?t:t.slice(0,r).trim(),{id:o,de:a,en:l}=nD(r<0?"":t.slice(r+1));if(!i||!Ri(o)||!a||l===void 0||n(l)==="")throw new Error(`offer workflow node: malformed --decision-outcomes entry "${t}" (expected <id>:<${bt.join("|")}>:<Deutsch>:<English> \u2014 meaning and both languages are required)`);return{id:i,semantic:o,label:{de:n(a),en:n(l)}}})}s(Y5,"parseDecisionOutcomes");function H5(e){let n={};for(let[t,r]of Object.entries(Ux(e))){if(!Ri(r))throw new Error(`offer workflow node set: --outcome-semantics "${t}:${r}" \u2014 the meaning is one of ${bt.join("|")}`);n[t]=r}return n}s(H5,"parseOutcomeSemantics");function J5(e){if(!e)return[];let n=[];for(let t of e.split(",")){let r=t.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed --from "${r}" (expected <nodeId>:<outcome>)`);let o=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(!o||!a)throw new Error(`offer workflow node: malformed --from "${r}" (empty nodeId/outcome)`);n.push({nodeId:o,outcome:a})}return n}s(J5,"parseJoinFrom");function Vx(e){return e.split(":").map(n=>n.trim())}s(Vx,"fields");function Gm(e){return e?e.split(",").map(n=>n.trim()).filter(Boolean):[]}s(Gm,"parseIdList");function aK(e,n){if(e===void 0||e==="")return;let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error(`offer workflow node: malformed ${n} dueInDays "${e}" (expected a positive integer)`);return t}s(aK,"parseDueInDays");function lK(e,n){if(!n||n.length===0)return e;for(let t of n){let[r,i,...o]=Vx(t);if(!r||!i)throw new Error(`offer workflow node: malformed --task-blocks "${t}" (expected <taskKey>:<target>)`);let a=e.find(d=>d.key===r);if(a===void 0)throw new Error(`offer workflow node: --task-blocks "${t}" names task "${r}", which is not among the --task entries (${e.map(d=>d.key).join(", ")||"none"})`);let l=o.filter(d=>d.length>0);if(l.length>0)throw new Error(`offer workflow node: malformed --task-blocks "${t}" \u2014 a blocker holds its target's whole action group; there is no third field (got ${l.map(d=>JSON.stringify(d)).join(", ")})`);a.blocks={templateKey:i}}return e}s(lK,"applyTaskBlocks");function dK(e,n){if(!e)return[];let t=n!==void 0;if(t&&n!=="spawnRevision")throw new Error(`offer workflow node: --task-on-reject must be 'spawnRevision' (got "${n}")`);return e.map(r=>{let i=Vx(r),[o,a,l,d]=i;if(!o||!a||!l)throw new Error(`offer workflow node: malformed --task "${r}" (expected key:kind:title:group[\u2026] \u2014 kind task|approval)`);if(a==="task"){let c=aK(i[4],"--task");return{key:o,kind:a,title:Vm(l),...d?{assign:{group:d}}:{},...c!==void 0?{params:{dueInDays:c}}:{}}}if(a==="approval"){let[,,,,c]=i,u={};return t&&(u.onReject="spawnRevision"),c&&(u.revisionGroup=c),{key:o,kind:a,title:Vm(l),...d?{assign:{group:d}}:{},...Object.keys(u).length>0?{params:u}:{}}}throw new Error(`offer workflow node: malformed --task "${r}" \u2014 kind must be 'task' | 'approval' (got "${a}")`)})}s(dK,"parseTasks");function cK(e){return e?e.map(n=>{let[t,r,i,...o]=Vx(n),a=o.join(":");if(!t||!r||!i)throw new Error(`offer workflow node: malformed --artifact "${n}" (expected key:type:visibility:label)`);if(i!=="internal"&&i!=="external")throw new Error(`offer workflow node: --artifact "${n}" \u2014 visibility must be 'internal' | 'external' (got "${i}")`);if(!Df(r))throw new Error(`offer workflow node: --artifact "${n}" \u2014 type must be one of ${Ks.join(" | ")} (got "${r}")`);return{key:t,type:r,visibility:i,...a?{label:Vm(a)}:{}}}):[]}s(cK,"parseArtifacts");function iK(e){if(e===void 0)return;let n=e.split(":"),t=n[n.length-1],r=n.length>1&&/^\d+$/.test(t)?Number(t):void 0,i=r!==void 0?n.slice(0,-1).join(":"):e;if(!i)throw new Error(`offer workflow node: malformed --decision-as-task "${e}" (expected title[:dueInDays])`);return{title:Vm(i),...r!==void 0?{dueInDays:r}:{}}}s(iK,"parseDecisionAsTask");function Q5(e){let n={};for(let t of e??[]){let r=t.indexOf("=");if(r<=0)throw new Error(`offer workflow node: malformed --literal "${t}" (expected <param>=<value>)`);let i=t.slice(0,r).trim(),o=t.slice(r+1);if(!i)throw new Error(`offer workflow node: malformed --literal "${t}" (empty parameter)`);n[i]=o==="true"?{literal:!0}:o==="false"?{literal:!1}:/^-?\d+(\.\d+)?$/.test(o.trim())?{literal:Number(o.trim())}:{literal:o}}return n}s(Q5,"parseNotificationLiterals");function uK(e){if(e!==void 0){if(!/^\d+$/.test(e.trim()))throw new Error(`offer workflow node: malformed --deadline-days "${e}" (expected whole days, e.g. 14)`);return Number(e.trim())}}s(uK,"parseDeadlineDays");function Z5(e){if(!e||e.length===0)return;let n={};for(let t of e){let r=t.indexOf("="),i=r>0?t.slice(0,r).trim():"",o=r>0?t.slice(r+1).trim():"";if(!i||!o)throw new Error(`offer workflow node: malformed --notification "${t}" (expected <event>=<templateId>)`);if(i in n)throw new Error(`offer workflow node: --notification names event "${i}" twice`);n[i]=o}return n}s(Z5,"parseNotificationBindings");function oK(e,n){if(n==="true")return!0;if(n==="false")return!1;throw new Error(`offer workflow node: ${e} must be 'true' | 'false' (got "${n}")`)}s(oK,"parseBoolOption");function ux(e){if(e!==void 0){if(e==="true")return!0;if(e==="false")return!1;throw new Error(`offer workflow node: --flag-value must be 'true' | 'false' (got "${e}")`)}}s(ux,"parseFlagValue");function mi(e,n,t=` \u2192 NOT written (fix validation errors)
10844
10849
  `){let r=Rt(e).filter(i=>i.severity==="error");if(r.length>0){for(let i of r)n.write(` \u2716 ${i.area}: ${i.message}
10845
- `);return n.write(t),1}return Tt(e),0}s(mi,"validateAndWrite");var fx=class extends xe{static{s(this,"OfferWorkflowNodeListCommand")}static paths=[["offer","workflow","node","list"]];static usage=T.Usage({category:"Offer",description:"List the workflow graph's nodes (id, type, label, outcomes, routing)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=ox(je(this.dir));return this.print(n,t=>t.map(r=>({id:r.id,type:r.type,label:r.label?.de??"\u2014",labelEn:r.label?.en||"\u2014",outcomes:r.outcomes.join(", ")||"\u2014",next:r.next.map(i=>`${i.outcome}\u2192${i.target}`).join(", ")||"\u2014",reads:r.reviewForm!==null?`pr\xFCfpflichtige Felder von ${r.reviewForm}`:r.reads.length>0?`${r.reads.length} Felder`:"\u2014",letters:r.notifications.map(i=>`${i.event}\u2192${i.templateId}${i.disabled?" (aus)":""}`).join(", ")||"\u2014"}))),0}},px=class extends xe{static{s(this,"OfferWorkflowNodeAddCommand")}static paths=[["offer","workflow","node","add"]];static usage=T.Usage({category:"Offer",description:"Insert a workflow node + sync progress layout/wiring; validate before write"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});type=p.String("--type",{required:!0,description:`Node type (${Km.join("|")})`});label=p.String("--label",{required:!0,description:"Node label (German)"});labelEn=p.String("--label-en",{required:!0,description:"Node label (English) \u2014 every node label exists in both languages"});node=p.String("--node",{description:"The new node's id (default: the type, numbered from 2 when taken \u2014 e.g. form, form2)"});after=p.String("--after",{description:"Insert after this node id (default: before the end node)"});onEdge=p.String("--on-edge",{description:"Insert on exactly this edge \u2014 <fromNodeId>:<outcome>; the new node continues to the edge's old target (excludes --after)"});progress=p.Array("--progress",{description:"Put a progress event on an EXISTING board state instead of a new column \u2014 <event>=<stateId> (repeatable)"});outcomes=p.String("--outcomes",{description:"Outcome routing: <outcome>:<target>,\u2026 (defaults splice into chain)"});decisionOutcomes=p.String("--decision-outcomes",{description:"decision only: author a custom outcome SET \u2014 <id>:<granted|rejected|waitlisted|other>:<Deutsch>:<English>,\u2026 (configurable decision node; route with --outcomes)"});form=p.String("--form",{description:"form: SmartForm slug to bind (or the new form's slug with --new-form) \xB7 engagePush (required): the form instance it maps \xB7 review: the form whose review-required fields it checks \u2014 an address '$node.<formNode>.admission'"});newForm=p.Boolean("--new-form",!1,{description:"form only: scaffold the --form SmartForm first, then bind it"});adoptForm=p.String("--adopt-form",{description:"form only: continue this form instance instead of creating one \u2014 '$node.<formNode>.admission' (excludes --form)"});contract=p.String("--contract",{description:"countersign (required) \xB7 engagePush (when the mapping reads it): the contract \u2014 '$node.<contractNode>.contract'"});payment=p.String("--payment",{description:"engagePush only (when the mapping reads it): the payment \u2014 '$node.<paymentNode>.payment'"});outcome=p.String("--outcome",{description:`end only: terminal application outcome (${oi.join("|")}; default approved)`});dataDecision=p.String("--data-decision",{description:"end only (required): commit|discard \u2014 keep or discard the application's data at this end"});waitlistOrder=p.String("--waitlist-order",{description:"waitlist only (required): arrival|manual \u2014 the queue's order"});role=p.String("--role",{description:"roleAssign only: role key granted (a tenant roles.key; checked at publish)"});mode=p.String("--mode",{description:"roleAssign only: add|remove|replace (default add)"});person=p.String("--person",{description:"roleAssign (required) \xB7 completenessCheck (with --guest-role): the party, an address \u2014 '$node.<formNode>.admission.beneficiary'; never defaulted"});from=p.String("--from",{description:"join only: converging sources \u2014 <nodeId>:<outcome>,\u2026 (reroutes each onto this join)"});article=p.String("--article",{description:"collectPayment only (required): the fee's article \u2014 its catalog key (billing_item_definitions.configKey), a one-time article assigned to the offer's program; amount, currency and name are read from it at runtime"});reason=p.String("--reason",{description:"collectPayment only: human-facing reason on the pay screen (German; needs --reason-en)"});reasonEn=p.String("--reason-en",{description:"collectPayment only: the reason in English"});settlement=p.String("--settlement",{description:"collectPayment only (required): online (die Familie zahlt im Portal) | separate (Schule rechnet au\xDFerhalb ab; Zust\xE4ndige*r schlie\xDFt mit \u201EZahlung \xFCberspringen\u201C)"});payee=p.String("--payee",{description:"collectPayment with --settlement online only (required there): the payee Tr\xE4ger \u2014 whose Stripe account takes the money; a legal entity key (foundation.legalEntities[].key). Not the contract's --traeger: a fee and a contract may go to different Tr\xE4ger"});assignDecision=p.String("--assign-decision",{description:"decision/review only: permission-group key whose members hold the decision row (pairs with --decision-as-task)"});commentRequired=p.String("--comment-required",{description:"decision only: authored outcome ids requiring a comment \u2014 <id>[,<id>]"});task=p.Array("--task",{description:"any: composed task \u2014 task: key:task:title:group[:dueInDays] \xB7 approval: key:approval:title:group[:revisionGroup] (repeatable)"});taskBlocks=p.Array("--task-blocks",{description:"any: blocking edge \u2014 <taskKey>:<target> (target: sibling task or intrinsic template, e.g. 'decision' for the Freigabe row; its whole action group waits; repeatable)"});artifact=p.Array("--artifact",{description:"decision/any: declare an artifact slot \u2014 key:type:visibility:label (type offer|contract, visibility internal|external; repeatable)"});taskOnReject=p.String("--task-on-reject",{description:"'spawnRevision' \u2014 applies params.onReject to approval tasks (needs a revisionGroup field)"});decisionAsTask=p.String("--decision-as-task",{description:"decision/review only: override the decision row's caption/SLA \u2014 title[:dueInDays] (optional; the wiring is --assign-decision)"});flagKey=p.String("--flag-key",{description:"setFlag only: external-flag key to flip on the --target instance"});flagValue=p.String("--flag-value",{description:"setFlag only: value to set \u2014 true|false (default true)"});target=p.String("--target",{description:"setFlag only (required): the form instance the flag is raised on \u2014 '$node.<formNode>.admission'"});assignTeam=p.String("--assign-team",{description:"countersign (required): permission-group key whose members countersign (assign.countersign) \xB7 engagePush (required): the team of a stopped transfer (assign.engagePush)"});engageTarget=p.String("--engage-target",{description:"engagePush only (required): sandbox | production"});whenNothingOwed=p.String("--when-nothing-owed",{description:"review only: park (default \u2014 someone looks at it) | advance (pass through when no field is owed)"});engageContractFields=p.String("--engage-contract-fields",{description:"engagePush only: off (default) | on \u2014 the contract fields F01\u2013F25, meaning not confirmed by the school yet"});engageConfig=p.String("--engage-config",{description:"engagePush only (required): JSON file with the mapping (node.engage \u2014 lookup ids, AIF ids; never commit a real school's file)"});title=p.String("--title",{description:"countersign only: the row's title, German (needs --title-en; default \u201EVertrag gegenzeichnen\u201C)"});titleEn=p.String("--title-en",{description:"countersign only: the row's title, English"});dueInDays=p.String("--due-in-days",{description:"countersign only: SLA of the row in days"});require=p.Array("--require",{description:"completenessCheck only: a form field that must be there, as an address '$node.<formNode>.admission.<field>' (repeatable, comma-separated; at least one)"});deadlineDays=p.String("--deadline-days",{description:"completenessCheck only: due N calendar days after entering (excludes --deadline-until; one of the two is required)"});deadlineUntil=p.String("--deadline-until",{description:"completenessCheck only: fixed due day YYYY-MM-DD (tenant zone)"});guestRole=p.String("--guest-role",{description:"completenessCheck only: tenant role key (leaf) held while something is missing; needs --person"});condition=p.String("--condition",{description:"if only (required): one DSL expression over $env, e.g. '$env.staffInput.staffApplication' \u2014 outcomes true/false, route them with --outcomes true:<node>,false:<node>"});notification=p.Array("--notification",{description:"Bind a letter with the node \u2014 <event>=<templateId> (repeatable). Required for an event the type declares required, e.g. completenessCheck: requested=admission.documentsRequested"});async execute(){let n=je(this.dir);if(this.newForm){if(this.type!=="form")throw new Error("offer workflow node add: --new-form is only valid with --type form");if(!this.form)throw new Error("offer workflow node add: --new-form needs --form <slug> (the new form's slug)");Om(n,{key:this.form,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}let t=bq(n,{type:this.type,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.node?{id:this.node}:{},...this.after?{after:this.after}:{},...this.onEdge!==void 0?{onEdge:z3(this.onEdge)}:{},...this.progress!==void 0?{progress:W3(this.progress)}:{},outcomeTargets:Ux(this.outcomes),...this.decisionOutcomes?{decisionOutcomes:Y3(this.decisionOutcomes)}:{},...this.form?this.type==="form"?{formSlug:this.form}:{formSource:this.form}:{},...this.adoptForm!==void 0?{adoptForm:this.adoptForm}:{},...this.target!==void 0?{target:this.target}:{},...this.contract!==void 0?{contract:this.contract}:{},...this.payment!==void 0?{payment:this.payment}:{},...this.outcome?{outcome:this.outcome}:{},...this.dataDecision?{dataDecision:this.dataDecision}:{},...this.waitlistOrder!==void 0?{waitlistOrder:this.waitlistOrder}:{},...this.role?{role:this.role}:{},...this.mode?{mode:this.mode}:{},...this.person?{person:this.person}:{},...this.from?{joinFrom:J3(this.from)}:{},...this.article!==void 0?{article:this.article}:{},...this.reason!==void 0||this.reasonEn!==void 0?{reason:un(this.reason,this.reasonEn,"offer workflow node add","--reason")}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.payee!==void 0?{payee:this.payee}:{},...this.assignDecision?{assignDecision:this.assignDecision}:{},...this.commentRequired?{commentRequired:Gm(this.commentRequired)}:{},...this.task?{tasks:lK(dK(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact?{artifacts:cK(this.artifact)}:{},...iK(this.decisionAsTask)?{decisionAsTask:iK(this.decisionAsTask)}:{},...this.flagKey?{flagKey:this.flagKey}:{},...ux(this.flagValue)!==void 0?{flagValue:ux(this.flagValue)}:{},...this.assignTeam!==void 0?{assignTeam:this.assignTeam}:{},...this.engageTarget!==void 0?{engageTarget:this.engageTarget}:{},...this.whenNothingOwed!==void 0?{whenNothingOwed:this.whenNothingOwed}:{},...this.engageContractFields!==void 0?{engageContractFields:this.engageContractFields}:{},...this.engageConfig!==void 0?{engageConfig:pK(this.engageConfig,"--engage-config")}:{},...this.title!==void 0?{titleDe:this.title}:{},...this.titleEn!==void 0?{titleEn:this.titleEn}:{},...this.dueInDays!==void 0?{dueInDays:aK(this.dueInDays,"--due-in-days")}:{},...this.require!==void 0?{requires:this.require}:{},...this.deadlineDays!==void 0?{deadlineDays:uK(this.deadlineDays)}:{},...this.deadlineUntil!==void 0?{deadlineUntil:this.deadlineUntil}:{},...this.guestRole!==void 0?{guestRole:this.guestRole}:{},...this.condition!==void 0?{condition:this.condition}:{},...this.notification!==void 0?{notifications:Z3(this.notification)}:{}});for(let i of t.warnings)this.context.stderr.write(` \u26A0 ${i}
10850
+ `);return n.write(t),1}return Tt(e),0}s(mi,"validateAndWrite");var fx=class extends xe{static{s(this,"OfferWorkflowNodeListCommand")}static paths=[["offer","workflow","node","list"]];static usage=T.Usage({category:"Offer",description:"List the workflow graph's nodes (id, type, label, outcomes, routing)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=ox(je(this.dir));return this.print(n,t=>t.map(r=>({id:r.id,type:r.type,label:r.label?.de??"\u2014",labelEn:r.label?.en||"\u2014",outcomes:r.outcomes.join(", ")||"\u2014",next:r.next.map(i=>`${i.outcome}\u2192${i.target}`).join(", ")||"\u2014",reads:r.reviewForm!==null?`pr\xFCfpflichtige Felder von ${r.reviewForm}`:r.reads.length>0?`${r.reads.length} Felder`:"\u2014",letters:r.notifications.map(i=>`${i.event}\u2192${i.templateId}${i.disabled?" (aus)":""}`).join(", ")||"\u2014"}))),0}},px=class extends xe{static{s(this,"OfferWorkflowNodeAddCommand")}static paths=[["offer","workflow","node","add"]];static usage=T.Usage({category:"Offer",description:"Insert a workflow node + sync progress layout/wiring; validate before write"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});type=p.String("--type",{required:!0,description:`Node type (${Km.join("|")})`});label=p.String("--label",{required:!0,description:"Node label (German)"});labelEn=p.String("--label-en",{required:!0,description:"Node label (English) \u2014 every node label exists in both languages"});node=p.String("--node",{description:"The new node's id (default: the type, numbered from 2 when taken \u2014 e.g. form, form2)"});after=p.String("--after",{description:"Insert after this node id (default: before the end node)"});onEdge=p.String("--on-edge",{description:"Insert on exactly this edge \u2014 <fromNodeId>:<outcome>; the new node continues to the edge's old target (excludes --after)"});progress=p.Array("--progress",{description:"Put a progress event on an EXISTING board state instead of a new column \u2014 <event>=<stateId> (repeatable)"});outcomes=p.String("--outcomes",{description:"Outcome routing: <outcome>:<target>,\u2026 (defaults splice into chain)"});decisionOutcomes=p.String("--decision-outcomes",{description:"decision only: author a custom outcome SET \u2014 <id>:<granted|rejected|waitlisted|other>:<Deutsch>:<English>,\u2026 (configurable decision node; route with --outcomes)"});form=p.String("--form",{description:"form: SmartForm slug to bind (or the new form's slug with --new-form) \xB7 engagePush (required): the form instance it maps \xB7 review: the form whose review-required fields it checks \u2014 an address '$node.<formNode>.admission'"});newForm=p.Boolean("--new-form",!1,{description:"form only: scaffold the --form SmartForm first, then bind it"});adoptForm=p.String("--adopt-form",{description:"form only: continue this form instance instead of creating one \u2014 '$node.<formNode>.admission' (excludes --form)"});contract=p.String("--contract",{description:"countersign (required) \xB7 engagePush (when the mapping reads it): the contract \u2014 '$node.<contractNode>.contract'"});payment=p.String("--payment",{description:"engagePush only (when the mapping reads it): the payment \u2014 '$node.<paymentNode>.payment'"});outcome=p.String("--outcome",{description:`end only: terminal application outcome (${oi.join("|")}; default approved)`});dataDecision=p.String("--data-decision",{description:"end only (required): commit|discard \u2014 keep or discard the application's data at this end"});waitlistOrder=p.String("--waitlist-order",{description:"waitlist only (required): arrival|manual \u2014 the queue's order"});role=p.String("--role",{description:"roleAssign only: role key granted (a tenant roles.key; checked at publish)"});mode=p.String("--mode",{description:"roleAssign only: add|remove|replace (default add)"});person=p.String("--person",{description:"roleAssign (required) \xB7 completenessCheck (with --guest-role): the party, an address \u2014 '$node.<formNode>.admission.beneficiary'; never defaulted"});from=p.String("--from",{description:"join only: converging sources \u2014 <nodeId>:<outcome>,\u2026 (reroutes each onto this join)"});article=p.String("--article",{description:"collectPayment only (required): the fee's article \u2014 its catalog key (billing_item_definitions.configKey), a one-time article assigned to the offer's program; amount, currency and name are read from it at runtime"});reason=p.String("--reason",{description:"collectPayment only: human-facing reason on the pay screen (German; needs --reason-en)"});reasonEn=p.String("--reason-en",{description:"collectPayment only: the reason in English"});settlement=p.String("--settlement",{description:"collectPayment only (required): online (die Familie zahlt im Portal) | separate (Schule rechnet au\xDFerhalb ab; Zust\xE4ndige*r schlie\xDFt mit \u201EZahlung \xFCberspringen\u201C)"});payee=p.String("--payee",{description:"collectPayment with --settlement online only (required there): the payee Tr\xE4ger \u2014 whose Stripe account takes the money; a legal entity key (foundation.legalEntities[].key). Not the contract's --traeger: a fee and a contract may go to different Tr\xE4ger"});assignDecision=p.String("--assign-decision",{description:"decision/review only: permission-group key whose members hold the decision row (pairs with --decision-as-task)"});commentRequired=p.String("--comment-required",{description:"decision only: authored outcome ids requiring a comment \u2014 <id>[,<id>]"});task=p.Array("--task",{description:"any: composed task \u2014 task: key:task:title:group[:dueInDays] \xB7 approval: key:approval:title:group[:revisionGroup] (repeatable)"});taskBlocks=p.Array("--task-blocks",{description:"any: blocking edge \u2014 <taskKey>:<target> (target: sibling task or intrinsic template, e.g. 'decision' for the Freigabe row; its whole action group waits; repeatable)"});artifact=p.Array("--artifact",{description:"decision/any: declare an artifact slot \u2014 key:type:visibility:label (type offer|contract, visibility internal|external; repeatable)"});taskOnReject=p.String("--task-on-reject",{description:"'spawnRevision' \u2014 applies params.onReject to approval tasks (needs a revisionGroup field)"});decisionAsTask=p.String("--decision-as-task",{description:"decision/review only: override the decision row's caption/SLA \u2014 title[:dueInDays] (optional; the wiring is --assign-decision)"});flagKey=p.String("--flag-key",{description:"setFlag only: external-flag key to flip on the --target instance"});flagValue=p.String("--flag-value",{description:"setFlag only: value to set \u2014 true|false (default true)"});target=p.String("--target",{description:"setFlag only (required): the form instance the flag is raised on \u2014 '$node.<formNode>.admission'"});assignTeam=p.String("--assign-team",{description:"countersign (required): permission-group key whose members countersign (assign.countersign) \xB7 engagePush (required): the team of a stopped transfer (assign.engagePush)"});engageTarget=p.String("--engage-target",{description:"engagePush only (required): sandbox | production"});whenNothingOwed=p.String("--when-nothing-owed",{description:"review only: park (default \u2014 someone looks at it) | advance (pass through when no field is owed)"});engageContractFields=p.String("--engage-contract-fields",{description:"engagePush only: off (default) | on \u2014 the contract fields F01\u2013F25, meaning not confirmed by the school yet"});engageConfig=p.String("--engage-config",{description:"engagePush only (required): JSON file with the mapping (node.engage \u2014 lookup ids, AIF ids; never commit a real school's file)"});title=p.String("--title",{description:"countersign only: the row's title, German (needs --title-en; default \u201EVertrag gegenzeichnen\u201C)"});titleEn=p.String("--title-en",{description:"countersign only: the row's title, English"});dueInDays=p.String("--due-in-days",{description:"countersign only: SLA of the row in days"});require=p.Array("--require",{description:"completenessCheck only: a form field that must be there, as an address '$node.<formNode>.admission.<field>' (repeatable, comma-separated; at least one)"});deadlineDays=p.String("--deadline-days",{description:"completenessCheck only: due N calendar days after entering (excludes --deadline-until; one of the two is required)"});deadlineUntil=p.String("--deadline-until",{description:"completenessCheck only: fixed due day YYYY-MM-DD (tenant zone)"});guestRole=p.String("--guest-role",{description:"completenessCheck only: tenant role key (leaf) held while something is missing; needs --person"});condition=p.String("--condition",{description:"if only (required): one DSL expression over $env, e.g. '$env.staffInput.staffApplication' \u2014 outcomes true/false, route them with --outcomes true:<node>,false:<node>"});notification=p.Array("--notification",{description:"Bind a letter with the node \u2014 <event>=<templateId> (repeatable). Required for an event the type declares required, e.g. completenessCheck: requested=admission.documentsRequested"});async execute(){let n=je(this.dir);if(this.newForm){if(this.type!=="form")throw new Error("offer workflow node add: --new-form is only valid with --type form");if(!this.form)throw new Error("offer workflow node add: --new-form needs --form <slug> (the new form's slug)");Om(n,{key:this.form,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}let t=bq(n,{type:this.type,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.node?{id:this.node}:{},...this.after?{after:this.after}:{},...this.onEdge!==void 0?{onEdge:z5(this.onEdge)}:{},...this.progress!==void 0?{progress:W5(this.progress)}:{},outcomeTargets:Ux(this.outcomes),...this.decisionOutcomes?{decisionOutcomes:Y5(this.decisionOutcomes)}:{},...this.form?this.type==="form"?{formSlug:this.form}:{formSource:this.form}:{},...this.adoptForm!==void 0?{adoptForm:this.adoptForm}:{},...this.target!==void 0?{target:this.target}:{},...this.contract!==void 0?{contract:this.contract}:{},...this.payment!==void 0?{payment:this.payment}:{},...this.outcome?{outcome:this.outcome}:{},...this.dataDecision?{dataDecision:this.dataDecision}:{},...this.waitlistOrder!==void 0?{waitlistOrder:this.waitlistOrder}:{},...this.role?{role:this.role}:{},...this.mode?{mode:this.mode}:{},...this.person?{person:this.person}:{},...this.from?{joinFrom:J5(this.from)}:{},...this.article!==void 0?{article:this.article}:{},...this.reason!==void 0||this.reasonEn!==void 0?{reason:un(this.reason,this.reasonEn,"offer workflow node add","--reason")}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.payee!==void 0?{payee:this.payee}:{},...this.assignDecision?{assignDecision:this.assignDecision}:{},...this.commentRequired?{commentRequired:Gm(this.commentRequired)}:{},...this.task?{tasks:lK(dK(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact?{artifacts:cK(this.artifact)}:{},...iK(this.decisionAsTask)?{decisionAsTask:iK(this.decisionAsTask)}:{},...this.flagKey?{flagKey:this.flagKey}:{},...ux(this.flagValue)!==void 0?{flagValue:ux(this.flagValue)}:{},...this.assignTeam!==void 0?{assignTeam:this.assignTeam}:{},...this.engageTarget!==void 0?{engageTarget:this.engageTarget}:{},...this.whenNothingOwed!==void 0?{whenNothingOwed:this.whenNothingOwed}:{},...this.engageContractFields!==void 0?{engageContractFields:this.engageContractFields}:{},...this.engageConfig!==void 0?{engageConfig:pK(this.engageConfig,"--engage-config")}:{},...this.title!==void 0?{titleDe:this.title}:{},...this.titleEn!==void 0?{titleEn:this.titleEn}:{},...this.dueInDays!==void 0?{dueInDays:aK(this.dueInDays,"--due-in-days")}:{},...this.require!==void 0?{requires:this.require}:{},...this.deadlineDays!==void 0?{deadlineDays:uK(this.deadlineDays)}:{},...this.deadlineUntil!==void 0?{deadlineUntil:this.deadlineUntil}:{},...this.guestRole!==void 0?{guestRole:this.guestRole}:{},...this.condition!==void 0?{condition:this.condition}:{},...this.notification!==void 0?{notifications:Z5(this.notification)}:{}});for(let i of t.warnings)this.context.stderr.write(` \u26A0 ${i}
10846
10851
  `);let r=mi(t.bundle,this.context.stderr);return r!==0?r:(this.print({added:t.nodeId,type:this.type,form:this.form,events:t.events},i=>[{key:"node added",value:i.added},{key:"type",value:i.type},...i.form?[{key:this.type==="form"?"smartForm":"form",value:i.form}]:[],{key:"progress events",value:i.events.join(", ")||"\u2014"}]),0)}},mx=class extends xe{static{s(this,"OfferWorkflowNodeSetCommand")}static paths=[["offer","workflow","node","set"]];static usage=T.Usage({category:"Offer",description:"Edit a workflow node (label/assign-decision/form/target/contract/payment/routing/approval/confirm-issue/confirm-terms/terms-question/response-due-days/deadline/guest-role/settlement/payee/article/traeger/condition/engage-target/when-nothing-owed); validate before write"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id to edit"});label=p.String("--label",{description:"New node label (German). A node with a real English label needs --label-en too"});labelEn=p.String("--label-en",{description:"New node label (English); alone it re-translates the current German"});assignDecision=p.String("--assign-decision",{description:"decision only: replace the decision-row group key (this is the whole wiring)"});commentRequired=p.String("--comment-required",{description:"decision only: replace comment-required outcome ids \u2014 <id>[,<id>]"});requiresOneOf=p.String("--requires-one-of",{description:'decision only: the decision waits until ONE of these optional actions (keys on this node) is completed \u2014 <key>[,<key>]; "" drops the rule'});task=p.Array("--task",{description:"any: replace composed tasks \u2014 task: key:task:title:group[:dueInDays] \xB7 approval: key:approval:title:group[:revisionGroup]"});taskBlocks=p.Array("--task-blocks",{description:"any: blocking edge \u2014 <taskKey>:<target> (target: sibling task or intrinsic template, e.g. 'decision' for the Freigabe row; its whole action group waits; repeatable)"});artifact=p.Array("--artifact",{description:"decision/any: replace artifact slots \u2014 key:type:visibility:label (type offer|contract)"});taskOnReject=p.String("--task-on-reject",{description:"'spawnRevision' applied to approval tasks"});flagKey=p.String("--flag-key",{description:"setFlag only: external-flag key"});flagValue=p.String("--flag-value",{description:"setFlag only: value \u2014 true|false"});target=p.String("--target",{description:"setFlag only: the form instance the flag is raised on \u2014 '$node.<formNode>.admission'"});form=p.String("--form",{description:"form node: rebind to this carried SmartForm slug \xB7 resolver governedDocument / engagePush / review: the form instance it reads \u2014 '$node.<formNode>.admission'"});contract=p.String("--contract",{description:"countersign / engagePush: the contract \u2014 '$node.<contractNode>.contract'"});payment=p.String("--payment",{description:"engagePush only: the payment \u2014 '$node.<paymentNode>.payment'"});outcomes=p.String("--outcomes",{description:"Rewrite routing: <outcome>:<target>,\u2026"});outcome=p.String("--outcome",{description:`end only: re-author terminal outcome (${oi.join("|")})`});outcomeSemantics=p.String("--outcome-semantics",{description:"decision / review only: what each outcome MEANS \u2014 <outcomeId>:<granted|rejected|waitlisted|other>,\u2026"});dataDecision=p.String("--data-decision",{description:"end only: commit|discard \u2014 keep or discard the application's data at this end"});role=p.String("--role",{description:"roleAssign only: role key (a tenant roles.key; checked at publish)"});mode=p.String("--mode",{description:"roleAssign only: add|remove|replace"});person=p.String("--person",{description:"roleAssign \xB7 completenessCheck: the party, an address (e.g. '$node.form.admission.beneficiary')"});deadlineDays=p.String("--deadline-days",{description:"completenessCheck only: replace the deadline \u2014 N calendar days after entering"});deadlineUntil=p.String("--deadline-until",{description:"completenessCheck only: replace the deadline \u2014 fixed due day YYYY-MM-DD"});guestRole=p.String("--guest-role",{description:'completenessCheck only: set the guest role (needs a bound --person); "" drops the role and its person'});approval=p.String("--approval",{description:"governedDocument only: release|none \u2014 the Freigabe before the document goes out. 'none' drops assign.releaseApproval + titles.approve; 'release' drops the confirmation"});signing=p.String("--signing",{description:"governedDocument (generated contract): signedUploadChecked (auf Papier, R\xFCcklauf gepr\xFCft) | eSignature (beim E-Signatur-Anbieter der Schule; adds assign.signingRecovery = the check team). countersign: scan (Scan hochladen) | eSignature (Unterschriftsperson des Tr\xE4gers beim Anbieter; adds assign.signingRecovery = the countersign team)"});approveTitle=p.String("--approve-title",{description:"governedDocument only (with --approval release): the Freigabe task's title (German, stands in for English too); default '<Dokument> freigeben'"});responseDueDays=p.String("--response-due-days",{description:'governedDocument only: the family answers within N calendar days of the issue (1\u2013366; due date + reminder/overdue mails); "" removes the deadline'});confirmIssue=p.String("--confirm-issue",{description:"governedDocument only: true|false \u2014 \u201EBereitstellen\u201C asks before the family sees the document (needs approval none)"});confirmTerms=p.String("--confirm-terms",{description:"governedDocument (signedUpload / signedUploadChecked) only: true|false \u2014 before the signed copy is uploaded, ask \u201EHaben Sie die Vertragsbedingungen gelesen und verstanden?\u201C and log the confirmation (default: on)"});termsQuestionDe=p.String("--terms-question-de",{description:'governedDocument only (with --terms-question-en): reword that question, German; both empty ("") restore the default wording'});termsQuestionEn=p.String("--terms-question-en",{description:"governedDocument only (with --terms-question-de): reword that question, English"});settlement=p.String("--settlement",{description:"collectPayment only: online (die Familie zahlt im Portal) | separate (Schule rechnet au\xDFerhalb ab; Zust\xE4ndige*r schlie\xDFt mit \u201EZahlung \xFCberspringen\u201C)"});article=p.String("--article",{description:"collectPayment only: switch the fee's article \u2014 its catalog key (billing_item_definitions.configKey)"});reason=p.String("--reason",{description:"collectPayment only: the note the family reads (German; needs --reason-en) \u2014 the `reason` input"});reasonEn=p.String("--reason-en",{description:"collectPayment only: the note in English"});payee=p.String("--payee",{description:"collectPayment online only: the payee Tr\xE4ger \u2014 whose Stripe account takes the money (foundation.legalEntities[].key); required when switching to --settlement online without one. Switching to separate drops it. Not the contract's --traeger"});traeger=p.String("--traeger",{description:"generated contract (governedDocument, production resolver) only: the Tr\xE4ger that concludes and countersigns \u2014 a legal entity key (foundation.legalEntities[].key, a school_operator or service_entity); publish refuses an unknown one"});condition=p.String("--condition",{description:"if only: replace the condition \u2014 one DSL expression over $env, e.g. '$env.staffInput.staffApplication'"});engageTarget=p.String("--engage-target",{description:"engagePush only: switch the target \u2014 sandbox | production (the go-live step)"});whenNothingOwed=p.String("--when-nothing-owed",{description:"review only: park (someone looks at it) | advance (pass through when no field is owed)"});type=p.String("--type",{description:"(not editable) \u2014 remove + add to change node type"});async execute(){if(this.type!==void 0)return this.context.stderr.write(` \u2716 offer workflow node set: --type is not editable (a type change rewires outcomes/specs/progress).
10847
10852
  \u2192 remove the node (offer workflow node rm) and add it again (offer workflow node add).
10848
10853
  `),1;if(this.termsQuestionDe===void 0!=(this.termsQuestionEn===void 0))return this.context.stderr.write(` \u2716 offer workflow node set: --terms-question-de and --terms-question-en go together \u2014 the question exists in both languages.
10849
- `),1;let n=je(this.dir),t=Pq(n,{id:this.node,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.form!==void 0?{form:this.form}:{},...this.target!==void 0?{target:this.target}:{},...this.contract!==void 0?{contract:this.contract}:{},...this.payment!==void 0?{payment:this.payment}:{},...this.outcomes!==void 0?{outcomeTargets:Ux(this.outcomes)}:{},...this.outcome!==void 0?{outcome:this.outcome}:{},...this.outcomeSemantics!==void 0?{outcomeSemantics:H3(this.outcomeSemantics)}:{},...this.dataDecision!==void 0?{dataDecision:this.dataDecision}:{},...this.role!==void 0?{role:this.role}:{},...this.mode!==void 0?{mode:this.mode}:{},...this.person!==void 0?{person:this.person}:{},...this.approval!==void 0?{approval:this.approval}:{},...this.signing!==void 0?{signing:this.signing}:{},...this.approveTitle!==void 0?{approveTitle:this.approveTitle}:{},...this.confirmIssue!==void 0?{confirmIssue:oK("--confirm-issue",this.confirmIssue)}:{},...this.confirmTerms!==void 0?{confirmTerms:oK("--confirm-terms",this.confirmTerms)}:{},...this.termsQuestionDe!==void 0&&this.termsQuestionEn!==void 0?{termsQuestion:this.termsQuestionDe===""&&this.termsQuestionEn===""?null:{de:this.termsQuestionDe,en:this.termsQuestionEn}}:{},...this.responseDueDays!==void 0?{responseDueDays:this.responseDueDays===""?null:Number(this.responseDueDays)}:{},...this.assignDecision!==void 0?{assignDecision:this.assignDecision}:{},...this.commentRequired!==void 0?{commentRequired:Gm(this.commentRequired)}:{},...this.requiresOneOf!==void 0?{requiresOneOf:Gm(this.requiresOneOf)}:{},...this.task!==void 0?{tasks:lK(dK(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact!==void 0?{artifacts:cK(this.artifact)}:{},...this.flagKey!==void 0?{flagKey:this.flagKey}:{},...this.flagValue!==void 0?{flagValue:ux(this.flagValue)}:{},...this.deadlineDays!==void 0?{deadlineDays:uK(this.deadlineDays)}:{},...this.deadlineUntil!==void 0?{deadlineUntil:this.deadlineUntil}:{},...this.guestRole!==void 0?{guestRole:this.guestRole}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.payee!==void 0?{payee:this.payee}:{},...this.article!==void 0?{article:this.article}:{},...this.reason!==void 0||this.reasonEn!==void 0?{reason:un(this.reason,this.reasonEn,"offer workflow node set","--reason")}:{},...this.traeger!==void 0?{traeger:this.traeger}:{},...this.condition!==void 0?{condition:this.condition}:{},...this.engageTarget!==void 0?{engageTarget:this.engageTarget}:{},...this.whenNothingOwed!==void 0?{whenNothingOwed:this.whenNothingOwed}:{}}),r=mi(t.bundle,this.context.stderr);return r!==0?r:(this.print({node:t.nodeId,changed:t.changed},i=>[{key:"node edited",value:i.node},{key:"changed",value:i.changed.join(", ")||"\u2014"}]),0)}},hx=class extends xe{static{s(this,"OfferWorkflowNodeSetNotificationCommand")}static paths=[["offer","workflow","node","set-notification"]];static usage=T.Usage({category:"Offer",description:"Bind a letter to one of a node's declared events; validate before write",details:"The node TYPE declares at which events it can write to a family and with which typed arguments; this binds a letter to one of them. An argument binds itself when exactly one of the event's arguments (or an ambient one) carries its name and a compatible type \u2014 pass --literal only for what the event cannot supply.\n\nOffline this catches an event the node type does not declare. An unknown TEMPLATE id and an unresolvable argument are caught server-side at `offer apply --publish`: the letter catalog deliberately does not travel with the offline validators.",examples:[["Send the rejection letter when the decision says no","$0 offer workflow node set-notification --dir ./bundle --node decision --event rejected --template admission.rejected"],["Author it, switched off","$0 offer workflow node set-notification --dir ./bundle --node waitlist --event placed --template admission.waitlisted --disabled"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the binding"});event=p.String("--event",{required:!0,description:"Event id declared by that node's type (e.g. approved)"});template=p.String("--template",{required:!0,description:"Letter registry key (e.g. admission.rejected)"});literal=p.Array("--literal",{description:"Fix a letter parameter to a value \u2014 <param>=<value> (true/false \u2192 boolean, digits \u2192 number; repeatable)"});disabled=p.Boolean("--disabled",!1,{description:"Author the binding but keep it switched off"});async execute(){let n=Q3(this.literal),t=je(this.dir),r=hq(t,{id:this.node,event:this.event,templateId:this.template,...Object.keys(n).length>0?{args:n}:{},...this.disabled?{disabled:!0}:{}}),i=mi(r.bundle,this.context.stderr);return i!==0?i:(this.print({node:r.nodeId,event:r.event,templateId:r.binding.templateId,args:r.binding.args??{},disabled:r.binding.disabled===!0,replaced:r.replaced},o=>[{key:o.replaced?"binding replaced":"binding added",value:`${o.node}.${o.event}`},{key:"letter",value:o.templateId},{key:"explicit args",value:Object.entries(o.args).map(([a,l])=>`${a}=${JSON.stringify(l.literal)}`).join(", ")||"\u2014 (all resolved automatically)"},{key:"state",value:o.disabled?"disabled":"active"}]),0)}},gx=class extends xe{static{s(this,"OfferWorkflowNodeClearNotificationCommand")}static paths=[["offer","workflow","node","clear-notification"]];static usage=T.Usage({category:"Offer",description:"Remove a node's letter binding for one event; validate before write",details:"The node then says nothing at that event \u2014 which is a legitimate choice unless the node type declares the event `required`, in which case the publish gate refuses the removal ([notification/missingBinding]). Use `set-notification --disabled` to switch a letter off without losing how its arguments were wired.",examples:[["Say nothing on rejection","$0 offer workflow node clear-notification --dir ./bundle --node decision --event rejected"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the binding"});event=p.String("--event",{required:!0,description:"Event id whose binding is removed"});async execute(){let n=gq(je(this.dir),this.node,this.event),t=mi(n.bundle,this.context.stderr,` \u2192 NOT written (this event's letter is required by the node type)
10854
+ `),1;let n=je(this.dir),t=Pq(n,{id:this.node,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.form!==void 0?{form:this.form}:{},...this.target!==void 0?{target:this.target}:{},...this.contract!==void 0?{contract:this.contract}:{},...this.payment!==void 0?{payment:this.payment}:{},...this.outcomes!==void 0?{outcomeTargets:Ux(this.outcomes)}:{},...this.outcome!==void 0?{outcome:this.outcome}:{},...this.outcomeSemantics!==void 0?{outcomeSemantics:H5(this.outcomeSemantics)}:{},...this.dataDecision!==void 0?{dataDecision:this.dataDecision}:{},...this.role!==void 0?{role:this.role}:{},...this.mode!==void 0?{mode:this.mode}:{},...this.person!==void 0?{person:this.person}:{},...this.approval!==void 0?{approval:this.approval}:{},...this.signing!==void 0?{signing:this.signing}:{},...this.approveTitle!==void 0?{approveTitle:this.approveTitle}:{},...this.confirmIssue!==void 0?{confirmIssue:oK("--confirm-issue",this.confirmIssue)}:{},...this.confirmTerms!==void 0?{confirmTerms:oK("--confirm-terms",this.confirmTerms)}:{},...this.termsQuestionDe!==void 0&&this.termsQuestionEn!==void 0?{termsQuestion:this.termsQuestionDe===""&&this.termsQuestionEn===""?null:{de:this.termsQuestionDe,en:this.termsQuestionEn}}:{},...this.responseDueDays!==void 0?{responseDueDays:this.responseDueDays===""?null:Number(this.responseDueDays)}:{},...this.assignDecision!==void 0?{assignDecision:this.assignDecision}:{},...this.commentRequired!==void 0?{commentRequired:Gm(this.commentRequired)}:{},...this.requiresOneOf!==void 0?{requiresOneOf:Gm(this.requiresOneOf)}:{},...this.task!==void 0?{tasks:lK(dK(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact!==void 0?{artifacts:cK(this.artifact)}:{},...this.flagKey!==void 0?{flagKey:this.flagKey}:{},...this.flagValue!==void 0?{flagValue:ux(this.flagValue)}:{},...this.deadlineDays!==void 0?{deadlineDays:uK(this.deadlineDays)}:{},...this.deadlineUntil!==void 0?{deadlineUntil:this.deadlineUntil}:{},...this.guestRole!==void 0?{guestRole:this.guestRole}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.payee!==void 0?{payee:this.payee}:{},...this.article!==void 0?{article:this.article}:{},...this.reason!==void 0||this.reasonEn!==void 0?{reason:un(this.reason,this.reasonEn,"offer workflow node set","--reason")}:{},...this.traeger!==void 0?{traeger:this.traeger}:{},...this.condition!==void 0?{condition:this.condition}:{},...this.engageTarget!==void 0?{engageTarget:this.engageTarget}:{},...this.whenNothingOwed!==void 0?{whenNothingOwed:this.whenNothingOwed}:{}}),r=mi(t.bundle,this.context.stderr);return r!==0?r:(this.print({node:t.nodeId,changed:t.changed},i=>[{key:"node edited",value:i.node},{key:"changed",value:i.changed.join(", ")||"\u2014"}]),0)}},hx=class extends xe{static{s(this,"OfferWorkflowNodeSetNotificationCommand")}static paths=[["offer","workflow","node","set-notification"]];static usage=T.Usage({category:"Offer",description:"Bind a letter to one of a node's declared events; validate before write",details:"The node TYPE declares at which events it can write to a family and with which typed arguments; this binds a letter to one of them. An argument binds itself when exactly one of the event's arguments (or an ambient one) carries its name and a compatible type \u2014 pass --literal only for what the event cannot supply.\n\nOffline this catches an event the node type does not declare. An unknown TEMPLATE id and an unresolvable argument are caught server-side at `offer apply --publish`: the letter catalog deliberately does not travel with the offline validators.",examples:[["Send the rejection letter when the decision says no","$0 offer workflow node set-notification --dir ./bundle --node decision --event rejected --template admission.rejected"],["Author it, switched off","$0 offer workflow node set-notification --dir ./bundle --node waitlist --event placed --template admission.waitlisted --disabled"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the binding"});event=p.String("--event",{required:!0,description:"Event id declared by that node's type (e.g. approved)"});template=p.String("--template",{required:!0,description:"Letter registry key (e.g. admission.rejected)"});literal=p.Array("--literal",{description:"Fix a letter parameter to a value \u2014 <param>=<value> (true/false \u2192 boolean, digits \u2192 number; repeatable)"});disabled=p.Boolean("--disabled",!1,{description:"Author the binding but keep it switched off"});async execute(){let n=Q5(this.literal),t=je(this.dir),r=hq(t,{id:this.node,event:this.event,templateId:this.template,...Object.keys(n).length>0?{args:n}:{},...this.disabled?{disabled:!0}:{}}),i=mi(r.bundle,this.context.stderr);return i!==0?i:(this.print({node:r.nodeId,event:r.event,templateId:r.binding.templateId,args:r.binding.args??{},disabled:r.binding.disabled===!0,replaced:r.replaced},o=>[{key:o.replaced?"binding replaced":"binding added",value:`${o.node}.${o.event}`},{key:"letter",value:o.templateId},{key:"explicit args",value:Object.entries(o.args).map(([a,l])=>`${a}=${JSON.stringify(l.literal)}`).join(", ")||"\u2014 (all resolved automatically)"},{key:"state",value:o.disabled?"disabled":"active"}]),0)}},gx=class extends xe{static{s(this,"OfferWorkflowNodeClearNotificationCommand")}static paths=[["offer","workflow","node","clear-notification"]];static usage=T.Usage({category:"Offer",description:"Remove a node's letter binding for one event; validate before write",details:"The node then says nothing at that event \u2014 which is a legitimate choice unless the node type declares the event `required`, in which case the publish gate refuses the removal ([notification/missingBinding]). Use `set-notification --disabled` to switch a letter off without losing how its arguments were wired.",examples:[["Say nothing on rejection","$0 offer workflow node clear-notification --dir ./bundle --node decision --event rejected"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the binding"});event=p.String("--event",{required:!0,description:"Event id whose binding is removed"});async execute(){let n=gq(je(this.dir),this.node,this.event),t=mi(n.bundle,this.context.stderr,` \u2192 NOT written (this event's letter is required by the node type)
10850
10855
  `);return t!==0?t:(this.print({node:n.nodeId,event:n.event,templateId:n.templateId},r=>[{key:"binding removed",value:`${r.node}.${r.event}`},{key:"was",value:r.templateId}]),0)}},fK="Each entry is a full address naming its form: --address '$node.<formNode>.admission.<field>' (single quotes \u2014 the shell would expand $node), repeatable and comma-separated; or the short form --from <formNode> --field <path>[,<path>], which composes exactly that address. A bare key is refused with the list of addresses visible at the node. Only errors the edit INTRODUCES block it; errors the bundle already had are listed as warnings.",Gx="`reads` names the SmartForm fields a human reads before the node acts \u2014 for an uploaded contract, the fields staff copy into it. The readiness gate holds the node's actions while one of them has an open correction or is empty where the form requires it, and once the document is issued those fields are consumed (a correction is refused until it is rescinded). Allowed on decision nodes and on governedDocument nodes that produce a document.\n\nEvery address is resolved offline against the SmartForm its form node pins, by the same `[address/*]` / `[readiness/*]` rules publish runs: an unknown field, a field inside a repeated block, a form that does not run before the node, two forms in one list or a duplicate refuses the write.\n\n"+fK,zm=class extends xe{static{s(this,"NodeKeyListCommand")}writeKeyListEdit(n,t,r,i){let o;if(Ji(this.context.stderr,n,[`nodes.${t}.${r}`],`${r} keys`,d=>(o=i(d),o.bundle))===null)return 1;let l=o;return this.print({node:l.nodeId,[r]:l.after,after:l.after,added:l.added,removed:l.removed,unchanged:l.unchanged},d=>[{key:"node",value:d.node},{key:"added",value:d.added.join(", ")||"\u2014"},{key:"removed",value:d.removed.join(", ")||"\u2014"},...d.unchanged.length>0?[{key:"already read",value:d.unchanged.join(", ")}]:[],{key:`${r} now`,value:d.after.length>0?`${d.after.length}: ${d.after.join(", ")}`:"\u2014 (no declaration)"}]),0}};function sK(e){if(e===void 0)return"\u2014 (default)";let n=e;return n.kind==="binding"?`binding ${Vc(n.address,"binding")}`:n.kind==="literal"?`literal ${JSON.stringify(n.value)}`:n.kind==="cockpit"?"cockpit (entered before generating)":"unset"}s(sK,"describeCell");var yx=class extends xe{static{s(this,"OfferWorkflowNodeSetInputCommand")}static paths=[["offer","workflow","node","set-input"]];static usage=T.Usage({category:"Offer",description:"Bind one input of a node to an address, set a literal, or clear it; validate before write",details:"The input must be a slot the node declares (a template document's slots are its template's parameters \u2014 stamped by `offer workflow restamp-pins` or `offer plan`). A binding names the full address it reads (single quotes \u2014 the shell would expand $): '$node.<formNode>.admission.<field>' (a form field; short form --from <formNode> --field <path>), '$task.<task>.<key>' (a value a task records), '$derived.<key>' (a computed price), '$env.applicant.language'. A bare key is refused with the addresses visible at the node. Whether the address resolves, fits the slot and is produced on every path before the node is the publish gate's question, run before writing: [address/*], [governedDocument/envNotCovered], the uncovered-input contract.",examples:[["Write the offer letter in the applicant's language","$0 offer workflow node set-input --dir ./bundle --node angebot --input sprache --address '$env.applicant.language'"],["Tuition, the derived price","$0 offer workflow node set-input --dir ./bundle --node contract --input schulgeld --address '$derived.schulgeld'"],["A form field (short form)","$0 offer workflow node set-input --dir ./bundle --node contract --input vorname --from form --field kind.vorname"],["A fixed value",`$0 offer workflow node set-input --dir ./bundle --node angebot --input sprache --literal '"de"'`],["Back to the slot's default","$0 offer workflow node set-input --dir ./bundle --node angebot --input sprache --clear"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id"});input=p.String("--input",{required:!0,description:"Input slot key (e.g. a template field)"});address=p.String("--address",{description:"The address bound, e.g. '$env.applicant.language', '$derived.schulgeld', '$node.form.admission.kind.vorname'"});from=p.String("--from",{description:"Short form with --field: the form node whose field is bound ($node.<from>.admission.<field>)"});field=p.String("--field",{description:"Short form with --from: the field path in that node's form"});literal=p.String("--literal",{description:'A JSON value: "de", 3, true, null, or {"itemKey":\u2026,"grantKeys":[\u2026]}'});clear=p.Boolean("--clear",!1,{description:"Remove the cell (the slot falls back to its default)"});async execute(){let n=Nq({...this.address!==void 0?{address:this.address}:{},...this.from!==void 0?{from:this.from}:{},...this.field!==void 0?{field:this.field}:{},...this.literal!==void 0?{literal:this.literal}:{},clear:this.clear}),t,r;return Ji(this.context.stderr,this.dir,[`nodes.${this.node}.inputs.${this.input}`,`node.${this.node}.input.${this.input}`],`input "${this.input}"`,o=>{let a=Cq(o,this.node,this.input,n);return t=a.before,r=a.after,a.bundle})===null?1:(this.print({node:this.node,input:this.input,before:t??null,after:r??null},o=>[{key:"node",value:o.node},{key:"input",value:o.input},{key:"before",value:sK(o.before??void 0)},{key:"now",value:sK(o.after??void 0)}]),0)}};function pK(e,n){let t;try{t=ye(e,"utf8")}catch(r){throw new Error(`${n}: ${e} is not readable (${r instanceof Error?r.message:String(r)})`,{cause:r})}try{return JSON.parse(t)}catch(r){throw new Error(`${n}: ${e} is no JSON (${r instanceof Error?r.message:String(r)})`,{cause:r})}}s(pK,"readJsonFile");var wx=class extends xe{static{s(this,"OfferWorkflowNodeSetEngageCommand")}static paths=[["offer","workflow","node","set-engage"]];static usage=T.Usage({category:"Offer",description:"Replace an engagePush node's Engage mapping from a JSON file; validate before write",details:"The mapping (`node.engage`) is the school's Engage configuration \u2014 lookup ids, AIF field ids, the admission stage \u2014 and belongs in the bundle, never in git. The publish gate checks its shape and the fields against the form its `form` address names ([engagePush/config], warning [engagePush/unmappedField]) before anything is written. Temporary.",examples:[["Update the Engage mapping","$0 offer workflow node set-engage --dir ./school-r17 --node engagePush --config ./engage.json"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"The engagePush node's id"});config=p.String("--config",{required:!0,description:"JSON file with the mapping"});async execute(){let n=pK(this.config,"--config");return Ji(this.context.stderr,this.dir,[`nodes.${this.node}`],"engage mapping",r=>Lq(r,this.node,n).bundle)===null?1:(this.print({node:this.node,config:this.config},r=>[{key:"node",value:r.node},{key:"mapping",value:r.config}]),0)}},zc=class extends zm{static{s(this,"NodeReadsCommand")}writeReadsEdit(n,t,r){return this.writeKeyListEdit(n,t,"reads",i=>yq(i,t,r))}},kx=class extends zc{static{s(this,"OfferWorkflowNodeSetReadsCommand")}static paths=[["offer","workflow","node","set-reads"]];static usage=T.Usage({category:"Offer",description:"Replace the form fields a node reads before acting (readiness gate); validate before write",details:Gx,examples:[["The contract copies the child's and parents' names","$0 offer workflow node set-reads --dir ./bundle --node contract --address '$node.form.admission.kind.vorname,$node.form.admission.kind.nachname'"],["The same, short form","$0 offer workflow node set-reads --dir ./bundle --node contract --from form --field kind.vorname,kind.nachname"],["Drop the declaration","$0 offer workflow node set-reads --dir ./bundle --node contract --clear"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id (decision or governedDocument)"});address=p.Array("--address",{description:"A form field's address '$node.<formNode>.admission.<field>' (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are read"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});clear=p.Boolean("--clear",!1,{description:"Remove the node's reads declaration"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});if(this.clear&&n.length>0)throw new Error("offer workflow node set-reads: --clear and --address/--field exclude each other");return this.writeReadsEdit(this.dir,this.node,this.clear?{op:"clear"}:{op:"set",addresses:n})}},bx=class extends zc{static{s(this,"OfferWorkflowNodeAddReadsCommand")}static paths=[["offer","workflow","node","add-reads"]];static usage=T.Usage({category:"Offer",description:"Add form fields to a node's reads (addresses already read are kept); validate before write",details:Gx,examples:[["Also read the birth date","$0 offer workflow node add-reads --dir ./bundle --node contract --address '$node.form.admission.kind.geburtsdatum'"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id (decision or governedDocument)"});address=p.Array("--address",{description:"A form field's address '$node.<formNode>.admission.<field>' (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are read"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});return this.writeReadsEdit(this.dir,this.node,{op:"add",addresses:n})}},vx=class extends zc{static{s(this,"OfferWorkflowNodeRemoveReadsCommand")}static paths=[["offer","workflow","node","remove-reads"]];static usage=T.Usage({category:"Offer",description:"Remove form fields from a node's reads (an address it does not read fails); validate before write",details:Gx,examples:[["Stop reading the birth date","$0 offer workflow node remove-reads --dir ./bundle --node contract --address '$node.form.admission.kind.geburtsdatum'"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the reads"});address=p.Array("--address",{description:"Address to drop (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are dropped"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});return this.writeReadsEdit(this.dir,this.node,{op:"remove",addresses:n})}},zx="`requires` names the SmartForm fields a completenessCheck waits for: entered with all of them there it completes at once; otherwise the family gets ONE request (\u201EUnterlagen nachreichen\u201C) with the node's deadline, and the node parks until the last one arrives or a person closes it. A field the form currently hides is not owed.\n\nEvery address is resolved offline against the SmartForm its form node pins, by the `[address/*]` and the node's own `[completenessCheck/*]` rules: an unknown field, a computed field, a field inside a repeated block, two forms in one list or a duplicate refuses the write, and so does removing the last address.\n\n"+fK,Wc=class extends zm{static{s(this,"NodeRequiresCommand")}writeRequiresEdit(n,t,r){return this.writeKeyListEdit(n,t,"requires",i=>wq(i,t,r))}},xx=class extends Wc{static{s(this,"OfferWorkflowNodeSetRequiresCommand")}static paths=[["offer","workflow","node","set-requires"]];static usage=T.Usage({category:"Offer",description:"Replace the form fields a completenessCheck waits for; validate before write",details:zx,examples:[["Measles protection and birth certificate must be there","$0 offer workflow node set-requires --dir ./bundle --node nachreichen --address '$node.form.admission.kind.masernschutz,$node.form.admission.kind.geburtsurkunde'"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"completenessCheck node id"});address=p.Array("--address",{description:"A form field's address '$node.<formNode>.admission.<field>' (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are meant"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"set",addresses:n})}},Sx=class extends Wc{static{s(this,"OfferWorkflowNodeAddRequiresCommand")}static paths=[["offer","workflow","node","add-requires"]];static usage=T.Usage({category:"Offer",description:"Add form fields a completenessCheck waits for (addresses already required are kept); validate before write",details:zx,examples:[["Also wait for the vaccination record","$0 offer workflow node add-requires --dir ./bundle --node nachreichen --from form --field kind.impfpass"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"completenessCheck node id"});address=p.Array("--address",{description:"A form field's address '$node.<formNode>.admission.<field>' (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are meant"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"add",addresses:n})}},Ax=class extends Wc{static{s(this,"OfferWorkflowNodeRemoveRequiresCommand")}static paths=[["offer","workflow","node","remove-requires"]];static usage=T.Usage({category:"Offer",description:"Remove form fields a completenessCheck waits for (an address it does not require fails; the last one cannot go); validate before write",details:zx,examples:[["Stop waiting for the vaccination record","$0 offer workflow node remove-requires --dir ./bundle --node nachreichen --address '$node.form.admission.kind.impfpass'"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"completenessCheck node id"});address=p.Array("--address",{description:"A form field's address '$node.<formNode>.admission.<field>' (repeatable, comma-separated)"});from=p.String("--from",{description:"Short form with --field: the form node whose fields are meant"});field=p.Array("--field",{description:"Short form with --from: field paths of that node's form (repeatable, comma-separated)"});async execute(){let n=Ho({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"remove",addresses:n})}},Wx=`A composed task spawns when its node is entered (and, with --when, while that boolean form export holds \u2014 named by its address, e.g. --when '$node.form.admission.antragErmaessigung'). Every flag that reads data takes full addresses (single quotes \u2014 the shell would expand $): --when, --reads, --documents (artifact:<own slot>, field:<address>, document:$node.<node>.document), --family-request-fields / --family-request-from, a record field's suggest {"kind":"form","address":"$node.\u2026"}. A bare key is refused with the addresses visible at the node. --blocks withholds a target's actions while the task is open: a bare <templateKey> is a sibling on the same node, <nodeId>:<templateKey> a template on a LATER node (a cross-node blocker, which survives the node exit and needs a --result). Intrinsic targets: \`decision\`, \`prepareDocument\`, \`releaseApproval\`. The target's whole action group waits \u2014 on a decision Freigeben, Warteliste, Ablehnen and Nachr\xFCcken.
10851
10856
 
10852
10857
  A task with --result closes only by recording it: freetext (text, always required), recommendation (Positiv/Neutral/Negativ + optional text), choice (>= 2 --option key=Label[|English] + optional text). --chat (required for these three) names the one chat the result is posted to and documented in: all | team:<group> | <authored channel key> \u2014 never external. A result with a value (choice, pricedItem, reduction) writes it under the task's own address (--writes '$task.<task>.<key>') and names it (--result-label); a pricedItem names its article (--item <catalog key>), a reduction the derived price it lowers (--prices '$derived.<key>').
@@ -10861,10 +10866,10 @@ A task with --result closes only by recording it: freetext (text, always require
10861
10866
  `),1;let n=this.generator!==void 0?{key:this.generator,kind:"generator"}:{key:this.pkg,kind:"package"},t;if(Ji(this.context.stderr,this.dir,[`nodes.${this.node}.inputs.contractGenerator`,`node.${this.node}.input.contractGenerator`,`nodes.${this.node}.generatorStamp`],"generator pin",o=>(t=G0(o,this.node,n),o))===null||t===void 0)return 1;let i=s(o=>o===null?"\u2014":`${o.kind}:${o.key}`,"show");return this.print({node:this.node,...t},o=>[{key:"node",value:o.node},{key:"before",value:i(o.before)},{key:"now",value:i(o.after)},{key:"next",value:o.droppedStamp||o.before===null?"offer workflow restamp-pins --env <env> stamps the pin (then node set-input knows its fields)":"\u2014"},{key:"kept cells",value:o.keptParameterCells.length===0?"\u2014":`${o.keptParameterCells.join(", ")} \u2014 those the new generator does not declare are refused once stamped ([inputs/undeclared]); remove with node set-input --clear`}]),0}},Kx=class extends xe{static{s(this,"OfferWorkflowNodeSetCockpitFieldsCommand")}static paths=[["offer","workflow","node","set-cockpit-fields"]];static usage=T.Usage({category:"Offer",description:"Replace the fields a contract node leaves to the cockpit mask (generator or Word template); validate before write",details:'A cockpit field is a parameter the team fills in the cockpit before generating, instead of a binding or a fixed value \u2014 its `required` holds at generation, not at publish. Writes each listed parameter\'s cell `{ kind: "cockpit" }`, on a generator node and on a Word-template node alike; parameters left before and not listed lose it, "" takes all back. A parameter holding a binding or a fixed value is refused (clear it first). A name the generator / template does not declare is refused by the gate ([inputs/undeclared] once `offer plan` stamped the pin), and so is a node-type setting such as the reserved Tr\xE4ger ([inputs/notDeferrable]). A party field needs no entry: the cockpit is its only source.',examples:[["Leave the note and the start date to the cockpit","$0 offer workflow node set-cockpit-fields --dir ./bundle --node contract --fields hinweis,startDate"],["None any more",'$0 offer workflow node set-cockpit-fields --dir ./bundle --node contract --fields ""']]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"The contract node's id"});fields=p.String("--fields",{required:!0,description:'Parameter keys, comma-separated; "" takes all back'});async execute(){let n=Gm(this.fields),t;return Ji(this.context.stderr,this.dir,[`nodes.${this.node}.inputs`,`nodes.${this.node}`],"cockpit fields",i=>(t=z0(i,this.node,n),i))===null||t===void 0?1:(this.print({node:this.node,...t},i=>[{key:"node",value:i.node},{key:"pin",value:i.pin},{key:"before",value:i.before.join(", ")||"\u2014"},{key:"now",value:i.after.join(", ")||"\u2014"}]),0)}},jx=class extends xe{static{s(this,"OfferWorkflowRestampExportsCommand")}static paths=[["offer","workflow","restamp-exports"]];static usage=T.Usage({category:"Offer",description:"Re-stamp every form node's formExports from the form the bundle carries (publish's own derivation); validate before write",details:"An exported bundle carries each form node's `formExports` \u2014 the exported leaves of its form, stamped by publish \u2014 and the offline address checks read that copy. After a form change (a field exported, removed or retyped) the copy is stale: a binding to a newly exported field reads as [address/pathNotInTarget], one to a removed field passes offline and fails at publish. `offer validate` warns [formExports/stale]; this verb writes what publish would. `offer form field export` re-stamps by itself. Refused while a form node binds a form the bundle does not carry or the gate refuses.",examples:[["After editing a form by hand","$0 offer workflow restamp-exports --dir ./bundle"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=[];return Ji(this.context.stderr,this.dir,[],"formExports stamp",r=>(n=Pm(r),r))===null?1:(this.print(n,r=>r.map(i=>({node:i.node,form:i.form,changed:i.changed?"yes":"no",before:i.before===null?"(none)":i.before.join(", ")||"\u2014",now:i.after.join(", ")||"\u2014"}))),0)}},Bx=class extends D{static{s(this,"OfferWorkflowRestampPinsCommand")}static paths=[["offer","workflow","restamp-pins"]];static usage=T.Usage({category:"Offer",description:"Stamp every contract generator/package pin and every Word-template node from the environment into the bundle, so the offline verbs know their fields",details:"A contract node's input `contractGenerator: { kind, key }` names a generator or package by key; its parameters, parties and parts are what the environment's current sealed revision declares. `offer plan|apply` fetch that stamp in memory; this verb WRITES it into workflow.json \u2014 the same stamp publish writes \u2014 so `node set-input` can bind a package's fields offline, without saving a draft and exporting it. Reads only (no deployment write). A pin the environment refuses (unknown key, no sealed revision) writes nothing. Required fields still without a source are listed as the to-do list, not refused: bind them with `node set-input`. Re-run after the package is resealed; `offer plan` re-stamps regardless.",examples:[["Pin, stamp, bind","$0 offer workflow node set-generator --dir ./bundle --node contract --package school-with-care && $0 --env staging --tenant <slug> offer workflow restamp-pins --dir ./bundle"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let n=await this.caller(),{rows:t,refused:r,open:i}=await H0(n,this.requireTenant(n),this.dir);if(r.length>0){for(let o of r)this.context.stderr.write(` \u2716 ${o.area}: ${o.message}
10862
10867
  `);return this.context.stderr.write(` \u2192 NOT written (fix the pin or seal the generator/package first)
10863
10868
  `),1}for(let o of i)this.context.stderr.write(` \xB7 to bind: ${o.message}
10864
- `);return this.print({stamped:t,open:i.map(o=>o.message)},o=>[...o.stamped.map(a=>({node:a.target.slice(6),stamp:a.detail})),{node:"open",stamp:o.open.length===0?"\u2014":`${o.open.length} finding(s) on the stamped nodes \u2014 bind with node set-input`}]),0}},hK=[fx,px,mx,hx,gx,kx,yx,qx,Kx,jx,Bx,wx,bx,vx,xx,Sx,Ax,Ex,Tx,$x,Rx,Ix,Ox,Px,_x,Nx,Cx,Dx,Fx,Lx,Mx];var Yx=class extends kd{static{s(this,"PlatformTenantsCommand")}static paths=[["platform","tenants"]];async execute(){return an(this.context.stderr,"platform tenants","tenants"),await super.execute()}},Hx=class extends D{static{s(this,"PlatformTenantRenameCommand")}static paths=[["platform","tenant","rename"]];static usage=T.Usage({category:"Platform",description:"Change a tenant's slug and name in place (plan unless --confirm)",details:"The tenant id stays, so every row keyed by it follows. Upload tickets, payment return paths and dashboard notepads move with the slug in the same transaction. Refused while mail is queued, a Stripe checkout is open or contract generators exist. Old URLs do not redirect; links in mail already sent break. Re-export the config afterwards \u2014 an older export would create a new tenant. Recipe: playbooks/platform/rename-tenant.md.",examples:[["Plan it",'plexus-cli --env prod --tenant alte-schule platform tenant rename --to neue-schule --name "Neue Schule"'],["Apply it",'plexus-cli --env prod --tenant alte-schule platform tenant rename --to neue-schule --name "Neue Schule" --confirm --allow-prod']]});to=p.String("--to",{required:!0,description:"The new slug (the first URL segment)."});name=p.String("--name",{required:!0,description:"The new display name."});confirm=p.Boolean("--confirm",!1,{description:"Write the change (without it, only the plan is printed)."});async execute(){if(this.tenant===void 0)throw new Error("plexus: platform tenant rename needs an explicit --tenant <current slug> (the configured default is not used).");let t=await(await this.caller()).mutation(x.platformAdmin.renameTenant,{tenantSlug:this.tenant,newSlug:this.to,name:this.name,dryRun:!this.confirm});return this.json?(this.print(t),0):(this.context.stdout.write(`${X3(t)}
10869
+ `);return this.print({stamped:t,open:i.map(o=>o.message)},o=>[...o.stamped.map(a=>({node:a.target.slice(6),stamp:a.detail})),{node:"open",stamp:o.open.length===0?"\u2014":`${o.open.length} finding(s) on the stamped nodes \u2014 bind with node set-input`}]),0}},hK=[fx,px,mx,hx,gx,kx,yx,qx,Kx,jx,Bx,wx,bx,vx,xx,Sx,Ax,Ex,Tx,$x,Rx,Ix,Ox,Px,_x,Nx,Cx,Dx,Fx,Lx,Mx];var Yx=class extends kd{static{s(this,"PlatformTenantsCommand")}static paths=[["platform","tenants"]];async execute(){return an(this.context.stderr,"platform tenants","tenants"),await super.execute()}},Hx=class extends D{static{s(this,"PlatformTenantRenameCommand")}static paths=[["platform","tenant","rename"]];static usage=T.Usage({category:"Platform",description:"Change a tenant's slug and name in place (plan unless --confirm)",details:"The tenant id stays, so every row keyed by it follows. Upload tickets, payment return paths and dashboard notepads move with the slug in the same transaction. Refused while mail is queued, a Stripe checkout is open or contract generators exist. Old URLs do not redirect; links in mail already sent break. Re-export the config afterwards \u2014 an older export would create a new tenant. Recipe: playbooks/platform/rename-tenant.md.",examples:[["Plan it",'plexus-cli --env prod --tenant alte-schule platform tenant rename --to neue-schule --name "Neue Schule"'],["Apply it",'plexus-cli --env prod --tenant alte-schule platform tenant rename --to neue-schule --name "Neue Schule" --confirm --allow-prod']]});to=p.String("--to",{required:!0,description:"The new slug (the first URL segment)."});name=p.String("--name",{required:!0,description:"The new display name."});confirm=p.Boolean("--confirm",!1,{description:"Write the change (without it, only the plan is printed)."});async execute(){if(this.tenant===void 0)throw new Error("plexus: platform tenant rename needs an explicit --tenant <current slug> (the configured default is not used).");let t=await(await this.caller()).mutation(x.platformAdmin.renameTenant,{tenantSlug:this.tenant,newSlug:this.to,name:this.name,dryRun:!this.confirm});return this.json?(this.print(t),0):(this.context.stdout.write(`${X5(t)}
10865
10870
  `),t.changed&&!t.applied&&this.context.stdout.write(`Dry run \u2014 re-run with --confirm to write.
10866
- `),0)}};function X3(e){return e.changed?[`${e.applied?"Renamed":"Would rename"} tenant ${e.tenantId}: ${e.from.slug} \u201E${e.from.name}\u201C \u2192 ${e.to.slug} \u201E${e.to.name}\u201C`,` tenants ${e.moved.tenants}`,` stripe_payments.returnPath ${e.moved.payments}`,` dashboard notepads ${e.moved.notepads}`].join(`
10867
- `):`${e.from.slug} \u201E${e.from.name}\u201C is unchanged.`}s(X3,"renamePlanText");var Jx=class extends D{static{s(this,"PlatformWorkersCommand")}static paths=[["platform","workers","list"],["platform","workers"]];static usage=T.Usage({category:"Platform",description:"List live job workers (platform-admin)"});async execute(){let t=await(await this.caller()).query(x.workers.listFleet,{});return this.print(t,r=>r.map(i=>{let o=i.currentJob?i.currentJob.status?`${i.currentJob.kind}:${i.currentJob.status}`:i.currentJob.kind:"";return{workerId:i.workerId,lifecycle:i.lifecycle,status:i.status,kinds:i.kinds.join(","),host:i.hostname??"",job:o}}),["workerId","lifecycle","status","kinds","host","job"]),0}},Qx=class extends D{static{s(this,"AuditAccessCommand")}static paths=[["audit","access"]];static usage=T.Usage({category:"Platform",description:"Read the privileged-access log (platform-admin)",details:"Pass --application to report accesses to ONE application (date + purpose; add --with-actor to also name the employee), or --actor to report what one employee accessed in the active tenant. Reading this log is itself logged."});application=p.String("--application",{description:"Application id to report accesses for"});actor=p.String("--actor",{description:"Employee email to report accesses BY (tenant-scoped)"});withActor=p.Boolean("--with-actor",!1,{description:"Include the employee identity (needs _platform.audit.readActor)"});async execute(){let n=await this.caller();if(this.application===void 0==(this.actor===void 0))throw new Error("plexus audit access: pass exactly one of --application <id> or --actor <email>.");if(this.actor!==void 0){let i=await n.mutation(x.audit.listActorAccess,{client:this.requireTenant(n),actorEmail:this.actor});return this.printAccessRows(i.rows,i.truncated,!0),0}let t=this.application;if(this.withActor){let i=await n.mutation(x.audit.listApplicationAccessWithActor,{applicationId:t});return this.printAccessRows(i.rows,i.truncated,!0),0}let r=await n.mutation(x.audit.listApplicationAccess,{applicationId:t});return this.printAccessRows(r.rows,r.truncated,!1),0}printAccessRows(n,t,r){this.print({rows:n,truncated:t},i=>i.rows.map(o=>({at:new Date(o.at).toISOString(),purpose:o.purpose,...r?{actor:o.actorEmail??""}:{}})),r?["at","actor","purpose"]:["at","purpose"]),t&&!this.json&&this.context.stderr.write(`warning: the report was truncated \u2014 older rows are not shown.
10871
+ `),0)}};function X5(e){return e.changed?[`${e.applied?"Renamed":"Would rename"} tenant ${e.tenantId}: ${e.from.slug} \u201E${e.from.name}\u201C \u2192 ${e.to.slug} \u201E${e.to.name}\u201C`,` tenants ${e.moved.tenants}`,` stripe_payments.returnPath ${e.moved.payments}`,` dashboard notepads ${e.moved.notepads}`].join(`
10872
+ `):`${e.from.slug} \u201E${e.from.name}\u201C is unchanged.`}s(X5,"renamePlanText");var Jx=class extends D{static{s(this,"PlatformWorkersCommand")}static paths=[["platform","workers","list"],["platform","workers"]];static usage=T.Usage({category:"Platform",description:"List live job workers (platform-admin)"});async execute(){let t=await(await this.caller()).query(x.workers.listFleet,{});return this.print(t,r=>r.map(i=>{let o=i.currentJob?i.currentJob.status?`${i.currentJob.kind}:${i.currentJob.status}`:i.currentJob.kind:"";return{workerId:i.workerId,lifecycle:i.lifecycle,status:i.status,kinds:i.kinds.join(","),host:i.hostname??"",job:o}}),["workerId","lifecycle","status","kinds","host","job"]),0}},Qx=class extends D{static{s(this,"AuditAccessCommand")}static paths=[["audit","access"]];static usage=T.Usage({category:"Platform",description:"Read the privileged-access log (platform-admin)",details:"Pass --application to report accesses to ONE application (date + purpose; add --with-actor to also name the employee), or --actor to report what one employee accessed in the active tenant. Reading this log is itself logged."});application=p.String("--application",{description:"Application id to report accesses for"});actor=p.String("--actor",{description:"Employee email to report accesses BY (tenant-scoped)"});withActor=p.Boolean("--with-actor",!1,{description:"Include the employee identity (needs _platform.audit.readActor)"});async execute(){let n=await this.caller();if(this.application===void 0==(this.actor===void 0))throw new Error("plexus audit access: pass exactly one of --application <id> or --actor <email>.");if(this.actor!==void 0){let i=await n.mutation(x.audit.listActorAccess,{client:this.requireTenant(n),actorEmail:this.actor});return this.printAccessRows(i.rows,i.truncated,!0),0}let t=this.application;if(this.withActor){let i=await n.mutation(x.audit.listApplicationAccessWithActor,{applicationId:t});return this.printAccessRows(i.rows,i.truncated,!0),0}let r=await n.mutation(x.audit.listApplicationAccess,{applicationId:t});return this.printAccessRows(r.rows,r.truncated,!1),0}printAccessRows(n,t,r){this.print({rows:n,truncated:t},i=>i.rows.map(o=>({at:new Date(o.at).toISOString(),purpose:o.purpose,...r?{actor:o.actorEmail??""}:{}})),r?["at","actor","purpose"]:["at","purpose"]),t&&!this.json&&this.context.stderr.write(`warning: the report was truncated \u2014 older rows are not shown.
10868
10873
  `)}},eQ=200,gK=2e3,Zx=class extends D{static{s(this,"AccountsEmailChangesCommand")}static paths=[["accounts","email-changes"]];static usage=T.Usage({category:"Users",description:"Read the login-address change log (who changed whose login address)",details:"Without --user: the changes this tenant's staff made (needs administration.users.manage). With --user <email>: every change naming that address \u2014 current, previous or new \u2014 across all tenants, including the platform operator's (platform-admin). Read-only."});user=p.String("--user",{description:"An address the account holds or held (data-subject request)"});async execute(){let n=await this.caller(),t=this.user!==void 0?await n.query(x.accountEmailChangeLog.listForAddress,{email:this.user}):await this.tenantRows(n);return this.print(t,r=>r.map(i=>({at:new Date(i.at).toISOString(),account:i.account.kind==="deleted"?"(gel\xF6scht)":i.account.kind==="outsideTenant"?"(kein Zugang mehr)":i.account.email,from:i.previousEmail,to:i.newEmail,by:(i.actorKind==="staff"?"Schule":"Plattformbetrieb")+(i.actorEmail===null?"":`: ${i.actorEmail}`),oldProven:i.previousWasProven?"ja":"nein",firstSession:i.firstSessionAt===null?"\u2014":new Date(i.firstSessionAt).toISOString(),redacted:i.addressesRedacted?"ja":""})),["at","account","from","to","by","oldProven","firstSession","redacted"]),0}async tenantRows(n){let t=this.requireTenant(n),r=[],i=null;for(;;){let o=await n.query(x.accountEmailChangeLog.listForTenant,{client:t,paginationOpts:{numItems:eQ,cursor:i}});if(r.push(...o.page),o.isDone)return r;if(r.length>=gK)throw new Error(`plexus accounts email-changes: more than ${gK} rows \u2014 narrow it with --user <email>.`);i=o.continueCursor}}},yK=[Hx,Yx,Jx,Qx,Zx];var Xe=class extends D{static{s(this,"GeneratorCommand")}async loadContext(){let n=await this.caller();return{caller:n,client:this.requireTenant(n)}}},Xx=class extends Xe{static{s(this,"ResolverListCommand")}static paths=[["generator","list"]];static usage=T.Usage({category:"Contracts",description:"List generator identities and their revisions."});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.query(x.contractGeneratorRevisions.model,{client:t})),0}},eS=class extends Xe{static{s(this,"ResolverShowCommand")}static paths=[["generator","show"]];id=p.String({required:!0,name:"revision-id"});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.query(x.contractGeneratorRevisions.detail,{client:t,id:this.id})),0}},nS=class extends Xe{static{s(this,"ResolverCreateCommand")}static paths=[["generator","create"]];key=p.String("--key",{required:!0});name=p.String("--name",{required:!0});nameEn=p.String("--name-en",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.mutation(x.contractGeneratorRevisions.create,{client:t,key:this.key,name:{de:this.name,en:this.nameEn},description:{de:"",en:""}})),0}},tS=class extends Xe{static{s(this,"ResolverCloneCommand")}static paths=[["generator","clone"]];id=p.String({required:!0,name:"source-revision-id"});definition=p.String("--definition-id",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.mutation(x.contractGeneratorRevisions.cloneDraft,{client:t,id:this.id,targetDefinitionId:this.definition})),0}},rS=class extends Xe{static{s(this,"ResolverSealCommand")}static paths=[["generator","seal"]];id=p.String({required:!0,name:"revision-id"});sourceRevision=p.String("--source-revision",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.mutation(x.contractGeneratorRevisions.seal,{client:t,id:this.id,expectedSourceRevision:Number(this.sourceRevision)})),0}},iS=class extends Xe{static{s(this,"ResolverDeleteDraftCommand")}static paths=[["generator","delete-draft"]];id=p.String({required:!0,name:"revision-id"});sourceRevision=p.String("--source-revision",{required:!0});confirm=p.Boolean("--confirm",!1,{description:"Discard (without it, only the plan is printed)."});async execute(){let{caller:n,client:t}=await this.loadContext();if(!this.confirm){let r=await n.query(x.contractGeneratorRevisions.detail,{client:t,id:this.id});return this.print({id:this.id,status:r.status,deleted:!1}),this.context.stderr.write(`Would discard generator draft ${this.id} \u2014 re-run with --confirm.
10869
10874
  `),0}return this.print(await n.mutation(x.contractGeneratorRevisions.discardDraft,{client:t,id:this.id,expectedSourceRevision:Number(this.sourceRevision)})),0}},oS=class extends Xe{static{s(this,"ResolverArchiveCommand")}static paths=[["generator","archive"]];id=p.String({required:!0,name:"definition-id"});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.mutation(x.contractGeneratorRevisions.archive,{client:t,id:this.id})),0}},sS=class extends Xe{static{s(this,"ResolverUpdateCommand")}static paths=[["generator","save"]];id=p.String({required:!0,name:"revision-id"});file=p.String("--file",{required:!0});sourceRevision=p.String("--source-revision",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext(),r=JSON.parse(await Ut(this.file,"utf8"));return this.print(await n.mutation(x.contractGeneratorRevisions.save,{client:t,id:this.id,expectedSourceRevision:Number(this.sourceRevision),...r})),0}},aS=class extends Xe{static{s(this,"GeneratorSourceExportCommand")}static paths=[["generator","source","export"]];id=p.String({required:!0,name:"revision-id"});out=p.String("--out",{required:!0});force=An();async execute(){let n=Wn(this.out,this.force),{caller:t,client:r}=await this.loadContext(),i=await t.query(x.contractGeneratorRevisions.detail,{client:r,id:this.id});return await iu(n,i.source),this.print({file:n,sourceRevision:i.sourceRevision}),0}},lS=class extends Xe{static{s(this,"GeneratorSourceSaveCommand")}static paths=[["generator","source","save"]];id=p.String({required:!0,name:"revision-id"});file=p.String("--file",{required:!0});manifest=p.String("--manifest",{required:!0});sourceRevision=p.String("--source-revision",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext(),r=JSON.parse(await Ut(this.manifest,"utf8")),i=await n.action(x.contractGeneratorRevisionActions.saveSource,{client:t,id:this.id,expectedSourceRevision:Number(this.sourceRevision),source:await Ut(this.file,"utf8"),...r});return this.print(i),i.diagnostics.length===0?0:1}},dS=class extends Xe{static{s(this,"GeneratorScenarioTestCommand")}static paths=[["generator","scenarios","test"]];id=p.String({required:!0,name:"revision-id"});input=p.String("--input",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await n.query(x.contractGeneratorRevisions.resolve,{client:t,id:this.id,input:JSON.parse(await Ut(this.input,"utf8"))})),0}},cS=class extends Xe{static{s(this,"GeneratorScenarioApproveCommand")}static paths=[["generator","scenarios","approve"]];id=p.String({required:!0,name:"revision-id"});file=p.String("--file",{required:!0});sourceRevision=p.String("--source-revision",{required:!0});artifactHash=p.String("--artifact-hash",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext(),r=JSON.parse(await Ut(this.file,"utf8"));return this.print(await n.mutation(x.contractGeneratorRevisions.approveScenarios,{client:t,id:this.id,expectedSourceRevision:Number(this.sourceRevision),artifactHash:this.artifactHash,scenarios:r})),0}},uS=class extends Xe{static{s(this,"ResolverSetupPlanCommand")}static paths=[["generator","setup","plan"]];file=p.String("--file",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print((await Nd(n,t,Nm(this.file))).rows),0}},fS=class extends Xe{static{s(this,"ResolverSetupApplyCommand")}static paths=[["generator","setup","apply"]];file=p.String("--file",{required:!0});async execute(){let{caller:n,client:t}=await this.loadContext();return this.print(await Z0(n,t,Nm(this.file))),0}},pS=class extends Xe{static{s(this,"GeneratorScopeCommand")}static paths=[["generator","scope"]];static usage=T.Usage({category:"Contracts",description:"Set a template's unit and declared Tr\xE4ger (by config keys).",examples:[["A Hortvertrag of the Grundschule, concluded with a Tr\xE4ger of its own","$0 --tenant test generator scope --key hortvertrag-musterbunt --unit test_grundschule --traeger test_seminare"]]});key=p.String("--key",{required:!0,description:"The generator's key."});unit=p.String("--unit",{description:"The unit's config key (units.configKey)."});noUnit=p.Boolean("--no-unit",!1,{description:"The template belongs to the whole tenant."});traeger=p.String("--traeger",{description:"The Tr\xE4ger's config key (legal_entities.configKey)."});noTraeger=p.Boolean("--no-traeger",!1,{description:"The template declares no Tr\xE4ger."});async execute(){if(this.unit!==void 0&&this.noUnit)throw new Error("--unit and --no-unit exclude each other.");if(this.traeger!==void 0&&this.noTraeger)throw new Error("--traeger and --no-traeger exclude each other.");let n=this.noUnit?null:this.unit,t=this.noTraeger?null:this.traeger;if(n===void 0&&t===void 0)throw new Error("Name --unit/--no-unit or --traeger/--no-traeger.");let{caller:r,client:i}=await this.loadContext();return this.print(await r.mutation(x.contractGeneratorRevisions.setTemplateScope,{client:i,key:this.key,...n===void 0?{}:{unitKey:n},...t===void 0?{}:{traegerKey:t}})),0}},wK=[pS,Xx,eS,nS,tS,rS,iS,oS,sS,aS,lS,dS,cS,uS,fS];var Ta=["party","legalEntity","learningGroup"];var $a=["string","number","boolean","date","enum","address","pricedItem","pricedGroup"];function kK(e){return/^[a-z][a-zA-Z0-9]*$/.test(e)?null:{de:"Eingabeschl\xFCssel m\xFCssen camelCase verwenden.",en:"Input keys must use camelCase."}}s(kK,"inputKeyNameIssue");function mS(e,n){let t=s(r=>Array.isArray(r)?r.map(t):r!==null&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,"sorted");return JSON.stringify(t(e))===JSON.stringify(t(n))}s(mS,"sameJson");function bK(e,n){return[mS(e.label,n.label)?null:"label",mS(e.description,n.description)?null:"description",mS(e.value,n.value)?null:"value"].filter(t=>t!==null)}s(bK,"inputKeyDifferences");var ht="generator input-key";function Jm(e,n){if(e===void 0==(n===void 0))throw new Error(`${ht}: name exactly one of --scalar <${$a.join("|")}> or --entity <${Ta.join("|")}>`);if(e!==void 0){if(!$a.includes(e))throw new Error(`${ht}: --scalar "${e}" is none of ${$a.join(", ")}`);return{valueKind:"scalar",scalarType:e}}if(!Ta.includes(n))throw new Error(`${ht}: --entity "${n}" is none of ${Ta.join(", ")}`);return{valueKind:"entity",entityKind:n}}s(Jm,"inputKeyValue");function nQ(e,n){let t=_n(e,n,ht);if(t.valueKind==="scalar"){if(Object.keys(t).some(r=>r!=="valueKind"&&r!=="scalarType"))throw new Error(`${ht}: ${n} carries keys besides valueKind and scalarType.`);return Jm(String(t.scalarType),void 0)}if(t.valueKind==="entity"){if(Object.keys(t).some(r=>r!=="valueKind"&&r!=="entityKind"))throw new Error(`${ht}: ${n} carries keys besides valueKind and entityKind.`);return Jm(void 0,String(t.entityKind))}throw new Error(`${ht}: ${n}.valueKind must be "scalar" or "entity" (got ${JSON.stringify(t.valueKind)}).`)}s(nQ,"parseValue");function gS(e){if(!Array.isArray(e))throw new Error(`${ht}: the file must be a JSON array of { key, label, description, value }.`);let n=new Set;return e.map((t,r)=>{let i=_n(t,`[${r}]`,ht),o=typeof i.key=="string"?i.key:"",a=kK(o);if(a!==null)throw new Error(`${ht}: [${r}].key ${JSON.stringify(i.key)}: ${a.en}`);if(n.has(o))throw new Error(`${ht}: key "${o}" appears twice in the file.`);n.add(o);let l=Object.keys(i).filter(d=>!["key","label","description","value"].includes(d));if(l.length>0)throw new Error(`${ht}: [${r}] (${o}) carries unknown keys: ${l.join(", ")}.`);return{key:o,label:ut(i.label,`${o}.label`,ht,"labels"),description:ut(i.description,`${o}.description`,ht,"descriptions"),value:nQ(i.value,`${o}.value`)}})}s(gS,"parseInputKeyFile");function vK(e){return e.valueKind==="entity"?{valueKind:"entity",entityKind:e.entityKind}:{valueKind:"scalar",scalarType:e.scalarType}}s(vK,"registeredValue");var hS=s(e=>e.valueKind==="entity"?`entity:${e.entityKind}`:e.scalarType,"describeValue");function yS(e,n){let t=new Map(n.map(r=>[r.key,r]));return e.map(r=>{let i=t.get(r.key);if(i===void 0)return{key:r.key,action:"create",detail:hS(r.value)};if(i.deprecatedAt!==void 0)return{key:r.key,action:"deprecated",detail:"registered but deprecated \u2014 choose a new key"};let o=bK({label:i.label,description:i.description,value:vK(i)},{label:r.label,description:r.description,value:r.value}).map(a=>a==="value"?`value (${hS(vK(i))} registered)`:a);return o.length===0?{key:r.key,action:"same",detail:hS(r.value)}:{key:r.key,action:"differs",detail:`registered with another ${o.join(", ")} \u2014 entries are immutable`}})}s(yS,"planInputKeys");function wS(e){return e.action==="differs"||e.action==="deprecated"}s(wS,"isConflict");function xK(e,n){let t=e.find(r=>r.key===n);if(t===void 0)throw new Error(`${ht}: "${n}" is not registered.`);return t}s(xK,"registeredKey");var rn="generator package";function Yc(e,n){return _n(e,n,rn)}s(Yc,"plainObject");function tQ(e,n,t){let r=Yc(e,"Datei"),i=Object.keys(r).filter(f=>!["key","name","description","inputSchema","parts","source","scenarios"].includes(f));if(i.length>0)throw new Error(`${rn}: unknown keys in the file: ${i.join(", ")}.`);let o=Ge(r.key,"key",rn),a=new Set,l=Ct(r.parts,"parts",rn).map((f,m)=>{let y=Yc(f,`parts[${m}]`),k=Ge(y.partKey,`parts[${m}].partKey`,rn);if(a.has(k))throw new Error(`${rn}: part "${k}" appears twice.`);if(a.add(k),typeof y.position!="number"||!Number.isInteger(y.position))throw new Error(`${rn}: parts[${m}].position must be an integer.`);if(typeof y.optional!="boolean")throw new Error(`${rn}: parts[${m}].optional must be true or false.`);return{partKey:k,generator:Ge(y.generator,`parts[${m}].generator`,rn),position:y.position,optional:y.optional,defaults:Yc(y.defaults,`parts[${m}].defaults`),fixedValues:Yc(y.fixedValues,`parts[${m}].fixedValues`)}});if(!("source"in r))throw new Error(`${rn}: "source" is missing \u2014 the package code's file, or null for none.`);let d=r.source===null?null:t(rQ(r.source)),c=new Set,u=Ct(r.scenarios,"scenarios",rn).map((f,m)=>{let y=Yc(f,`scenarios[${m}]`),k=Ge(y.key,`scenarios[${m}].key`,rn);if(c.has(k))throw new Error(`${rn}: scenario "${k}" appears twice.`);if(c.add(k),!("input"in y))throw new Error(`${rn}: scenario "${k}" has no input.`);return{key:k,input:y.input,...y.expected===void 0?{}:{expected:y.expected}}});if(u.length===0)throw new Error(`${rn}: a package needs at least one scenario before it can be sealed.`);if(!("inputSchema"in r))throw new Error(`${rn}: "inputSchema" is missing.`);return{file:n,raw:r,key:o,name:ut(r.name,"name",rn,"Paketnamen"),description:ut(r.description,"description",rn,"Beschreibungen"),inputSchema:r.inputSchema,parts:l,source:d,scenarios:u}}s(tQ,"parsePackageSetup");function rQ(e){let n=Ge(e,"source",rn);if(/\n/.test(n)||!n.endsWith(".ts"))throw new Error(`${rn}: "source" is the package code's .ts file, relative to the package file (or null) \u2014 inline code is not read; move it into e.g. package.ts and write "source": "package.ts".`);return n}s(rQ,"sourcePath");function kS(e){let n=z.resolve(e);return tQ(JSON.parse(ye(n,"utf8")),n,t=>ye(z.join(z.dirname(n),t),"utf8"))}s(kS,"readPackageSetup");function iQ(e,n){let t=new Map(n.map(r=>[r.definition.key,r]));return e.map(({generator:r,...i})=>{let o=t.get(r);if(o===void 0)throw new Error(`${rn}: part "${i.partKey}": no generator "${r}" on this environment (generator list).`);if(o.currentRevisionId===null)throw new Error(`${rn}: part "${i.partKey}": generator "${r}" has no sealed revision here \u2014 seal it first.`);return{...i,generatorDefinitionId:o.definition.id}})}s(iQ,"resolveParts");var SK=s(e=>Pe([...e].map(({partKey:n,generatorDefinitionId:t,position:r,optional:i,defaults:o,fixedValues:a})=>({partKey:n,generatorDefinitionId:t,position:r,optional:i,defaults:o,fixedValues:a})).sort((n,t)=>n.partKey.localeCompare(t.partKey))),"comparableParts");function oQ(e,n,t){return e.revision.status==="sealed"&&(e.revision.source??null)===n.source&&Pe(e.revision.inputSchema)===Pe(n.inputSchema)&&Pe(e.revision.scenarios)===Pe(n.scenarios)&&SK(e.parts)===SK(t)}s(oQ,"revisionMatches");async function Qm(e,n,t){let r=await e.query(x.contractGeneratorRevisions.model,{client:n}),i=iQ(t.parts,r),a=(await e.query(x.contractPackages.model,{client:n})).find(k=>k.definition.key===t.key);if(a?.definition.archivedAt!==void 0)throw new Error(`${rn}: package "${t.key}" is archived \u2014 a new revision needs an active package (choose a new key).`);let l=t.scenarios.filter(k=>k.expected===void 0).map(k=>k.key),d=l.length>0?` \u2014 ${l.length} scenario(s) without expected: evaluated and written into the file, not sealed`:"";if(a===void 0)return{rows:[{step:"package",target:t.key,action:"create",detail:`New package, revision 1${d}`}],parts:i,head:a,action:"create",draftId:null,currentRevisionId:null,metadataChanged:!1};let c=Pe(a.definition.name)!==Pe(t.name)||Pe(a.definition.description)!==Pe(t.description),u=c?[{step:"metadata",target:t.key,action:"update",detail:"name or description"}]:[],f=a.revisions.find(k=>k.status==="draft")??null,m=a.currentRevisionId===null?null:await e.query(x.contractPackages.detail,{client:n,id:a.currentRevisionId}),y=m===null?"none":String(m.revision.revisionNumber);return f===null&&m!==null&&oQ(m,t,i)?(u.push({step:"revision",target:t.key,action:"same",detail:`Current sealed revision ${y}`}),{rows:u,parts:i,head:a,action:"same",draftId:null,currentRevisionId:a.currentRevisionId,metadataChanged:c}):(u.push({step:"revision",target:t.key,action:"revise",detail:`${f===null?`Copy of revision ${y}`:`Open draft ${f.revisionNumber}`} takes the file${d}`}),{rows:u,parts:i,head:a,action:"revise",draftId:f?._id??null,currentRevisionId:a.currentRevisionId,metadataChanged:c})}s(Qm,"planPackageSetup");async function AK(e,n,t){let r=await Qm(e,n,t);if(r.metadataChanged&&await e.mutation(x.contractPackages.updateMetadata,{client:n,id:r.head.definition._id,name:t.name,description:t.description}),r.action==="same")return{rows:r.rows,revisionId:r.currentRevisionId,sealed:!0,reviewWritten:[]};let i;if(r.action==="create")i=(await e.mutation(x.contractPackages.create,{client:n,key:t.key,name:t.name,description:t.description})).revisionId;else if(r.draftId!==null)i=r.draftId;else{if(r.currentRevisionId===null)throw new Error(`${rn}: package "${t.key}" has neither a draft nor a sealed revision.`);i=await e.mutation(x.contractPackages.cloneDraft,{client:n,id:r.currentRevisionId})}let o=t.scenarios.every(f=>f.expected!==void 0),a=s(async(f,m)=>await e.mutation(x.contractPackages.save,{client:n,id:i,expectedSourceRevision:f,inputSchema:t.inputSchema,scenarios:m,parts:r.parts.map(y=>({...y,generatorDefinitionId:y.generatorDefinitionId}))}),"save"),l=await e.query(x.contractPackages.detail,{client:n,id:i}),d=await a(l.revision.sourceRevision,o?t.scenarios:[]),c=await e.action(x.contractPackageActions.saveSource,{client:n,id:i,expectedSourceRevision:d,source:t.source});if(c.sourceRevision===null)throw new Error(`${rn}: the package code does not compile:
10870
10875
  ${c.diagnostics.join(`
@@ -10984,6 +10989,6 @@ ${t.length} unusable ${o}:
10984
10989
  `),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli platform users relink-auth <email>
10985
10990
  `),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>
10986
10991
  `)}else this.context.stdout.write(`No unusable identities.
10987
- `);return t.length>0?1:0}},EE=class extends lr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.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 Rj(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(Rj,"requireOnOff");var Ij=[lE,dE,cE,uE,fE,pE,mE,hE,gE,yE,Zc,wE,kE,bE,vE,xE,SE,AE,EE];function Oj(e){return e.de??e.en??Object.values(e)[0]??""}s(Oj,"titleDe");function w8(e){return{id:e._id,kind:e.kind,status:e.status,title:Oj(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(w8,"row");var k8=["id","kind","status","title","assignee","group","outcome"],RE=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.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(w8),k8),0}},IE=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.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:Oj(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}},OE=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.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}},PE=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.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}},_E=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.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}},Pj=[RE,IE,OE,PE,_E];var Xc=[...fR,...xN,...NN,...CC,...NC,...sD,...pD,...fD,...Tj,...Ij,...Ej,...yK,...sN,...tD,...mj,...cR,...FR,...G_,...gD,...hD,...kD,...bD,...eD,...KC,...Pj,...hM,...eq,...hK,...nq,...QK,...oj,...wK,...$K,...OK,...CK,...FK,...lj,...wj,...RR];for(let e of Xc){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:NT(e.usage.category,n.join(" "))})}var _j="0.1.105";function Nj(){return Xc.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=IT[so(t)];return{path:t,effect:ao(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(Nj,"plexusCommandCatalog");import Zo from"node:path";function b8(e){let n=ln()?.workspaceRoot??process.cwd(),t=Zo.resolve(n,e),r=Zo.relative(n,t);if(Zo.isAbsolute(e)||r===".."||r.startsWith(`..${Zo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(b8,"workspacePath");function v8(e){let{absolute:n,relative:t}=b8(e.path??".");if(e.operation==="list"){if(!Se(n))return{files:[]};let r=[],i=s(o=>{for(let a of $r(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Zo.join(o,a.name);if(a.isDirectory()?i(l):r.push(Zo.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=ye(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 We(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 Cn(Zo.dirname(n),{recursive:!0}),We(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return ts(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(v8,"plexusWorkspace");function Cj(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=il[t];if(!o||!Object.hasOwn(il,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(_g,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:_g[i.path],skillHash:Wu}}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 v8(i)},"executePlexusAgentTool")}s(Cj,"createPlexusAgentToolExecutor");var yh=Cj({inspectCommand:Fj,executeCommand:Lj});function wh(){let e=new ss({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:_j});e.register(ja.HelpCommand),e.register(ja.VersionCommand);for(let t of Xc)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 A8(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(wh,"createPlexusCli");function A8(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&za[t]===r&&an(n,t,r),t in za&&ao(t)==="confirm"&&!Wa(e)&&n.write(`plexus-cli: \`${za[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
10992
+ `);return t.length>0?1:0}},EE=class extends lr{static{s(this,"UsersRelinkAuthCommand")}static paths=[["platform","users","relink-auth"],["users","relink-auth"]];static usage=T.Usage({category:"Users",description:"Relink a user's identity row to its live Better Auth account (heals an orphan)."});email=p.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 Rj(e,n){if(e===n)throw new Error("Pass exactly one of --on or --off.");return e}s(Rj,"requireOnOff");var Ij=[lE,dE,cE,uE,fE,pE,mE,hE,gE,yE,Zc,wE,kE,bE,vE,xE,SE,AE,EE];function Oj(e){return e.de??e.en??Object.values(e)[0]??""}s(Oj,"titleDe");function w8(e){return{id:e._id,kind:e.kind,status:e.status,title:Oj(e.title).slice(0,50),assignee:e.assigneeUserId??"",group:e.queueGroupId??"",outcome:e.outcome??""}}s(w8,"row");var k8=["id","kind","status","title","assignee","group","outcome"],RE=class extends D{static{s(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=T.Usage({category:"Work-Items",description:"List work-items for the active tenant (filter by --mine/--application/--group)."});mine=p.Boolean("--mine",!1,{description:"Only items assigned to me."});application=p.String("--application",{description:"Filter by application id."});group=p.String("--group",{description:"Filter by team (permission-group) id."});assignee=p.String("--assignee",{description:"Filter by assignee users._id."});openOnly=p.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(w8),k8),0}},IE=class extends D{static{s(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=T.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.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:Oj(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}},OE=class extends D{static{s(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=T.Usage({category:"Work-Items",description:"Create a manual task work-item."});title=p.String("--title",{required:!0,description:"Task title."});description=p.String("--description",{description:"Task description."});application=p.String("--application",{description:"Link to an application id."});group=p.String("--group",{description:"Team (permission-group) id whose queue holds the task."});assignee=p.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}},PE=class extends D{static{s(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=T.Usage({category:"Work-Items",description:"Complete a work-item (optionally with an outcome)."});workItemId=p.String({required:!0,name:"workItemId"});outcome=p.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}},_E=class extends D{static{s(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=T.Usage({category:"Work-Items",description:"Assign a work-item to a user (omit --user to unassign)."});workItemId=p.String({required:!0,name:"workItemId"});user=p.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}},Pj=[RE,IE,OE,PE,_E];var Xc=[...fR,...xN,...NN,...CC,...NC,...sD,...pD,...fD,...Tj,...Ij,...Ej,...yK,...sN,...tD,...mj,...cR,...FR,...G_,...gD,...hD,...kD,...bD,...eD,...KC,...Pj,...hM,...eq,...hK,...nq,...QK,...oj,...wK,...$K,...OK,...CK,...FK,...lj,...wj,...RR];for(let e of Xc){let n=e.paths?.[0];n===void 0||!Object.hasOwn(e,"usage")||e.usage===void 0||(e.usage={...e.usage,category:NT(e.usage.category,n.join(" "))})}var _j="0.1.106";function Nj(){return Xc.flatMap(e=>(e.paths??[]).map(n=>{let t=n.join(" "),r=IT[so(t)];return{path:t,effect:ao(t),host:r===void 0?"shared":"terminal",...r===void 0?{}:{reason:r}}})).sort((e,n)=>e.path.localeCompare(n.path))}s(Nj,"plexusCommandCatalog");import Zo from"node:path";function b8(e){let n=ln()?.workspaceRoot??process.cwd(),t=Zo.resolve(n,e),r=Zo.relative(n,t);if(Zo.isAbsolute(e)||r===".."||r.startsWith(`..${Zo.sep}`))throw new Error("plexus: use a relative path inside the current workspace.");return{absolute:t,relative:r}}s(b8,"workspacePath");function v8(e){let{absolute:n,relative:t}=b8(e.path??".");if(e.operation==="list"){if(!Se(n))return{files:[]};let r=[],i=s(o=>{for(let a of $r(o,{withFileTypes:!0})){if(a.isSymbolicLink())throw new Error("plexus: workspace symlinks are not supported.");let l=Zo.join(o,a.name);if(a.isDirectory()?i(l):r.push(Zo.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=ye(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 We(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 Cn(Zo.dirname(n),{recursive:!0}),We(n,e.content,"utf8"),{path:t,sizeBytes:Buffer.byteLength(e.content)}}if(e.operation==="remove")return ts(n),{path:t,removed:!0};throw new Error("plexus: unknown workspace operation.")}s(v8,"plexusWorkspace");function Cj(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=il[t];if(!o||!Object.hasOwn(il,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(_g,i.path))throw new Error("plexus: unknown skill reference. Start with SKILL.md.");return{path:i.path,content:_g[i.path],skillHash:Wu}}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 v8(i)},"executePlexusAgentTool")}s(Cj,"createPlexusAgentToolExecutor");var yh=Cj({inspectCommand:Fj,executeCommand:Lj});function wh(){let e=new ss({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:_j});e.register(ja.HelpCommand),e.register(ja.VersionCommand);for(let t of Xc)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 A8(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(wh,"createPlexusCli");function A8(e,n){let t=e.path.join(" "),r=e.constructor.paths?.[0]?.join(" ");r!==void 0&&t!==r&&za[t]===r&&an(n,t,r),t in za&&ao(t)==="confirm"&&!Wa(e)&&n.write(`plexus-cli: \`${za[t]}\` only prints its plan without --confirm \u2014 nothing was changed.
10988
10993
  `)}s(A8,"noteRetiredPath");function Fj(e){let n=wh().process(_a(e),{executePlexusAgentTool:yh}),t=n.path.join(" ");if(t.startsWith("agent "))throw new Error("plexus: nested agent transports are not allowed.");let r=Nj().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"?Dp(da(ca),i.fn??"",i.kind):void 0,a=Cu(t,{confirm:Wa(n),callKind:o});return{...r,writes:a}}s(Fj,"inspectPlexusCommand");async function Lj(e,n){if(n)return DE(n,()=>Lj(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=wh();if(ln()){let l=Fj(e.argv);if(l.host==="terminal")throw new Error(`plexus: this command requires a local machine. ${l.reason??""}`)}return{exitCode:await i.run(_a(e.argv),{executePlexusAgentTool:yh,stdin:S8.from(e.stdin===void 0?[]:[e.stdin]),stdout:new Dj({write(l,d,c){t+=String(l),c()}}),stderr:new Dj({write(l,d,c){r+=String(l),c()}})}),stdout:t,stderr:r}}s(Lj,"executePlexusCommand");KE({source:E8.join(import.meta.dirname,"skill")});wh().runExit(_a(process.argv.slice(2)),{executePlexusAgentTool:yh});
10989
10994
  //# sourceMappingURL=cli.mjs.map