@smartkomm/plexus-cli 0.0.0-stage → 0.1.0
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/README.md +826 -2
- package/dist/cli.mjs +483 -0
- package/dist/skill/.managed-by-plexus-cli +1 -0
- package/dist/skill/SKILL.md +185 -0
- package/dist/skill/references/accounts/email-changes.md +46 -0
- package/dist/skill/references/applications/inspect-process-store.md +61 -0
- package/dist/skill/references/applications/start-a-test-application.md +66 -0
- package/dist/skill/references/audit/answer-access-request.md +115 -0
- package/dist/skill/references/config/attach-a-template.md +117 -0
- package/dist/skill/references/config/init-tenant.md +121 -0
- package/dist/skill/references/config/onboard-tenant.md +71 -0
- package/dist/skill/references/config/rename-program-stage.md +99 -0
- package/dist/skill/references/config/set-tenant-branding.md +150 -0
- package/dist/skill/references/config/set-tenant-terms.md +50 -0
- package/dist/skill/references/config/set-up-billing-catalog.md +73 -0
- package/dist/skill/references/config/update-tenant-config.md +170 -0
- package/dist/skill/references/config/wipe-tenant-config.md +107 -0
- package/dist/skill/references/export/create-named-export.md +47 -0
- package/dist/skill/references/feedback/create-and-triage-feedback.md +69 -0
- package/dist/skill/references/feedback/manage-feedback-tags.md +57 -0
- package/dist/skill/references/finance/change-contract-grant.md +36 -0
- package/dist/skill/references/finance/record-submission-date.md +33 -0
- package/dist/skill/references/interessenten/list-interessenten.md +54 -0
- package/dist/skill/references/notifications/debug-mail-delivery.md +77 -0
- package/dist/skill/references/notifications/mail-level.md +90 -0
- package/dist/skill/references/notifications/reword-a-letter.md +155 -0
- package/dist/skill/references/notifications/trace-a-login.md +50 -0
- package/dist/skill/references/offer/add-workflow-node.md +268 -0
- package/dist/skill/references/offer/addresses.md +129 -0
- package/dist/skill/references/offer/appointment-task.md +79 -0
- package/dist/skill/references/offer/assignment-rule.md +195 -0
- package/dist/skill/references/offer/attach-form-to-workflow.md +79 -0
- package/dist/skill/references/offer/author-form-scenarios.md +97 -0
- package/dist/skill/references/offer/author-manifest-meta.md +94 -0
- package/dist/skill/references/offer/author-smartform.md +102 -0
- package/dist/skill/references/offer/bind-node-input.md +76 -0
- package/dist/skill/references/offer/completeness-check.md +137 -0
- package/dist/skill/references/offer/countersign-node.md +91 -0
- package/dist/skill/references/offer/create-pedagogy-unit.md +55 -0
- package/dist/skill/references/offer/declare-node-reads.md +99 -0
- package/dist/skill/references/offer/edit-live-tenant-offer.md +144 -0
- package/dist/skill/references/offer/edit-smartform.md +121 -0
- package/dist/skill/references/offer/edit-workflow-node.md +126 -0
- package/dist/skill/references/offer/engage-push-node.md +147 -0
- package/dist/skill/references/offer/insert-and-rewire-node.md +67 -0
- package/dist/skill/references/offer/node-tasks.md +162 -0
- package/dist/skill/references/offer/optional-assessment.md +65 -0
- package/dist/skill/references/offer/publish-offer-bundle.md +117 -0
- package/dist/skill/references/offer/set-offer-capacities.md +78 -0
- package/dist/skill/references/offer/staff-input-if-node.md +112 -0
- package/dist/skill/references/offer/task-appointment-result.md +69 -0
- package/dist/skill/references/offer/task-family-request.md +69 -0
- package/dist/skill/references/offer/task-result-files.md +52 -0
- package/dist/skill/references/offer/template-document-node.md +113 -0
- package/dist/skill/references/offer/workflow-default-channels.md +69 -0
- package/dist/skill/references/resolver/manage-contract-resolver.md +159 -0
- package/dist/skill/references/retention/erase-due-applications.md +99 -0
- package/dist/skill/references/retention/erase-due-parties.md +107 -0
- package/dist/skill/references/roles/migrate-parent-assignments.md +31 -0
- package/dist/skill/references/signing/README.md +113 -0
- package/dist/skill/references/signing/connect-a-school.md +90 -0
- package/dist/skill/references/signing/rotate-the-key.md +41 -0
- package/dist/skill/references/stammdaten/purge-deleted-person.md +68 -0
- package/dist/skill/references/stripe/connect-a-school.md +107 -0
- package/dist/skill/references/stripe/request-and-verify-a-payment.md +78 -0
- package/dist/skill/references/test-actions/drive-a-test-application.md +59 -0
- package/dist/skill/references/users/add-platform-admin.md +59 -0
- package/dist/skill/references/users/add-platform-user.md +59 -0
- package/dist/skill/references/users/add-tenant-admin.md +75 -0
- package/dist/skill/references/users/change-login-email.md +55 -0
- package/dist/skill/references/users/cli-access-for-tenant-admin.md +117 -0
- package/dist/skill/references/users/delete-permission-group.md +76 -0
- package/dist/skill/references/users/grant-cross-tenant-access.md +57 -0
- package/dist/skill/references/users/grant-feedback-assignable.md +43 -0
- package/dist/skill/references/users/set-password.md +57 -0
- package/dist/skill/references/users/use-test-account.md +79 -0
- package/dist/skill/references/worker-ops/debug-worker-jobs.md +90 -0
- package/dist/skill/references/worker-ops/verify-migrations.md +51 -0
- package/dist/spec.snapshot.json +145815 -0
- package/package.json +53 -4
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
+
var NN=Object.create;var wd=Object.defineProperty;var DN=Object.getOwnPropertyDescriptor;var FN=Object.getOwnPropertyNames;var LN=Object.getPrototypeOf,MN=Object.prototype.hasOwnProperty;var o=(t,e)=>wd(t,"name",{value:e,configurable:!0}),qN=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var BN=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),lv=(t,e)=>{for(var n in e)wd(t,n,{get:e[n],enumerable:!0})},VN=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of FN(e))!MN.call(t,i)&&i!==n&&wd(t,i,{get:()=>e[i],enumerable:!(r=DN(e,i))||r.enumerable});return t};var KN=(t,e,n)=>(n=t!=null?NN(LN(t)):{},VN(e||!t||!t.__esModule?wd(n,"default",{value:t,enumerable:!0}):n,t));var yv=BN(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});var UN=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ke(t){return t===null?"null":t===void 0?"undefined":t===""?"an empty string":typeof t=="symbol"?`<${t.toString()}>`:Array.isArray(t)?"an array":JSON.stringify(t)}o(Ke,"getPrintable");function ao(t,e){if(t.length===0)return"nothing";if(t.length===1)return Ke(t[0]);let n=t.slice(0,-1),r=t[t.length-1],i=t.length>2?`, ${e} `:` ${e} `;return`${n.map(s=>Ke(s)).join(", ")}${i}${Ke(r)}`}o(ao,"getPrintableArray");function Br(t,e){var n,r,i;return typeof e=="number"?`${(n=t?.p)!==null&&n!==void 0?n:"."}[${e}]`:UN.test(e)?`${(r=t?.p)!==null&&r!==void 0?r:""}.${e}`:`${(i=t?.p)!==null&&i!==void 0?i:"."}[${JSON.stringify(e)}]`}o(Br,"computeKey");function Qf(t,e,n){return t===1?e:n}o(Qf,"plural");var jN=/^#[0-9a-f]{6}$/i,GN=/^#[0-9a-f]{6}([0-9a-f]{2})?$/i,WN=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,zN=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i,cv=/^(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))T(?:[01]\d|2[0-3])(:?)[0-5]\d(?:\3[0-5]\d)?(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$/;function ge({errors:t,p:e}={},n){return t?.push(`${e??"."}: ${n}`),!1}o(ge,"pushError");function HN(t,e){return n=>{t[e]=n}}o(HN,"makeSetter");function Hn(t,e){return n=>{let r=t[e];return t[e]=n,Hn(t,e).bind(null,r)}}o(Hn,"makeCoercionFn");function ys(t,e,n){let r=o(()=>(t(n()),i),"commit"),i=o(()=>(t(e),r),"revert");return r}o(ys,"makeLazyCoercionFn");function Yf(){return Ee({test:o((t,e)=>!0,"test")})}o(Yf,"isUnknown");function uv(t){return Ee({test:o((e,n)=>e!==t?ge(n,`Expected ${Ke(t)} (got ${Ke(e)})`):!0,"test")})}o(uv,"isLiteral");function fv(){return Ee({test:o((t,e)=>typeof t!="string"?ge(e,`Expected a string (got ${Ke(t)})`):!0,"test")})}o(fv,"isString");function QN(t){let e=Array.isArray(t)?t:Object.values(t),n=e.every(i=>typeof i=="string"||typeof i=="number"),r=new Set(e);return r.size===1?uv([...r][0]):Ee({test:o((i,s)=>r.has(i)?!0:n?ge(s,`Expected one of ${ao(e,"or")} (got ${Ke(i)})`):ge(s,`Expected a valid enumeration value (got ${Ke(i)})`),"test")})}o(QN,"isEnum");var YN=new Map([["true",!0],["True",!0],["1",!0],[1,!0],["false",!1],["False",!1],["0",!1],[0,!1]]);function JN(){return Ee({test:o((t,e)=>{var n;if(typeof t!="boolean"){if(typeof e?.coercions<"u"){if(typeof e?.coercion>"u")return ge(e,"Unbound coercion result");let r=YN.get(t);if(typeof r<"u")return e.coercions.push([(n=e.p)!==null&&n!==void 0?n:".",e.coercion.bind(null,r)]),!0}return ge(e,`Expected a boolean (got ${Ke(t)})`)}return!0},"test")})}o(JN,"isBoolean");function ZN(){return Ee({test:o((t,e)=>{var n;if(typeof t!="number"){if(typeof e?.coercions<"u"){if(typeof e?.coercion>"u")return ge(e,"Unbound coercion result");let r;if(typeof t=="string"){let i;try{i=JSON.parse(t)}catch{}if(typeof i=="number")if(JSON.stringify(i)===t)r=i;else return ge(e,`Received a number that can't be safely represented by the runtime (${t})`)}if(typeof r<"u")return e.coercions.push([(n=e.p)!==null&&n!==void 0?n:".",e.coercion.bind(null,r)]),!0}return ge(e,`Expected a number (got ${Ke(t)})`)}return!0},"test")})}o(ZN,"isNumber");function XN(t){return Ee({test:o((e,n)=>{var r;if(typeof n?.coercions>"u")return ge(n,"The isPayload predicate can only be used with coercion enabled");if(typeof n.coercion>"u")return ge(n,"Unbound coercion result");if(typeof e!="string")return ge(n,`Expected a string (got ${Ke(e)})`);let i;try{i=JSON.parse(e)}catch{return ge(n,`Expected a JSON string (got ${Ke(e)})`)}let s={value:i};return t(i,Object.assign(Object.assign({},n),{coercion:Hn(s,"value")}))?(n.coercions.push([(r=n.p)!==null&&r!==void 0?r:".",n.coercion.bind(null,s.value)]),!0):!1},"test")})}o(XN,"isPayload");function e0(){return Ee({test:o((t,e)=>{var n;if(!(t instanceof Date)){if(typeof e?.coercions<"u"){if(typeof e?.coercion>"u")return ge(e,"Unbound coercion result");let r;if(typeof t=="string"&&cv.test(t))r=new Date(t);else{let i;if(typeof t=="string"){let s;try{s=JSON.parse(t)}catch{}typeof s=="number"&&(i=s)}else typeof t=="number"&&(i=t);if(typeof i<"u")if(Number.isSafeInteger(i)||!Number.isSafeInteger(i*1e3))r=new Date(i*1e3);else return ge(e,`Received a timestamp that can't be safely represented by the runtime (${t})`)}if(typeof r<"u")return e.coercions.push([(n=e.p)!==null&&n!==void 0?n:".",e.coercion.bind(null,r)]),!0}return ge(e,`Expected a date (got ${Ke(t)})`)}return!0},"test")})}o(e0,"isDate");function xd(t,{delimiter:e}={}){return Ee({test:o((n,r)=>{var i;let s=n;if(typeof n=="string"&&typeof e<"u"&&typeof r?.coercions<"u"){if(typeof r?.coercion>"u")return ge(r,"Unbound coercion result");n=n.split(e)}if(!Array.isArray(n))return ge(r,`Expected an array (got ${Ke(n)})`);let a=!0;for(let l=0,d=n.length;l<d&&(a=t(n[l],Object.assign(Object.assign({},r),{p:Br(r,l),coercion:Hn(n,l)}))&&a,!(!a&&r?.errors==null));++l);return n!==s&&r.coercions.push([(i=r.p)!==null&&i!==void 0?i:".",r.coercion.bind(null,n)]),a},"test")})}o(xd,"isArray");function t0(t,{delimiter:e}={}){let n=xd(t,{delimiter:e});return Ee({test:o((r,i)=>{var s,a;if(Object.getPrototypeOf(r).toString()==="[object Set]")if(typeof i?.coercions<"u"){if(typeof i?.coercion>"u")return ge(i,"Unbound coercion result");let l=[...r],d=[...r];if(!n(d,Object.assign(Object.assign({},i),{coercion:void 0})))return!1;let c=o(()=>d.some((u,f)=>u!==l[f])?new Set(d):r,"updateValue");return i.coercions.push([(s=i.p)!==null&&s!==void 0?s:".",ys(i.coercion,r,c)]),!0}else{let l=!0;for(let d of r)if(l=t(d,Object.assign({},i))&&l,!l&&i?.errors==null)break;return l}if(typeof i?.coercions<"u"){if(typeof i?.coercion>"u")return ge(i,"Unbound coercion result");let l={value:r};return n(r,Object.assign(Object.assign({},i),{coercion:Hn(l,"value")}))?(i.coercions.push([(a=i.p)!==null&&a!==void 0?a:".",ys(i.coercion,r,()=>new Set(l.value))]),!0):!1}return ge(i,`Expected a set (got ${Ke(r)})`)},"test")})}o(t0,"isSet");function n0(t,e){let n=xd(Ad([t,e])),r=Ed(e,{keys:t});return Ee({test:o((i,s)=>{var a,l,d;if(Object.getPrototypeOf(i).toString()==="[object Map]")if(typeof s?.coercions<"u"){if(typeof s?.coercion>"u")return ge(s,"Unbound coercion result");let c=[...i],u=[...i];if(!n(u,Object.assign(Object.assign({},s),{coercion:void 0})))return!1;let f=o(()=>u.some((h,g)=>h[0]!==c[g][0]||h[1]!==c[g][1])?new Map(u):i,"updateValue");return s.coercions.push([(a=s.p)!==null&&a!==void 0?a:".",ys(s.coercion,i,f)]),!0}else{let c=!0;for(let[u,f]of i)if(c=t(u,Object.assign({},s))&&c,!c&&s?.errors==null||(c=e(f,Object.assign(Object.assign({},s),{p:Br(s,u)}))&&c,!c&&s?.errors==null))break;return c}if(typeof s?.coercions<"u"){if(typeof s?.coercion>"u")return ge(s,"Unbound coercion result");let c={value:i};return Array.isArray(i)?n(i,Object.assign(Object.assign({},s),{coercion:void 0}))?(s.coercions.push([(l=s.p)!==null&&l!==void 0?l:".",ys(s.coercion,i,()=>new Map(c.value))]),!0):!1:r(i,Object.assign(Object.assign({},s),{coercion:Hn(c,"value")}))?(s.coercions.push([(d=s.p)!==null&&d!==void 0?d:".",ys(s.coercion,i,()=>new Map(Object.entries(c.value)))]),!0):!1}return ge(s,`Expected a map (got ${Ke(i)})`)},"test")})}o(n0,"isMap");function Ad(t,{delimiter:e}={}){let n=hv(t.length);return Ee({test:o((r,i)=>{var s;if(typeof r=="string"&&typeof e<"u"&&typeof i?.coercions<"u"){if(typeof i?.coercion>"u")return ge(i,"Unbound coercion result");r=r.split(e),i.coercions.push([(s=i.p)!==null&&s!==void 0?s:".",i.coercion.bind(null,r)])}if(!Array.isArray(r))return ge(i,`Expected a tuple (got ${Ke(r)})`);let a=n(r,Object.assign({},i));for(let l=0,d=r.length;l<d&&l<t.length&&(a=t[l](r[l],Object.assign(Object.assign({},i),{p:Br(i,l),coercion:Hn(r,l)}))&&a,!(!a&&i?.errors==null));++l);return a},"test")})}o(Ad,"isTuple");function Ed(t,{keys:e=null}={}){let n=xd(Ad([e??fv(),t]));return Ee({test:o((r,i)=>{var s;if(Array.isArray(r)&&typeof i?.coercions<"u")return typeof i?.coercion>"u"?ge(i,"Unbound coercion result"):n(r,Object.assign(Object.assign({},i),{coercion:void 0}))?(r=Object.fromEntries(r),i.coercions.push([(s=i.p)!==null&&s!==void 0?s:".",i.coercion.bind(null,r)]),!0):!1;if(typeof r!="object"||r===null)return ge(i,`Expected an object (got ${Ke(r)})`);let a=Object.keys(r),l=!0;for(let d=0,c=a.length;d<c&&(l||i?.errors!=null);++d){let u=a[d],f=r[u];if(u==="__proto__"||u==="constructor"){l=ge(Object.assign(Object.assign({},i),{p:Br(i,u)}),"Unsafe property name");continue}if(e!==null&&!e(u,i)){l=!1;continue}if(!t(f,Object.assign(Object.assign({},i),{p:Br(i,u),coercion:Hn(r,u)}))){l=!1;continue}}return l},"test")})}o(Ed,"isRecord");function r0(t,e={}){return Ed(t,e)}o(r0,"isDict");function pv(t,{extra:e=null}={}){let n=Object.keys(t),r=Ee({test:o((i,s)=>{if(typeof i!="object"||i===null)return ge(s,`Expected an object (got ${Ke(i)})`);let a=new Set([...n,...Object.keys(i)]),l={},d=!0;for(let c of a){if(c==="constructor"||c==="__proto__")d=ge(Object.assign(Object.assign({},s),{p:Br(s,c)}),"Unsafe property name");else{let u=Object.prototype.hasOwnProperty.call(t,c)?t[c]:void 0,f=Object.prototype.hasOwnProperty.call(i,c)?i[c]:void 0;typeof u<"u"?d=u(f,Object.assign(Object.assign({},s),{p:Br(s,c),coercion:Hn(i,c)}))&&d:e===null?d=ge(Object.assign(Object.assign({},s),{p:Br(s,c)}),`Extraneous property (got ${Ke(f)})`):Object.defineProperty(l,c,{enumerable:!0,get:o(()=>f,"get"),set:HN(i,c)})}if(!d&&s?.errors==null)break}return e!==null&&(d||s?.errors!=null)&&(d=e(l,s)&&d),d},"test")});return Object.assign(r,{properties:t})}o(pv,"isObject");function i0(t){return pv(t,{extra:Ed(Yf())})}o(i0,"isPartial");var o0=o(t=>Ee({test:o((e,n)=>e instanceof t?!0:ge(n,`Expected an instance of ${t.name} (got ${Ke(e)})`),"test")}),"isInstanceOf"),s0=o((t,{exclusive:e=!1}={})=>Ee({test:o((n,r)=>{var i,s,a;let l=[],d=typeof r?.errors<"u"?[]:void 0;for(let c=0,u=t.length;c<u;++c){let f=typeof r?.errors<"u"?[]:void 0,h=typeof r?.coercions<"u"?[]:void 0;if(t[c](n,Object.assign(Object.assign({},r),{errors:f,coercions:h,p:`${(i=r?.p)!==null&&i!==void 0?i:"."}#${c+1}`}))){if(l.push([`#${c+1}`,h]),!e)break}else d?.push(f[0])}if(l.length===1){let[,c]=l[0];return typeof c<"u"&&((s=r?.coercions)===null||s===void 0||s.push(...c)),!0}return l.length>1?ge(r,`Expected to match exactly a single predicate (matched ${l.join(", ")})`):(a=r?.errors)===null||a===void 0||a.push(...d),!1},"test")}),"isOneOf");function mv(t){return()=>t}o(mv,"makeTrait");function Ee({test:t}){return mv(t)()}o(Ee,"makeValidator");var Vr=class extends Error{static{o(this,"TypeAssertionError")}constructor({errors:e}={}){let n="Type mismatch";if(e&&e.length>0){n+=`
|
|
4
|
+
`;for(let r of e)n+=`
|
|
5
|
+
- ${r}`}super(n)}};function a0(t,e){if(!e(t))throw new Vr}o(a0,"assert");function l0(t,e){let n=[];if(!e(t,{errors:n}))throw new Vr({errors:n})}o(l0,"assertWithErrors");function d0(t,e){}o(d0,"softAssert");function c0(t,e,{coerce:n=!1,errors:r,throw:i}={}){let s=r?[]:void 0;if(!n){if(e(t,{errors:s}))return i?t:{value:t,errors:void 0};if(i)throw new Vr({errors:s});return{value:void 0,errors:s??!0}}let a={value:t},l=Hn(a,"value"),d=[];if(!e(t,{errors:s,coercion:l,coercions:d})){if(i)throw new Vr({errors:s});return{value:void 0,errors:s??!0}}for(let[,c]of d)c();return i?a.value:{value:a.value,errors:void 0}}o(c0,"as");function u0(t,e){let n=Ad(t);return((...r)=>{if(!n(r))throw new Vr;return e(...r)})}o(u0,"fn");function f0(t){return Ee({test:o((e,n)=>e.length>=t?!0:ge(n,`Expected to have a length of at least ${t} elements (got ${e.length})`),"test")})}o(f0,"hasMinLength");function p0(t){return Ee({test:o((e,n)=>e.length<=t?!0:ge(n,`Expected to have a length of at most ${t} elements (got ${e.length})`),"test")})}o(p0,"hasMaxLength");function hv(t){return Ee({test:o((e,n)=>e.length!==t?ge(n,`Expected to have a length of exactly ${t} elements (got ${e.length})`):!0,"test")})}o(hv,"hasExactLength");function m0({map:t}={}){return Ee({test:o((e,n)=>{let r=new Set,i=new Set;for(let s=0,a=e.length;s<a;++s){let l=e[s],d=typeof t<"u"?t(l):l;if(r.has(d)){if(i.has(d))continue;ge(n,`Expected to contain unique elements; got a duplicate with ${Ke(e)}`),i.add(d)}else r.add(d)}return i.size===0},"test")})}o(m0,"hasUniqueItems");function h0(){return Ee({test:o((t,e)=>t<=0?!0:ge(e,`Expected to be negative (got ${t})`),"test")})}o(h0,"isNegative");function g0(){return Ee({test:o((t,e)=>t>=0?!0:ge(e,`Expected to be positive (got ${t})`),"test")})}o(g0,"isPositive");function y0(t){return Ee({test:o((e,n)=>e>=t?!0:ge(n,`Expected to be at least ${t} (got ${e})`),"test")})}o(y0,"isAtLeast");function b0(t){return Ee({test:o((e,n)=>e<=t?!0:ge(n,`Expected to be at most ${t} (got ${e})`),"test")})}o(b0,"isAtMost");function w0(t,e){return Ee({test:o((n,r)=>n>=t&&n<=e?!0:ge(r,`Expected to be in the [${t}; ${e}] range (got ${n})`),"test")})}o(w0,"isInInclusiveRange");function k0(t,e){return Ee({test:o((n,r)=>n>=t&&n<e?!0:ge(r,`Expected to be in the [${t}; ${e}[ range (got ${n})`),"test")})}o(k0,"isInExclusiveRange");function v0({unsafe:t=!1}={}){return Ee({test:o((e,n)=>e!==Math.round(e)?ge(n,`Expected to be an integer (got ${e})`):!t&&!Number.isSafeInteger(e)?ge(n,`Expected to be a safe integer (got ${e})`):!0,"test")})}o(v0,"isInteger");function S0(t){return Ee({test:o((e,n)=>t.test(e)?!0:ge(n,`Expected to match the pattern ${t.toString()} (got ${Ke(e)})`),"test")})}o(S0,"matchesRegExp");function x0(){return Ee({test:o((t,e)=>t!==t.toLowerCase()?ge(e,`Expected to be all-lowercase (got ${t})`):!0,"test")})}o(x0,"isLowerCase");function A0(){return Ee({test:o((t,e)=>t!==t.toUpperCase()?ge(e,`Expected to be all-uppercase (got ${t})`):!0,"test")})}o(A0,"isUpperCase");function E0(){return Ee({test:o((t,e)=>zN.test(t)?!0:ge(e,`Expected to be a valid UUID v4 (got ${Ke(t)})`),"test")})}o(E0,"isUUID4");function R0(){return Ee({test:o((t,e)=>cv.test(t)?!0:ge(e,`Expected to be a valid ISO 8601 date string (got ${Ke(t)})`),"test")})}o(R0,"isISO8601");function T0({alpha:t=!1}){return Ee({test:o((e,n)=>(t?jN.test(e):GN.test(e))?!0:ge(n,`Expected to be a valid hexadecimal color string (got ${Ke(e)})`),"test")})}o(T0,"isHexColor");function I0(){return Ee({test:o((t,e)=>WN.test(t)?!0:ge(e,`Expected to be a valid base 64 string (got ${Ke(t)})`),"test")})}o(I0,"isBase64");function $0(t=Yf()){return Ee({test:o((e,n)=>{let r;try{r=JSON.parse(e)}catch{return ge(n,`Expected to be a valid JSON string (got ${Ke(e)})`)}return t(r,n)},"test")})}o($0,"isJSON");function gv(t,...e){let n=Array.isArray(e[0])?e[0]:e;return Ee({test:o((r,i)=>{var s,a;let l={value:r},d=typeof i?.coercions<"u"?Hn(l,"value"):void 0,c=typeof i?.coercions<"u"?[]:void 0;if(!t(r,Object.assign(Object.assign({},i),{coercion:d,coercions:c})))return!1;let u=[];if(typeof c<"u")for(let[,f]of c)u.push(f());try{if(typeof i?.coercions<"u"){if(l.value!==r){if(typeof i?.coercion>"u")return ge(i,"Unbound coercion result");i.coercions.push([(s=i.p)!==null&&s!==void 0?s:".",i.coercion.bind(null,l.value)])}(a=i?.coercions)===null||a===void 0||a.push(...c)}return n.every(f=>f(l.value,i))}finally{for(let f of u)f()}},"test")})}o(gv,"cascade");function _0(t,...e){let n=Array.isArray(e[0])?e[0]:e;return gv(t,n)}o(_0,"applyCascade");function O0(t){return Ee({test:o((e,n)=>typeof e>"u"?!0:t(e,n),"test")})}o(O0,"isOptional");function C0(t){return Ee({test:o((e,n)=>e===null?!0:t(e,n),"test")})}o(C0,"isNullable");var bs={missing:o((t,e)=>t.has(e),"missing"),undefined:o((t,e,n)=>t.has(e)&&typeof n[e]<"u","undefined"),nil:o((t,e,n)=>t.has(e)&&n[e]!=null,"nil"),falsy:o((t,e,n)=>t.has(e)&&!!n[e],"falsy")};function P0(t,e){var n;let r=new Set(t),i=bs[(n=e?.missingIf)!==null&&n!==void 0?n:"missing"];return Ee({test:o((s,a)=>{let l=new Set(Object.keys(s)),d=[];for(let c of r)i(l,c,s)||d.push(c);return d.length>0?ge(a,`Missing required ${Qf(d.length,"property","properties")} ${ao(d,"and")}`):!0},"test")})}o(P0,"hasRequiredKeys");function N0(t,e){var n;let r=new Set(t),i=bs[(n=e?.missingIf)!==null&&n!==void 0?n:"missing"];return Ee({test:o((s,a)=>Object.keys(s).some(c=>i(r,c,s))?!0:ge(a,`Missing at least one property from ${ao(Array.from(r),"or")}`),"test")})}o(N0,"hasAtLeastOneKey");function D0(t,e){var n;let r=new Set(t),i=bs[(n=e?.missingIf)!==null&&n!==void 0?n:"missing"];return Ee({test:o((s,a)=>{let l=new Set(Object.keys(s)),d=[];for(let c of r)i(l,c,s)&&d.push(c);return d.length>0?ge(a,`Forbidden ${Qf(d.length,"property","properties")} ${ao(d,"and")}`):!0},"test")})}o(D0,"hasForbiddenKeys");function F0(t,e){var n;let r=new Set(t),i=bs[(n=e?.missingIf)!==null&&n!==void 0?n:"missing"];return Ee({test:o((s,a)=>{let l=new Set(Object.keys(s)),d=[];for(let c of r)i(l,c,s)&&d.push(c);return d.length>1?ge(a,`Mutually exclusive properties ${ao(d,"and")}`):!0},"test")})}o(F0,"hasMutuallyExclusiveKeys");(function(t){t.Forbids="Forbids",t.Requires="Requires"})(he.KeyRelationship||(he.KeyRelationship={}));var L0={[he.KeyRelationship.Forbids]:{expect:!1,message:"forbids using"},[he.KeyRelationship.Requires]:{expect:!0,message:"requires using"}};function M0(t,e,n,r){var i,s;let a=new Set((i=r?.ignore)!==null&&i!==void 0?i:[]),l=bs[(s=r?.missingIf)!==null&&s!==void 0?s:"missing"],d=new Set(n),c=L0[e],u=e===he.KeyRelationship.Forbids?"or":"and";return Ee({test:o((f,h)=>{let g=new Set(Object.keys(f));if(!l(g,t,f)||a.has(f[t]))return!0;let b=[];for(let y of d)(l(g,y,f)&&!a.has(f[y]))!==c.expect&&b.push(y);return b.length>=1?ge(h,`Property "${t}" ${c.message} ${Qf(b.length,"property","properties")} ${ao(b,u)}`):!0},"test")})}o(M0,"hasKeyRelationship");he.TypeAssertionError=Vr;he.applyCascade=_0;he.as=c0;he.assert=a0;he.assertWithErrors=l0;he.cascade=gv;he.fn=u0;he.hasAtLeastOneKey=N0;he.hasExactLength=hv;he.hasForbiddenKeys=D0;he.hasKeyRelationship=M0;he.hasMaxLength=p0;he.hasMinLength=f0;he.hasMutuallyExclusiveKeys=F0;he.hasRequiredKeys=P0;he.hasUniqueItems=m0;he.isArray=xd;he.isAtLeast=y0;he.isAtMost=b0;he.isBase64=I0;he.isBoolean=JN;he.isDate=e0;he.isDict=r0;he.isEnum=QN;he.isHexColor=T0;he.isISO8601=R0;he.isInExclusiveRange=k0;he.isInInclusiveRange=w0;he.isInstanceOf=o0;he.isInteger=v0;he.isJSON=$0;he.isLiteral=uv;he.isLowerCase=x0;he.isMap=n0;he.isNegative=h0;he.isNullable=C0;he.isNumber=ZN;he.isObject=pv;he.isOneOf=s0;he.isOptional=O0;he.isPartial=i0;he.isPayload=XN;he.isPositive=g0;he.isRecord=Ed;he.isSet=t0;he.isString=fv;he.isTuple=Ad;he.isUUID4=E0;he.isUnknown=Yf;he.isUpperCase=A0;he.makeTrait=mv;he.makeValidator=Ee;he.matchesRegExp=S0;he.softAssert=d0});import zG from"node:path";var Ve;(function(t){t.StartOfInput="\0",t.EndOfInput="",t.EndOfPartialInput=""})(Ve||(Ve={}));var Le;(function(t){t[t.InitialNode=0]="InitialNode",t[t.SuccessNode=1]="SuccessNode",t[t.ErrorNode=2]="ErrorNode",t[t.CustomNode=3]="CustomNode"})(Le||(Le={}));var qr=-1,Gf=/^(-h|--help)(?:=([0-9]+))?$/,kd=/^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/,dv=/^-[a-zA-Z]{2,}$/,Wf=/^([^=]+)=([\s\S]*)$/,zf=process.env.DEBUG_CLI==="1";var St=class extends Error{static{o(this,"UsageError")}constructor(e){super(e),this.clipanion={type:"usage"},this.name="UsageError"}},so=class extends Error{static{o(this,"UnknownSyntaxError")}constructor(e,n){if(super(),this.input=e,this.candidates=n,this.clipanion={type:"none"},this.name="UnknownSyntaxError",this.candidates.length===0)this.message="Command not found, but we're not sure what's the alternative.";else if(this.candidates.every(r=>r.reason!==null&&r.reason===n[0].reason)){let[{reason:r}]=this.candidates;this.message=`${r}
|
|
6
|
+
|
|
7
|
+
${this.candidates.map(({usage:i})=>`$ ${i}`).join(`
|
|
8
|
+
`)}`}else if(this.candidates.length===1){let[{usage:r}]=this.candidates;this.message=`Command not found; did you mean:
|
|
9
|
+
|
|
10
|
+
$ ${r}
|
|
11
|
+
${Hf(e)}`}else this.message=`Command not found; did you mean one of:
|
|
12
|
+
|
|
13
|
+
${this.candidates.map(({usage:r},i)=>`${`${i}.`.padStart(4)} ${r}`).join(`
|
|
14
|
+
`)}
|
|
15
|
+
|
|
16
|
+
${Hf(e)}`}},vd=class extends Error{static{o(this,"AmbiguousSyntaxError")}constructor(e,n){super(),this.input=e,this.usages=n,this.clipanion={type:"none"},this.name="AmbiguousSyntaxError",this.message=`Cannot find which to pick amongst the following alternatives:
|
|
17
|
+
|
|
18
|
+
${this.usages.map((r,i)=>`${`${i}.`.padStart(4)} ${r}`).join(`
|
|
19
|
+
`)}
|
|
20
|
+
|
|
21
|
+
${Hf(e)}`}},Hf=o(t=>`While running ${t.filter(e=>e!==Ve.EndOfInput&&e!==Ve.EndOfPartialInput).map(e=>{let n=JSON.stringify(e);return e.match(/\s/)||e.length===0||n!==`"${e}"`?n:e}).join(" ")}`,"whileRunning");var hs=Symbol("clipanion/isOption");function Jt(t){return{...t,[hs]:!0}}o(Jt,"makeCommandOption");function zn(t,e){return typeof t>"u"?[t,e]:typeof t=="object"&&t!==null&&!Array.isArray(t)?[void 0,t]:[t,e]}o(zn,"rerouteArguments");function Sd(t,{mergeName:e=!1}={}){let n=t.match(/^([^:]+): (.*)$/m);if(!n)return"validation failed";let[,r,i]=n;return e&&(i=i[0].toLowerCase()+i.slice(1)),i=r!=="."||!e?`${r.replace(/^\.(\[|$)/,"$1")}: ${i}`:`: ${i}`,i}o(Sd,"cleanValidationError");function gs(t,e){return e.length===1?new St(`${t}${Sd(e[0],{mergeName:!0})}`):new St(`${t}:
|
|
22
|
+
${e.map(n=>`
|
|
23
|
+
- ${Sd(n)}`).join("")}`)}o(gs,"formatError");function wi(t,e,n){if(typeof n>"u")return e;let r=[],i=[],s=o(l=>{let d=e;return e=l,s.bind(null,d)},"coercion");if(!n(e,{errors:r,coercions:i,coercion:s}))throw gs(`Invalid value for ${t}`,r);for(let[,l]of i)l();return e}o(wi,"applyValidator");var I=class{static{o(this,"Command")}constructor(){this.help=!1}static Usage(e){return e}async catch(e){throw e}async validateAndExecute(){let n=this.constructor.schema;if(Array.isArray(n)){let{isDict:i,isUnknown:s,applyCascade:a}=await Promise.resolve().then(()=>KN(yv(),1)),l=a(i(s()),n),d=[],c=[];if(!l(this,{errors:d,coercions:c}))throw gs("Invalid option schema",d);for(let[,f]of c)f()}else if(n!=null)throw new Error("Invalid command schema");let r=await this.execute();return typeof r<"u"?r:0}};I.isOption=hs;I.Default=[];import Jf from"tty";function wv(){return Jf&&"getColorDepth"in Jf.WriteStream.prototype?Jf.WriteStream.prototype.getColorDepth():process.env.FORCE_COLOR==="0"?1:process.env.FORCE_COLOR==="1"||typeof process.stdout<"u"&&process.stdout.isTTY?8:1}o(wv,"getDefaultColorDepth");var bv;function kv(t){let e=bv;if(typeof e>"u"){if(t.stdout===process.stdout&&t.stderr===process.stderr)return null;let{AsyncLocalStorage:n}=qN("async_hooks");e=bv=new n;let r=process.stdout._write;process.stdout._write=function(s,a,l){let d=e.getStore();return typeof d>"u"?r.call(this,s,a,l):d.stdout.write(s,a,l)};let i=process.stderr._write;process.stderr._write=function(s,a,l){let d=e.getStore();return typeof d>"u"?i.call(this,s,a,l):d.stderr.write(s,a,l)}}return n=>e.run(t,n)}o(kv,"getCaptureActivator");function sn(t){zf&&console.log(t)}o(sn,"debug");var vv={candidateUsage:null,requiredOptions:[],errorMessage:null,ignoreOptions:!1,path:[],positionals:[],options:[],remainder:null,selectedIndex:qr,tokens:[]};function Sv(){let t={nodes:[]};for(let e=0;e<Le.CustomNode;++e)t.nodes.push(an());return t}o(Sv,"makeStateMachine");function q0(t){let e=Sv(),n=[],r=e.nodes.length;for(let i of t){n.push(r);for(let s=0;s<i.nodes.length;++s)Av(s)||e.nodes.push(z0(i.nodes[s],r));r+=i.nodes.length-Le.CustomNode+1}for(let i of n)lo(e,Le.InitialNode,i);return e}o(q0,"makeAnyOfMachine");function wn(t,e){return t.nodes.push(e),t.nodes.length-1}o(wn,"injectNode");function B0(t){let e=new Set,n=o(r=>{if(e.has(r))return;e.add(r);let i=t.nodes[r];for(let a of Object.values(i.statics))for(let{to:l}of a)n(l);for(let[,{to:a}]of i.dynamics)n(a);for(let{to:a}of i.shortcuts)n(a);let s=new Set(i.shortcuts.map(({to:a})=>a));for(;i.shortcuts.length>0;){let{to:a}=i.shortcuts.shift(),l=t.nodes[a];for(let[d,c]of Object.entries(l.statics)){let u=Object.prototype.hasOwnProperty.call(i.statics,d)?i.statics[d]:i.statics[d]=[];for(let f of c)u.some(({to:h})=>f.to===h)||u.push(f)}for(let[d,c]of l.dynamics)i.dynamics.some(([u,{to:f}])=>d===u&&c.to===f)||i.dynamics.push([d,c]);for(let d of l.shortcuts)s.has(d.to)||(i.shortcuts.push(d),s.add(d.to))}},"process");n(Le.InitialNode)}o(B0,"simplifyMachine");function V0(t,{prefix:e=""}={}){if(zf){sn(`${e}Nodes are:`);for(let n=0;n<t.nodes.length;++n)sn(`${e} ${n}: ${JSON.stringify(t.nodes[n])}`)}}o(V0,"debugMachine");function K0(t,e,n=!1){sn(`Running a vm on ${JSON.stringify(e)}`);let r=[{node:Le.InitialNode,state:{candidateUsage:null,requiredOptions:[],errorMessage:null,ignoreOptions:!1,options:[],path:[],positionals:[],remainder:null,selectedIndex:null,tokens:[]}}];V0(t,{prefix:" "});let i=[Ve.StartOfInput,...e];for(let s=0;s<i.length;++s){let a=i[s],l=a===Ve.EndOfInput||a===Ve.EndOfPartialInput,d=s-1;sn(` Processing ${JSON.stringify(a)}`);let c=[];for(let{node:u,state:f}of r){sn(` Current node is ${u}`);let h=t.nodes[u];if(u===Le.ErrorNode){c.push({node:u,state:f});continue}console.assert(h.shortcuts.length===0,"Shortcuts should have been eliminated by now");let g=Object.prototype.hasOwnProperty.call(h.statics,a);if(!n||s<i.length-1||g)if(g){let b=h.statics[a];for(let{to:y,reducer:w}of b)c.push({node:y,state:typeof w<"u"?Rd(Xf,w,f,a,d):f}),sn(` Static transition to ${y} found`)}else sn(" No static transition found");else{let b=!1;for(let y of Object.keys(h.statics))if(y.startsWith(a)){if(a===y)for(let{to:w,reducer:S}of h.statics[y])c.push({node:w,state:typeof S<"u"?Rd(Xf,S,f,a,d):f}),sn(` Static transition to ${w} found`);else for(let{to:w}of h.statics[y])c.push({node:w,state:{...f,remainder:y.slice(a.length)}}),sn(` Static transition to ${w} found (partial match)`);b=!0}b||sn(" No partial static transition found")}if(!l)for(let[b,{to:y,reducer:w}]of h.dynamics)Rd(H0,b,f,a,d)&&(c.push({node:y,state:typeof w<"u"?Rd(Xf,w,f,a,d):f}),sn(` Dynamic transition to ${y} found (via ${b})`))}if(c.length===0&&l&&e.length===1)return[{node:Le.InitialNode,state:vv}];if(c.length===0)throw new so(e,r.filter(({node:u})=>u!==Le.ErrorNode).map(({state:u})=>({usage:u.candidateUsage,reason:null})));if(c.every(({node:u})=>u===Le.ErrorNode))throw new so(e,c.map(({state:u})=>({usage:u.candidateUsage,reason:u.errorMessage})));r=j0(c)}if(r.length>0){sn(" Results:");for(let s of r)sn(` - ${s.node} -> ${JSON.stringify(s.state)}`)}else sn(" No results");return r}o(K0,"runMachineInternal");function U0(t,e,{endToken:n=Ve.EndOfInput}={}){let r=K0(t,[...e,n]);return G0(e,r.map(({state:i})=>i))}o(U0,"runMachine");function j0(t){let e=0;for(let{state:n}of t)n.path.length>e&&(e=n.path.length);return t.filter(({state:n})=>n.path.length===e)}o(j0,"trimSmallerBranches");function G0(t,e){let n=e.filter(f=>f.selectedIndex!==null);if(n.length===0)throw new Error;let r=n.filter(f=>f.selectedIndex===qr||f.requiredOptions.every(h=>h.some(g=>f.options.find(b=>b.name===g))));if(r.length===0)throw new so(t,n.map(f=>({usage:f.candidateUsage,reason:null})));let i=0;for(let f of r)f.path.length>i&&(i=f.path.length);let s=r.filter(f=>f.path.length===i),a=o(f=>f.positionals.filter(({extra:h})=>!h).length+f.options.length,"getPositionalCount"),l=s.map(f=>({state:f,positionalCount:a(f)})),d=0;for(let{positionalCount:f}of l)f>d&&(d=f);let c=l.filter(({positionalCount:f})=>f===d).map(({state:f})=>f),u=W0(c);if(u.length>1)throw new vd(t,u.map(f=>f.candidateUsage));return u[0]}o(G0,"selectBestState");function W0(t){let e=[],n=[];for(let r of t)r.selectedIndex===qr?n.push(r):e.push(r);return n.length>0&&e.push({...vv,path:xv(...n.map(r=>r.path)),options:n.reduce((r,i)=>r.concat(i.options),[])}),e}o(W0,"aggregateHelpStates");function xv(t,e,...n){return e===void 0?Array.from(t):xv(t.filter((r,i)=>r===e[i]),...n)}o(xv,"findCommonPrefix");function an(){return{dynamics:[],shortcuts:[],statics:{}}}o(an,"makeNode");function Av(t){return t===Le.SuccessNode||t===Le.ErrorNode}o(Av,"isTerminalNode");function Zf(t,e=0){return{to:Av(t.to)?t.to:t.to>=Le.CustomNode?t.to+e-Le.CustomNode+1:t.to+e,reducer:t.reducer}}o(Zf,"cloneTransition");function z0(t,e=0){let n=an();for(let[r,i]of t.dynamics)n.dynamics.push([r,Zf(i,e)]);for(let r of t.shortcuts)n.shortcuts.push(Zf(r,e));for(let[r,i]of Object.entries(t.statics))n.statics[r]=i.map(s=>Zf(s,e));return n}o(z0,"cloneNode");function bt(t,e,n,r,i){t.nodes[e].dynamics.push([n,{to:r,reducer:i}])}o(bt,"registerDynamic");function lo(t,e,n,r){t.nodes[e].shortcuts.push({to:n,reducer:r})}o(lo,"registerShortcut");function jt(t,e,n,r,i){(Object.prototype.hasOwnProperty.call(t.nodes[e].statics,n)?t.nodes[e].statics[n]:t.nodes[e].statics[n]=[]).push({to:r,reducer:i})}o(jt,"registerStatic");function Rd(t,e,n,r,i){if(Array.isArray(e)){let[s,...a]=e;return t[s](n,r,i,...a)}else return t[e](n,r,i)}o(Rd,"execute");var H0={always:o(()=>!0,"always"),isOptionLike:o((t,e)=>!t.ignoreOptions&&e!=="-"&&e.startsWith("-"),"isOptionLike"),isNotOptionLike:o((t,e)=>t.ignoreOptions||e==="-"||!e.startsWith("-"),"isNotOptionLike"),isOption:o((t,e,n,r)=>!t.ignoreOptions&&e===r,"isOption"),isBatchOption:o((t,e,n,r)=>!t.ignoreOptions&&dv.test(e)&&[...e.slice(1)].every(i=>r.has(`-${i}`)),"isBatchOption"),isBoundOption:o((t,e,n,r,i)=>{let s=e.match(Wf);return!t.ignoreOptions&&!!s&&kd.test(s[1])&&r.has(s[1])&&i.filter(a=>a.nameSet.includes(s[1])).every(a=>a.allowBinding)},"isBoundOption"),isNegatedOption:o((t,e,n,r)=>!t.ignoreOptions&&e===`--no-${r.slice(2)}`,"isNegatedOption"),isHelp:o((t,e)=>!t.ignoreOptions&&Gf.test(e),"isHelp"),isUnsupportedOption:o((t,e,n,r)=>!t.ignoreOptions&&e.startsWith("-")&&kd.test(e)&&!r.has(e),"isUnsupportedOption"),isInvalidOption:o((t,e)=>!t.ignoreOptions&&e.startsWith("-")&&!kd.test(e),"isInvalidOption")},Xf={setCandidateState:o((t,e,n,r)=>({...t,...r}),"setCandidateState"),setSelectedIndex:o((t,e,n,r)=>({...t,selectedIndex:r}),"setSelectedIndex"),pushBatch:o((t,e,n,r)=>{let i=t.options.slice(),s=t.tokens.slice();for(let a=1;a<e.length;++a){let l=r.get(`-${e[a]}`),d=a===1?[0,2]:[a,a+1];i.push({name:l,value:!0}),s.push({segmentIndex:n,type:"option",option:l,slice:d})}return{...t,options:i,tokens:s}},"pushBatch"),pushBound:o((t,e,n)=>{let[,r,i]=e.match(Wf),s=t.options.concat({name:r,value:i}),a=t.tokens.concat([{segmentIndex:n,type:"option",slice:[0,r.length],option:r},{segmentIndex:n,type:"assign",slice:[r.length,r.length+1]},{segmentIndex:n,type:"value",slice:[r.length+1,r.length+i.length+1]}]);return{...t,options:s,tokens:a}},"pushBound"),pushPath:o((t,e,n)=>{let r=t.path.concat(e),i=t.tokens.concat({segmentIndex:n,type:"path"});return{...t,path:r,tokens:i}},"pushPath"),pushPositional:o((t,e,n)=>{let r=t.positionals.concat({value:e,extra:!1}),i=t.tokens.concat({segmentIndex:n,type:"positional"});return{...t,positionals:r,tokens:i}},"pushPositional"),pushExtra:o((t,e,n)=>{let r=t.positionals.concat({value:e,extra:!0}),i=t.tokens.concat({segmentIndex:n,type:"positional"});return{...t,positionals:r,tokens:i}},"pushExtra"),pushExtraNoLimits:o((t,e,n)=>{let r=t.positionals.concat({value:e,extra:fn}),i=t.tokens.concat({segmentIndex:n,type:"positional"});return{...t,positionals:r,tokens:i}},"pushExtraNoLimits"),pushTrue:o((t,e,n,r)=>{let i=t.options.concat({name:r,value:!0}),s=t.tokens.concat({segmentIndex:n,type:"option",option:r});return{...t,options:i,tokens:s}},"pushTrue"),pushFalse:o((t,e,n,r)=>{let i=t.options.concat({name:r,value:!1}),s=t.tokens.concat({segmentIndex:n,type:"option",option:r});return{...t,options:i,tokens:s}},"pushFalse"),pushUndefined:o((t,e,n,r)=>{let i=t.options.concat({name:e,value:void 0}),s=t.tokens.concat({segmentIndex:n,type:"option",option:e});return{...t,options:i,tokens:s}},"pushUndefined"),pushStringValue:o((t,e,n)=>{var r;let i=t.options[t.options.length-1],s=t.options.slice(),a=t.tokens.concat({segmentIndex:n,type:"value"});return i.value=((r=i.value)!==null&&r!==void 0?r:[]).concat([e]),{...t,options:s,tokens:a}},"pushStringValue"),setStringValue:o((t,e,n)=>{let r=t.options[t.options.length-1],i=t.options.slice(),s=t.tokens.concat({segmentIndex:n,type:"value"});return r.value=e,{...t,options:i,tokens:s}},"setStringValue"),inhibateOptions:o(t=>({...t,ignoreOptions:!0}),"inhibateOptions"),useHelp:o((t,e,n,r)=>{let[,,i]=e.match(Gf);return typeof i<"u"?{...t,options:[{name:"-c",value:String(r)},{name:"-i",value:i}]}:{...t,options:[{name:"-c",value:String(r)}]}},"useHelp"),setError:o((t,e,n,r)=>e===Ve.EndOfInput||e===Ve.EndOfPartialInput?{...t,errorMessage:`${r}.`}:{...t,errorMessage:`${r} ("${e}").`},"setError"),setOptionArityError:o((t,e)=>{let n=t.options[t.options.length-1];return{...t,errorMessage:`Not enough arguments to option ${n.name}.`}},"setOptionArityError")},fn=Symbol(),ep=class{static{o(this,"CommandBuilder")}constructor(e,n){this.allOptionNames=new Map,this.arity={leading:[],trailing:[],extra:[],proxy:!1},this.options=[],this.paths=[],this.cliIndex=e,this.cliOpts=n}addPath(e){this.paths.push(e)}setArity({leading:e=this.arity.leading,trailing:n=this.arity.trailing,extra:r=this.arity.extra,proxy:i=this.arity.proxy}){Object.assign(this.arity,{leading:e,trailing:n,extra:r,proxy:i})}addPositional({name:e="arg",required:n=!0}={}){if(!n&&this.arity.extra===fn)throw new Error("Optional parameters cannot be declared when using .rest() or .proxy()");if(!n&&this.arity.trailing.length>0)throw new Error("Optional parameters cannot be declared after the required trailing positional arguments");!n&&this.arity.extra!==fn?this.arity.extra.push(e):this.arity.extra!==fn&&this.arity.extra.length===0?this.arity.leading.push(e):this.arity.trailing.push(e)}addRest({name:e="arg",required:n=0}={}){if(this.arity.extra===fn)throw new Error("Infinite lists cannot be declared multiple times in the same command");if(this.arity.trailing.length>0)throw new Error("Infinite lists cannot be declared after the required trailing positional arguments");for(let r=0;r<n;++r)this.addPositional({name:e});this.arity.extra=fn}addProxy({required:e=0}={}){this.addRest({required:e}),this.arity.proxy=!0}addOption({names:e,description:n,arity:r=0,hidden:i=!1,required:s=!1,allowBinding:a=!0}){if(!a&&r>1)throw new Error("The arity cannot be higher than 1 when the option only supports the --arg=value syntax");if(!Number.isInteger(r))throw new Error(`The arity must be an integer, got ${r}`);if(r<0)throw new Error(`The arity must be positive, got ${r}`);let l=e.reduce((d,c)=>c.length>d.length?c:d,"");for(let d of e)this.allOptionNames.set(d,l);this.options.push({preferredName:l,nameSet:e,description:n,arity:r,hidden:i,required:s,allowBinding:a})}setContext(e){this.context=e}usage({detailed:e=!0,inlineOptions:n=!0}={}){let r=[this.cliOpts.binaryName],i=[];if(this.paths.length>0&&r.push(...this.paths[0]),e){for(let{preferredName:a,nameSet:l,arity:d,hidden:c,description:u,required:f}of this.options){if(c)continue;let h=[];for(let b=0;b<d;++b)h.push(` #${b}`);let g=`${l.join(",")}${h.join("")}`;!n&&u?i.push({preferredName:a,nameSet:l,definition:g,description:u,required:f}):r.push(f?`<${g}>`:`[${g}]`)}r.push(...this.arity.leading.map(a=>`<${a}>`)),this.arity.extra===fn?r.push("..."):r.push(...this.arity.extra.map(a=>`[${a}]`)),r.push(...this.arity.trailing.map(a=>`<${a}>`))}return{usage:r.join(" "),options:i}}compile(){if(typeof this.context>"u")throw new Error("Assertion failed: No context attached");let e=Sv(),n=Le.InitialNode,r=this.usage().usage,i=this.options.filter(l=>l.required).map(l=>l.nameSet);n=wn(e,an()),jt(e,Le.InitialNode,Ve.StartOfInput,n,["setCandidateState",{candidateUsage:r,requiredOptions:i}]);let s=this.arity.proxy?"always":"isNotOptionLike",a=this.paths.length>0?this.paths:[[]];for(let l of a){let d=n;if(l.length>0){let h=wn(e,an());lo(e,d,h),this.registerOptions(e,h),d=h}for(let h=0;h<l.length;++h){let g=wn(e,an());if(jt(e,d,l[h],g,"pushPath"),d=g,h+1<l.length){let b=wn(e,an());bt(e,d,"isHelp",b,["useHelp",this.cliIndex]),jt(e,b,Ve.EndOfInput,Le.SuccessNode,["setSelectedIndex",qr])}}if(this.arity.leading.length>0||!this.arity.proxy){let h=wn(e,an());bt(e,d,"isHelp",h,["useHelp",this.cliIndex]),bt(e,h,"always",h,"pushExtra"),jt(e,h,Ve.EndOfInput,Le.SuccessNode,["setSelectedIndex",qr]),this.registerOptions(e,d)}this.arity.leading.length>0&&(jt(e,d,Ve.EndOfInput,Le.ErrorNode,["setError","Not enough positional arguments"]),jt(e,d,Ve.EndOfPartialInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex]));let c=d;for(let h=0;h<this.arity.leading.length;++h){let g=wn(e,an());(!this.arity.proxy||h+1!==this.arity.leading.length)&&this.registerOptions(e,g),(this.arity.trailing.length>0||h+1!==this.arity.leading.length)&&(jt(e,g,Ve.EndOfInput,Le.ErrorNode,["setError","Not enough positional arguments"]),jt(e,g,Ve.EndOfPartialInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex])),bt(e,c,"isNotOptionLike",g,"pushPositional"),c=g}let u=c;if(this.arity.extra===fn||this.arity.extra.length>0){let h=wn(e,an());if(lo(e,c,h),this.arity.extra===fn){let g=wn(e,an());this.arity.proxy||this.registerOptions(e,g),bt(e,c,s,g,"pushExtraNoLimits"),bt(e,g,s,g,"pushExtraNoLimits"),lo(e,g,h)}else for(let g=0;g<this.arity.extra.length;++g){let b=wn(e,an());(!this.arity.proxy||g>0)&&this.registerOptions(e,b),bt(e,u,s,b,"pushExtra"),lo(e,b,h),u=b}u=h}this.arity.trailing.length>0&&(jt(e,u,Ve.EndOfInput,Le.ErrorNode,["setError","Not enough positional arguments"]),jt(e,u,Ve.EndOfPartialInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex]));let f=u;for(let h=0;h<this.arity.trailing.length;++h){let g=wn(e,an());this.arity.proxy||this.registerOptions(e,g),h+1<this.arity.trailing.length&&(jt(e,g,Ve.EndOfInput,Le.ErrorNode,["setError","Not enough positional arguments"]),jt(e,g,Ve.EndOfPartialInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex])),bt(e,f,"isNotOptionLike",g,"pushPositional"),f=g}bt(e,f,s,Le.ErrorNode,["setError","Extraneous positional argument"]),jt(e,f,Ve.EndOfInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex]),jt(e,f,Ve.EndOfPartialInput,Le.SuccessNode,["setSelectedIndex",this.cliIndex])}return{machine:e,context:this.context}}registerOptions(e,n){bt(e,n,["isOption","--"],n,"inhibateOptions"),bt(e,n,["isBatchOption",this.allOptionNames],n,["pushBatch",this.allOptionNames]),bt(e,n,["isBoundOption",this.allOptionNames,this.options],n,"pushBound"),bt(e,n,["isUnsupportedOption",this.allOptionNames],Le.ErrorNode,["setError","Unsupported option name"]),bt(e,n,["isInvalidOption"],Le.ErrorNode,["setError","Invalid option name"]);for(let r of this.options)if(r.arity===0)for(let i of r.nameSet)bt(e,n,["isOption",i],n,["pushTrue",r.preferredName]),i.startsWith("--")&&!i.startsWith("--no-")&&bt(e,n,["isNegatedOption",i],n,["pushFalse",r.preferredName]);else{let i=wn(e,an());for(let s of r.nameSet)bt(e,n,["isOption",s],i,["pushUndefined",r.preferredName]);for(let s=0;s<r.arity;++s){let a=wn(e,an());jt(e,i,Ve.EndOfInput,Le.ErrorNode,"setOptionArityError"),jt(e,i,Ve.EndOfPartialInput,Le.ErrorNode,"setOptionArityError"),bt(e,i,"isOptionLike",Le.ErrorNode,"setOptionArityError");let l=r.arity===1?"setStringValue":"pushStringValue";bt(e,i,"isNotOptionLike",a,l),i=a}lo(e,i,n)}}},Td=class t{static{o(this,"CliBuilder")}static build(e,n={}){return new t(n).commands(e).compile()}constructor({binaryName:e="..."}={}){this.builders=[],this.opts={binaryName:e}}getBuilderByIndex(e){if(!(e>=0&&e<this.builders.length))throw new Error(`Assertion failed: Out-of-bound command index (${e})`);return this.builders[e]}commands(e){for(let n of e)n(this.command());return this}command(){let e=new ep(this.builders.length,this.opts);return this.builders.push(e),e}compile(){let e=[],n=[];for(let i of this.builders){let{machine:s,context:a}=i.compile();e.push(s),n.push(a)}let r=q0(e);return B0(r),{machine:r,contexts:n,process:o((i,{partial:s}={})=>{let a=s?Ve.EndOfPartialInput:Ve.EndOfInput;return U0(r,i,{endToken:a})},"process")}}};var tp=Array(80).fill("\u2501");for(let t=0;t<=24;++t)tp[tp.length-t]=`\x1B[38;5;${232+t}m\u2501`;var Ev={header:o(t=>`\x1B[1m\u2501\u2501\u2501 ${t}${t.length<75?` ${tp.slice(t.length+5).join("")}`:":"}\x1B[0m`,"header"),bold:o(t=>`\x1B[1m${t}\x1B[22m`,"bold"),error:o(t=>`\x1B[31m\x1B[1m${t}\x1B[22m\x1B[39m`,"error"),code:o(t=>`\x1B[36m${t}\x1B[39m`,"code")},Rv={header:o(t=>t,"header"),bold:o(t=>t,"bold"),error:o(t=>t,"error"),code:o(t=>t,"code")};function Q0(t){let e=t.split(`
|
|
24
|
+
`),n=e.filter(i=>i.match(/\S/)),r=n.length>0?n.reduce((i,s)=>Math.min(i,s.length-s.trimStart().length),Number.MAX_VALUE):0;return e.map(i=>i.slice(r).trimRight()).join(`
|
|
25
|
+
`)}o(Q0,"dedent");function kn(t,{format:e,paragraphs:n}){return t=t.replace(/\r\n?/g,`
|
|
26
|
+
`),t=Q0(t),t=t.replace(/^\n+|\n+$/g,""),t=t.replace(/^(\s*)-([^\n]*?)\n+/gm,`$1-$2
|
|
27
|
+
|
|
28
|
+
`),t=t.replace(/\n(\n)?\n*/g,(r,i)=>i||" "),n&&(t=t.split(/\n/).map(r=>{let i=r.match(/^\s*[*-][\t ]+(.*)/);if(!i)return r.match(/(.{1,80})(?: |$)/g).join(`
|
|
29
|
+
`);let s=r.length-r.trimStart().length;return i[1].match(new RegExp(`(.{1,${78-s}})(?: |$)`,"g")).map((a,l)=>" ".repeat(s)+(l===0?"- ":" ")+a).join(`
|
|
30
|
+
`)}).join(`
|
|
31
|
+
|
|
32
|
+
`)),t=t.replace(/(`+)((?:.|[\n])*?)\1/g,(r,i,s)=>e.code(i+s+i)),t=t.replace(/(\*\*)((?:.|[\n])*?)\1/g,(r,i,s)=>e.bold(i+s+i)),t?`${t}
|
|
33
|
+
`:""}o(kn,"formatMarkdownish");var Id=class t extends I{static{o(this,"HelpCommand")}static from(e,n){let r=new t(n);r.path=e.path;for(let i of e.options)switch(i.name){case"-c":r.commands.push(Number(i.value));break;case"-i":r.index=Number(i.value);break}return r}constructor(e){super(),this.contexts=e,this.commands=[]}async execute(){let e=this.commands;if(typeof this.index<"u"&&this.index>=0&&this.index<e.length&&(e=[e[this.index]]),e.length===0)this.context.stdout.write(this.cli.usage());else if(e.length===1)this.context.stdout.write(this.cli.usage(this.contexts[e[0]].commandClass,{detailed:!0}));else if(e.length>1){this.context.stdout.write(`Multiple commands match your selection:
|
|
34
|
+
`),this.context.stdout.write(`
|
|
35
|
+
`);let n=0;for(let r of this.commands)this.context.stdout.write(this.cli.usage(this.contexts[r].commandClass,{prefix:`${n++}. `.padStart(5)}));this.context.stdout.write(`
|
|
36
|
+
`),this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.
|
|
37
|
+
`)}}};var Tv=Symbol("clipanion/errorCommand");var co=class t{static{o(this,"Cli")}static from(e,n={}){let r=new t(n),i=Array.isArray(e)?e:[e];for(let s of i)r.register(s);return r}constructor({binaryLabel:e,binaryName:n="...",binaryVersion:r,enableCapture:i=!1,enableColors:s}={}){this.registrations=new Map,this.builder=new Td({binaryName:n}),this.binaryLabel=e,this.binaryName=n,this.binaryVersion=r,this.enableCapture=i,this.enableColors=s}register(e){var n;if(this.registrations.has(e))throw new RangeError(`${e.name} has already been registered`);let r=new Map,i=new e;for(let d in i){let c=i[d];typeof c=="object"&&c!==null&&c[I.isOption]&&r.set(d,c)}let s=this.builder.command(),a=s.cliIndex,l=(n=e.paths)!==null&&n!==void 0?n:i.paths;if(typeof l<"u")for(let d of l)s.addPath(d);this.registrations.set(e,{specs:r,builder:s,index:a});for(let[d,{definition:c}]of r.entries())c(s,d);s.setContext({commandClass:e})}process(e,n){let{input:r,context:i,partial:s}=typeof e=="object"&&Array.isArray(e)?{input:e,context:n}:e,{contexts:a,process:l}=this.builder.compile(),d=l(r,{partial:s}),c={...t.defaultContext,...i};switch(d.selectedIndex){case qr:{let u=Id.from(d,a);return u.context=c,u.tokens=d.tokens,u}default:{let{commandClass:u}=a[d.selectedIndex],f=this.registrations.get(u);if(typeof f>"u")throw new Error("Assertion failed: Expected the command class to have been registered.");let h=new u;h.context=c,h.tokens=d.tokens,h.path=d.path;try{for(let[g,{transformer:b}]of f.specs.entries())h[g]=b(f.builder,g,d,c);return h}catch(g){throw g[Tv]=h,g}}break}}async run(e,n){var r,i;let s,a={...t.defaultContext,...n},l=(r=this.enableColors)!==null&&r!==void 0?r:a.colorDepth>1;if(!Array.isArray(e))s=e;else try{s=this.process(e,a)}catch(u){return a.stdout.write(this.error(u,{colored:l})),1}if(s.help)return a.stdout.write(this.usage(s,{colored:l,detailed:!0})),0;s.context=a,s.cli={binaryLabel:this.binaryLabel,binaryName:this.binaryName,binaryVersion:this.binaryVersion,enableCapture:this.enableCapture,enableColors:this.enableColors,definitions:o(()=>this.definitions(),"definitions"),definition:o(u=>this.definition(u),"definition"),error:o((u,f)=>this.error(u,f),"error"),format:o(u=>this.format(u),"format"),process:o((u,f)=>this.process(u,{...a,...f}),"process"),run:o((u,f)=>this.run(u,{...a,...f}),"run"),usage:o((u,f)=>this.usage(u,f),"usage")};let d=this.enableCapture&&(i=kv(a))!==null&&i!==void 0?i:Iv,c;try{c=await d(()=>s.validateAndExecute().catch(u=>s.catch(u).then(()=>0)))}catch(u){return a.stdout.write(this.error(u,{colored:l,command:s})),1}return c}async runExit(e,n){process.exitCode=await this.run(e,n)}definition(e,{colored:n=!1}={}){if(!e.usage)return null;let{usage:r}=this.getUsageByRegistration(e,{detailed:!1}),{usage:i,options:s}=this.getUsageByRegistration(e,{detailed:!0,inlineOptions:!1}),a=typeof e.usage.category<"u"?kn(e.usage.category,{format:this.format(n),paragraphs:!1}):void 0,l=typeof e.usage.description<"u"?kn(e.usage.description,{format:this.format(n),paragraphs:!1}):void 0,d=typeof e.usage.details<"u"?kn(e.usage.details,{format:this.format(n),paragraphs:!0}):void 0,c=typeof e.usage.examples<"u"?e.usage.examples.map(([u,f])=>[kn(u,{format:this.format(n),paragraphs:!1}),f.replace(/\$0/g,this.binaryName)]):void 0;return{path:r,usage:i,category:a,description:l,details:d,examples:c,options:s}}definitions({colored:e=!1}={}){let n=[];for(let r of this.registrations.keys()){let i=this.definition(r,{colored:e});i&&n.push(i)}return n}usage(e=null,{colored:n,detailed:r=!1,prefix:i="$ "}={}){var s;if(e===null){for(let d of this.registrations.keys()){let c=d.paths,u=typeof d.usage<"u";if(!c||c.length===0||c.length===1&&c[0].length===0||((s=c?.some(g=>g.length===0))!==null&&s!==void 0?s:!1))if(e){e=null;break}else e=d;else if(u){e=null;continue}}e&&(r=!0)}let a=e!==null&&e instanceof I?e.constructor:e,l="";if(a)if(r){let{description:d="",details:c="",examples:u=[]}=a.usage||{};d!==""&&(l+=kn(d,{format:this.format(n),paragraphs:!1}).replace(/^./,g=>g.toUpperCase()),l+=`
|
|
38
|
+
`),(c!==""||u.length>0)&&(l+=`${this.format(n).header("Usage")}
|
|
39
|
+
`,l+=`
|
|
40
|
+
`);let{usage:f,options:h}=this.getUsageByRegistration(a,{inlineOptions:!1});if(l+=`${this.format(n).bold(i)}${f}
|
|
41
|
+
`,h.length>0){l+=`
|
|
42
|
+
`,l+=`${this.format(n).header("Options")}
|
|
43
|
+
`;let g=h.reduce((b,y)=>Math.max(b,y.definition.length),0);l+=`
|
|
44
|
+
`;for(let{definition:b,description:y}of h)l+=` ${this.format(n).bold(b.padEnd(g))} ${kn(y,{format:this.format(n),paragraphs:!1})}`}if(c!==""&&(l+=`
|
|
45
|
+
`,l+=`${this.format(n).header("Details")}
|
|
46
|
+
`,l+=`
|
|
47
|
+
`,l+=kn(c,{format:this.format(n),paragraphs:!0})),u.length>0){l+=`
|
|
48
|
+
`,l+=`${this.format(n).header("Examples")}
|
|
49
|
+
`;for(let[g,b]of u)l+=`
|
|
50
|
+
`,l+=kn(g,{format:this.format(n),paragraphs:!1}),l+=`${b.replace(/^/m,` ${this.format(n).bold(i)}`).replace(/\$0/g,this.binaryName)}
|
|
51
|
+
`}}else{let{usage:d}=this.getUsageByRegistration(a);l+=`${this.format(n).bold(i)}${d}
|
|
52
|
+
`}else{let d=new Map;for(let[h,{index:g}]of this.registrations.entries()){if(typeof h.usage>"u")continue;let b=typeof h.usage.category<"u"?kn(h.usage.category,{format:this.format(n),paragraphs:!1}):null,y=d.get(b);typeof y>"u"&&d.set(b,y=[]);let{usage:w}=this.getUsageByIndex(g);y.push({commandClass:h,usage:w})}let c=Array.from(d.keys()).sort((h,g)=>h===null?-1:g===null?1:h.localeCompare(g,"en",{usage:"sort",caseFirst:"upper"})),u=typeof this.binaryLabel<"u",f=typeof this.binaryVersion<"u";u||f?(u&&f?l+=`${this.format(n).header(`${this.binaryLabel} - ${this.binaryVersion}`)}
|
|
53
|
+
|
|
54
|
+
`:u?l+=`${this.format(n).header(`${this.binaryLabel}`)}
|
|
55
|
+
`:l+=`${this.format(n).header(`${this.binaryVersion}`)}
|
|
56
|
+
`,l+=` ${this.format(n).bold(i)}${this.binaryName} <command>
|
|
57
|
+
`):l+=`${this.format(n).bold(i)}${this.binaryName} <command>
|
|
58
|
+
`;for(let h of c){let g=d.get(h).slice().sort((y,w)=>y.usage.localeCompare(w.usage,"en",{usage:"sort",caseFirst:"upper"})),b=h!==null?h.trim():"General commands";l+=`
|
|
59
|
+
`,l+=`${this.format(n).header(`${b}`)}
|
|
60
|
+
`;for(let{commandClass:y,usage:w}of g){let S=y.usage.description||"undocumented";l+=`
|
|
61
|
+
`,l+=` ${this.format(n).bold(w)}
|
|
62
|
+
`,l+=` ${kn(S,{format:this.format(n),paragraphs:!1})}`}}l+=`
|
|
63
|
+
`,l+=kn("You can also print more details about any of these commands by calling them with the `-h,--help` flag right after the command name.",{format:this.format(n),paragraphs:!0})}return l}error(e,n){var r,{colored:i,command:s=(r=e[Tv])!==null&&r!==void 0?r:null}=n===void 0?{}:n;(!e||typeof e!="object"||!("stack"in e))&&(e=new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(e)})`));let a="",l=e.name.replace(/([a-z])([A-Z])/g,"$1 $2");l==="Error"&&(l="Internal Error"),a+=`${this.format(i).error(l)}: ${e.message}
|
|
64
|
+
`;let d=e.clipanion;return typeof d<"u"?d.type==="usage"&&(a+=`
|
|
65
|
+
`,a+=this.usage(s)):e.stack&&(a+=`${e.stack.replace(/^.*\n/,"")}
|
|
66
|
+
`),a}format(e){var n;return((n=e??this.enableColors)!==null&&n!==void 0?n:t.defaultContext.colorDepth>1)?Ev:Rv}getUsageByRegistration(e,n){let r=this.registrations.get(e);if(typeof r>"u")throw new Error("Assertion failed: Unregistered command");return this.getUsageByIndex(r.index,n)}getUsageByIndex(e,n){return this.builder.getBuilderByIndex(e).usage(n)}};co.defaultContext={env:process.env,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,colorDepth:wv()};function Iv(t){return t()}o(Iv,"noopCaptureActivator");var xs={};lv(xs,{DefinitionsCommand:()=>ws,HelpCommand:()=>ks,TokensCommand:()=>vs,VersionCommand:()=>Ss});var ws=class extends I{static{o(this,"DefinitionsCommand")}async execute(){this.context.stdout.write(`${JSON.stringify(this.cli.definitions(),null,2)}
|
|
67
|
+
`)}};ws.paths=[["--clipanion=definitions"]];var ks=class extends I{static{o(this,"HelpCommand")}async execute(){this.context.stdout.write(this.cli.usage())}};ks.paths=[["-h"],["--help"]];function $d(t={}){return Jt({definition(e,n){var r;e.addProxy({name:(r=t.name)!==null&&r!==void 0?r:n,required:t.required})},transformer(e,n,r){return r.positionals.map(({value:i})=>i)}})}o($d,"Proxy");var vs=class extends I{static{o(this,"TokensCommand")}constructor(){super(...arguments),this.args=$d()}async execute(){this.context.stdout.write(`${JSON.stringify(this.cli.process(this.args).tokens,null,2)}
|
|
68
|
+
`)}};vs.paths=[["--clipanion=tokens"]];var Ss=class extends I{static{o(this,"VersionCommand")}async execute(){var e;this.context.stdout.write(`${(e=this.cli.binaryVersion)!==null&&e!==void 0?e:"<unknown>"}
|
|
69
|
+
`)}};Ss.paths=[["-v"],["--version"]];var p={};lv(p,{Array:()=>$v,Boolean:()=>_v,Counter:()=>Ov,Proxy:()=>$d,Rest:()=>Cv,String:()=>Pv,applyValidator:()=>wi,cleanValidationError:()=>Sd,formatError:()=>gs,isOptionSymbol:()=>hs,makeCommandOption:()=>Jt,rerouteArguments:()=>zn});function $v(t,e,n){let[r,i]=zn(e,n??{}),{arity:s=1}=i,a=t.split(","),l=new Set(a);return Jt({definition(d){d.addOption({names:a,arity:s,hidden:i?.hidden,description:i?.description,required:i.required})},transformer(d,c,u){let f,h=typeof r<"u"?[...r]:void 0;for(let{name:g,value:b}of u.options)l.has(g)&&(f=g,h=h??[],h.push(b));return typeof h<"u"?wi(f??c,h,i.validator):h}})}o($v,"Array");function _v(t,e,n){let[r,i]=zn(e,n??{}),s=t.split(","),a=new Set(s);return Jt({definition(l){l.addOption({names:s,allowBinding:!1,arity:0,hidden:i.hidden,description:i.description,required:i.required})},transformer(l,d,c){let u=r;for(let{name:f,value:h}of c.options)a.has(f)&&(u=h);return u}})}o(_v,"Boolean");function Ov(t,e,n){let[r,i]=zn(e,n??{}),s=t.split(","),a=new Set(s);return Jt({definition(l){l.addOption({names:s,allowBinding:!1,arity:0,hidden:i.hidden,description:i.description,required:i.required})},transformer(l,d,c){let u=r;for(let{name:f,value:h}of c.options)a.has(f)&&(u??(u=0),h?u+=1:u=0);return u}})}o(Ov,"Counter");function Cv(t={}){return Jt({definition(e,n){var r;e.addRest({name:(r=t.name)!==null&&r!==void 0?r:n,required:t.required})},transformer(e,n,r){let i=o(a=>{let l=r.positionals[a];return l.extra===fn||l.extra===!1&&a<e.arity.leading.length},"isRestPositional"),s=0;for(;s<r.positionals.length&&i(s);)s+=1;return r.positionals.splice(0,s).map(({value:a})=>a)}})}o(Cv,"Rest");function Y0(t,e,n){let[r,i]=zn(e,n??{}),{arity:s=1}=i,a=t.split(","),l=new Set(a);return Jt({definition(d){d.addOption({names:a,arity:i.tolerateBoolean?0:s,hidden:i.hidden,description:i.description,required:i.required})},transformer(d,c,u,f){let h,g=r;typeof i.env<"u"&&f.env[i.env]&&(h=i.env,g=f.env[i.env]);for(let{name:b,value:y}of u.options)l.has(b)&&(h=b,g=y);return typeof g=="string"?wi(h??c,g,i.validator):g}})}o(Y0,"StringOption");function J0(t={}){let{required:e=!0}=t;return Jt({definition(n,r){var i;n.addPositional({name:(i=t.name)!==null&&i!==void 0?i:r,required:t.required})},transformer(n,r,i){var s;for(let a=0;a<i.positionals.length;++a){if(i.positionals[a].extra===fn||e&&i.positionals[a].extra===!0||!e&&i.positionals[a].extra===!1)continue;let[l]=i.positionals.splice(a,1);return wi((s=t.name)!==null&&s!==void 0?s:r,l.value,t.validator)}}})}o(J0,"StringPositional");function Pv(t,...e){return typeof t=="string"?Y0(t,...e):J0(t)}o(Pv,"String");function Nv(t){return t[0]==="--"?t.slice(1):[...t]}o(Nv,"stripLauncherSeparator");import{existsSync as hM,writeFileSync as gM}from"node:fs";var Qn=[],vn=[],Z0=Uint8Array,np="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ki=0,Dv=np.length;ki<Dv;++ki)Qn[ki]=np[ki],vn[np.charCodeAt(ki)]=ki;var ki,Dv;vn[45]=62;vn[95]=63;function X0(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}o(X0,"getLens");function eD(t,e,n){return(e+n)*3/4-n}o(eD,"_byteLength");function _d(t){var e,n=X0(t),r=n[0],i=n[1],s=new Z0(eD(t,r,i)),a=0,l=i>0?r-4:r,d;for(d=0;d<l;d+=4)e=vn[t.charCodeAt(d)]<<18|vn[t.charCodeAt(d+1)]<<12|vn[t.charCodeAt(d+2)]<<6|vn[t.charCodeAt(d+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return i===2&&(e=vn[t.charCodeAt(d)]<<2|vn[t.charCodeAt(d+1)]>>4,s[a++]=e&255),i===1&&(e=vn[t.charCodeAt(d)]<<10|vn[t.charCodeAt(d+1)]<<4|vn[t.charCodeAt(d+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}o(_d,"toByteArray");function tD(t){return Qn[t>>18&63]+Qn[t>>12&63]+Qn[t>>6&63]+Qn[t&63]}o(tD,"tripletToBase64");function nD(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(tD(r));return i.join("")}o(nD,"encodeChunk");function uo(t){for(var e,n=t.length,r=n%3,i=[],s=16383,a=0,l=n-r;a<l;a+=s)i.push(nD(t,a,a+s>l?l:a+s));return r===1?(e=t[n-1],i.push(Qn[e>>2]+Qn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(Qn[e>>10]+Qn[e>>4&63]+Qn[e<<2&63]+"=")),i.join("")}o(uo,"fromByteArray");function ip(t){let e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}o(ip,"isSimpleObject");var rD=!0,fo=BigInt("-9223372036854775808"),Cd=BigInt("9223372036854775807"),ap=BigInt("0"),iD=BigInt("8"),oD=BigInt("256"),op="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",Si=class{static{o(this,"CommitTsPlaceholder")}[Symbol.toPrimitive](e){if(e==="string")return this.toString();throw new Error(op)}valueOf(){throw new Error(op)}toJSON(){throw new Error(op)}toString(){return"[unresolved commit timestamp]"}},sD=new Si;function aD(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}o(aD,"isSpecial");function lD(t){t<ap&&(t-=fo+fo);let e=t.toString(16);e.length%2===1&&(e="0"+e);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=iD;return uo(n)}o(lD,"slowBigIntToBase64");function dD(t){let e=_d(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=ap,r=ap;for(let i of e)n+=BigInt(i)*oD**r,r++;return n>Cd&&(n+=fo+fo),n}o(dD,"slowBase64ToBigInt");function cD(t){if(t<fo||Cd<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);let e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),uo(new Uint8Array(e))}o(cD,"modernBigIntToBase64");function uD(t){let e=_d(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}o(uD,"modernBase64ToBigInt");var fD=DataView.prototype.setBigInt64?cD:lD,$z=DataView.prototype.getBigInt64?uD:dD,Fv=1024;function Lv(t){if(t.length>Fv)throw new Error(`Field name ${t} exceeds maximum field name length ${Fv}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}o(Lv,"validateObjectField");var Mv=16384;function vi(t){let e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="function"?"[Function]":typeof r=="symbol"?String(r):typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Mv){let n="[...truncated]",r=Mv-n.length,i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}o(vi,"stringifyValueForError");function Od(t,e,n,r){if(t===void 0){let a=n&&` (present at path ${n} in original object ${vi(e)})`;throw new Error(`undefined is not a valid Convex value${a}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<fo||Cd<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:fD(t)}}if(typeof t=="number")if(aD(t)){let a=new ArrayBuffer(8);return new DataView(a).setFloat64(0,t,rD),{$float:uo(new Uint8Array(a))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:uo(new Uint8Array(t))};if(t instanceof Si)return{$commitTs:null};if(Array.isArray(t))return t.map((a,l)=>Od(a,e,n+`[${l}]`,!1));if(t instanceof Set)throw new Error(sp(n,"Set",[...t],e));if(t instanceof Map)throw new Error(sp(n,"Map",[...t],e));if(!ip(t)){let a=t?.constructor?.name,l=a?`${a} `:"";throw new Error(sp(n,l,t,e))}let i={},s=Object.entries(t);s.sort(([a,l],[d,c])=>a===d?0:a<d?-1:1);for(let[a,l]of s)l!==void 0?(Lv(a),i[a]=Od(l,e,n+`.${a}`,!1)):r&&(Lv(a),i[a]=pD(l,e,n+`.${a}`));return i}o(Od,"convexToJsonInternal");function sp(t,e,n,r){return t?`${e}${vi(n)} is not a supported Convex type (present at path ${t} in original object ${vi(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${vi(n)} is not a supported Convex type.`}o(sp,"errorMessageForUnsupportedType");function pD(t,e,n){if(t===void 0)return{$undefined:null};if(e===void 0)throw new Error(`Programming error. Current value is ${vi(t)} but original value is undefined`);return Od(t,e,n,!1)}o(pD,"convexOrUndefinedToJsonInternal");function Sn(t){return Od(t,t,"",!1)}o(Sn,"convexToJson");var mD=Object.defineProperty,hD=o((t,e,n)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),ze=o((t,e,n)=>hD(t,typeof e!="symbol"?e+"":e,n),"__publicField"),gD="https://docs.convex.dev/error#undefined-validator";function As(t,e){let n=e!==void 0?` for field "${e}"`:"";throw new Error(`A validator is undefined${n} in ${t}. This is often caused by circular imports. See ${gD} for details.`)}o(As,"throwUndefinedValidatorError");var Gt=class{static{o(this,"BaseValidator")}constructor({isOptional:e}){ze(this,"type"),ze(this,"fieldPaths"),ze(this,"isOptional"),ze(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}},Pd=class t extends Gt{static{o(this,"VId")}constructor({isOptional:e,tableName:n}){if(super({isOptional:e}),ze(this,"tableName"),ze(this,"kind","id"),typeof n!="string")throw new Error("v.id(tableName) requires a string");this.tableName=n}get json(){return{type:"id",tableName:this.tableName}}optional(){return new t({isOptional:"optional",tableName:this.tableName})}asOptional(){return this.optional()}},Es=class t extends Gt{static{o(this,"VFloat64")}constructor(){super(...arguments),ze(this,"kind","float64")}get json(){return{type:"number"}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Rs=class t extends Gt{static{o(this,"VInt64")}constructor(){super(...arguments),ze(this,"kind","int64")}get json(){return{type:"bigint"}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Nd=class t extends Gt{static{o(this,"VCommitTs")}constructor(){super(...arguments),ze(this,"kind","commitTs")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Dd=class t extends Gt{static{o(this,"VBoolean")}constructor(){super(...arguments),ze(this,"kind","boolean")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Fd=class t extends Gt{static{o(this,"VBytes")}constructor(){super(...arguments),ze(this,"kind","bytes")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Ld=class t extends Gt{static{o(this,"VString")}constructor(){super(...arguments),ze(this,"kind","string")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Md=class t extends Gt{static{o(this,"VNull")}constructor(){super(...arguments),ze(this,"kind","null")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},qd=class t extends Gt{static{o(this,"VAny")}constructor(){super(...arguments),ze(this,"kind","any")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},Bd=class t extends Gt{static{o(this,"VObject")}constructor({isOptional:e,fields:n}){super({isOptional:e}),ze(this,"fields"),ze(this,"kind","object"),globalThis.Object.entries(n).forEach(([r,i])=>{if(i===void 0&&As("v.object()",r),!i.isConvexValidator)throw new Error("v.object() entries must be validators")}),this.fields=n}get json(){return{type:this.kind,value:globalThis.Object.fromEntries(globalThis.Object.entries(this.fields).map(([e,n])=>[e,{fieldType:n.json,optional:n.isOptional==="optional"}]))}}optional(){return new t({isOptional:"optional",fields:this.fields})}asOptional(){return this.optional()}omit(...e){let n={...this.fields};for(let r of e)delete n[r];return new t({isOptional:this.isOptional,fields:n})}pick(...e){let n={};for(let r of e)n[r]=this.fields[r];return new t({isOptional:this.isOptional,fields:n})}partial(){let e={};for(let[n,r]of globalThis.Object.entries(this.fields))e[n]=r.asOptional();return new t({isOptional:this.isOptional,fields:e})}extend(e){return new t({isOptional:this.isOptional,fields:{...this.fields,...e}})}},Vd=class t extends Gt{static{o(this,"VLiteral")}constructor({isOptional:e,value:n}){if(super({isOptional:e}),ze(this,"value"),ze(this,"kind","literal"),typeof n!="string"&&typeof n!="boolean"&&typeof n!="number"&&typeof n!="bigint")throw new Error("v.literal(value) must be a string, number, or boolean");this.value=n}get json(){return{type:this.kind,value:Sn(this.value)}}optional(){return new t({isOptional:"optional",value:this.value})}asOptional(){return this.optional()}},Kd=class t extends Gt{static{o(this,"VArray")}constructor({isOptional:e,element:n}){super({isOptional:e}),ze(this,"element"),ze(this,"kind","array"),n===void 0&&As("v.array()"),this.element=n}get json(){return{type:this.kind,value:this.element.json}}optional(){return new t({isOptional:"optional",element:this.element})}asOptional(){return this.optional()}},Ud=class t extends Gt{static{o(this,"VRecord")}constructor({isOptional:e,key:n,value:r}){if(super({isOptional:e}),ze(this,"key"),ze(this,"value"),ze(this,"kind","record"),n===void 0&&As("v.record()","key"),r===void 0&&As("v.record()","value"),n.isOptional==="optional")throw new Error("Record validator cannot have optional keys");if(r.isOptional==="optional")throw new Error("Record validator cannot have optional values");if(!n.isConvexValidator||!r.isConvexValidator)throw new Error("Key and value of v.record() must be validators");this.key=n,this.value=r}get json(){return{type:this.kind,keys:this.key.json,values:{fieldType:this.value.json,optional:!1}}}optional(){return new t({isOptional:"optional",key:this.key,value:this.value})}asOptional(){return this.optional()}},jd=class t extends Gt{static{o(this,"VUnion")}constructor({isOptional:e,members:n}){super({isOptional:e}),ze(this,"members"),ze(this,"kind","union"),n.forEach((r,i)=>{if(r===void 0&&As("v.union()",`member at index ${i}`),!r.isConvexValidator)throw new Error("All members of v.union() must be validators")}),this.members=n}get json(){return{type:this.kind,value:this.members.map(e=>e.json)}}optional(){return new t({isOptional:"optional",members:this.members})}asOptional(){return this.optional()}};function Gd(t){return t?.isConvexValidator===!0}o(Gd,"isValidator");var D={id:o(t=>new Pd({isOptional:"required",tableName:t}),"id"),null:o(()=>new Md({isOptional:"required"}),"null"),number:o(()=>new Es({isOptional:"required"}),"number"),float64:o(()=>new Es({isOptional:"required"}),"float64"),bigint:o(()=>new Rs({isOptional:"required"}),"bigint"),int64:o(()=>new Rs({isOptional:"required"}),"int64"),commitTs:o(()=>new Nd({isOptional:"required"}),"commitTs"),boolean:o(()=>new Dd({isOptional:"required"}),"boolean"),string:o(()=>new Ld({isOptional:"required"}),"string"),bytes:o(()=>new Fd({isOptional:"required"}),"bytes"),literal:o(t=>new Vd({isOptional:"required",value:t}),"literal"),array:o(t=>new Kd({isOptional:"required",element:t}),"array"),object:o(t=>new Bd({isOptional:"required",fields:t}),"object"),record:o((t,e)=>new Ud({isOptional:"required",key:t,value:e}),"record"),union:o((...t)=>new jd({isOptional:"required",members:t}),"union"),any:o(()=>new qd({isOptional:"required"}),"any"),optional:o(t=>t.asOptional(),"optional"),nullable:o(t=>D.union(t,D.null()),"nullable")};var yD=Object.defineProperty,bD=o((t,e,n)=>e in t?yD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),lp=o((t,e,n)=>bD(t,typeof e!="symbol"?e+"":e,n),"__publicField"),qv,Bv,wD=Symbol.for("ConvexError"),Kr=class extends(Bv=Error,qv=wD,Bv){static{o(this,"ConvexError")}constructor(e){super(typeof e=="string"?e:vi(e)),lp(this,"name","ConvexError"),lp(this,"data"),lp(this,qv,!0),this.data=e}};var Vv=o(()=>Array.from({length:4},()=>0),"arr"),Vz=Vv(),Kz=Vv();var Wd=class extends Kr{static{o(this,"RefusalError")}constructor(e,n){super({code:e,message:n}),this.message=n}};function ke(t,e){throw new Wd(t,e)}o(ke,"refuse");function W(t,e){throw new Error(t,e)}o(W,"bug");function vD(t){return typeof t=="object"&&t!==null&&Symbol.for("ConvexError")in t}o(vD,"isConvexError");function zd(t){if(!vD(t))return null;let e=t.data;if(typeof e=="string")return{code:null,message:e};if(e&&typeof e=="object"){let{code:n,message:r}=e;return{code:typeof n=="string"?n:null,message:typeof r=="string"?r:""}}return null}o(zd,"refusalOf");function dp(t){let e=zd(t);if(e!==null&&e.message!=="")return e.message;let n=t instanceof Error?t.message:String(t),r=/\[Request ID:\s*([0-9a-f]+)\]/i.exec(n)?.[1],i=n.replace(/\[CONVEX[^\]]*\]/g,"").replace(/\[Request ID:[^\]]*\]/gi,"").replace(/\bServer Error\b/gi,"").replace(/\bCalled by client\b/g,"").trim();return r!==void 0&&i===""?`Serverfehler (Request-ID ${r}) \u2014 Details in GlitchTip.`:n}o(dp,"describeServerFailure");var cp=["month","year","once","unit"];function Hd(t){(!Number.isSafeInteger(t)||t<0)&&ke("INVALID","Betr\xE4ge m\xFCssen nichtnegative ganze Centbetr\xE4ge sein.")}o(Hd,"assertMoney");function Kv(t,e){if(Object.keys(e).some(n=>!["percent","amountMinor"].includes(n))&&ke("INVALID","Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag."),t==="percent"&&"percent"in e&&!("amountMinor"in e)){(!Number.isFinite(e.percent)||e.percent<0||e.percent>100)&&ke("INVALID","Prozentwerte m\xFCssen zwischen 0 und 100 liegen.");return}if(t==="absolute"&&"amountMinor"in e&&!("percent"in e))return Hd(e.amountMinor);ke("INVALID","Die Erm\xE4\xDFigung braucht genau eine Prozentregel oder einen Centbetrag.")}o(Kv,"validateRule");import{existsSync as GD,readFileSync as WD}from"node:fs";import Ts from"node:path";var up=Symbol.for("functionName");var Uv=Symbol.for("toReferencePath");var V4=D.object({numItems:D.number(),cursor:D.union(D.string(),D.null()),endCursor:D.optional(D.union(D.string(),D.null())),id:D.optional(D.number()),maximumRowsRead:D.optional(D.number()),maximumBytesRead:D.optional(D.number())});function Gv(t=[]){let e={get(n,r){if(typeof r=="string"){let i=[...t,r];return Gv(i)}else if(r===up){if(t.length<2){let a=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}let i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}o(Gv,"createApi");var Qd=Gv();function Wv(t,e){let n={get(r,i){if(typeof i=="string"){let s=[...e,i];return Wv(t,s)}else if(i===Uv){if(e.length<1){let s=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${s}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}o(Wv,"createChildComponents");var pp=o(()=>Wv("components",[]),"componentsGeneric");var AD=Symbol("var.requestId"),ED=Symbol("var.ip"),RD=Symbol("var.userAgent"),TD=Symbol("var.now"),ID=Symbol("var.convexActor"),$D={[AD]:"requestId",[ED]:"ip",[RD]:"userAgent",[TD]:"now",[ID]:"convexActor"};var _D=Object.defineProperty,OD=o((t,e,n)=>e in t?_D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),Nn=o((t,e,n)=>OD(t,typeof e!="symbol"?e+"":e,n),"__publicField"),Jd=class{static{o(this,"TableDefinition")}constructor(e){Nn(this,"indexes"),Nn(this,"stagedDbIndexes"),Nn(this,"searchIndexes"),Nn(this,"stagedSearchIndexes"),Nn(this,"vectorIndexes"),Nn(this,"stagedVectorIndexes"),Nn(this,"validator"),Nn(this,"stagedValidator"),this.indexes=[],this.stagedDbIndexes=[],this.searchIndexes=[],this.stagedSearchIndexes=[],this.vectorIndexes=[],this.stagedVectorIndexes=[],this.validator=e}" indexes"(){return this.indexes}index(e,n){return Array.isArray(n)?this.indexes.push({indexDescriptor:e,fields:n}):n.staged?this.stagedDbIndexes.push({indexDescriptor:e,fields:n.fields}):this.indexes.push({indexDescriptor:e,fields:n.fields}),this}searchIndex(e,n){return n.staged?this.stagedSearchIndexes.push({indexDescriptor:e,searchField:n.searchField,filterFields:n.filterFields||[]}):this.searchIndexes.push({indexDescriptor:e,searchField:n.searchField,filterFields:n.filterFields||[]}),this}vectorIndex(e,n){return n.staged?this.stagedVectorIndexes.push({indexDescriptor:e,vectorField:n.vectorField,dimensions:n.dimensions,filterFields:n.filterFields||[]}):this.vectorIndexes.push({indexDescriptor:e,vectorField:n.vectorField,dimensions:n.dimensions,filterFields:n.filterFields||[]}),this}staged(e){if(this.stagedValidator!==void 0)throw new Error("Table cannot have more than one staged validator.");if(Gd(e))this.stagedValidator=e;else{if(this.validator.kind!=="object"&&this.validator.kind!=="any")throw new Error("Specifying top-level field changes is only supported for simple table definitions. For a table defined with a union or record validator, you must stage a fully defined object or union validator.");let n=this.validator.kind==="object"?this.validator.fields:{},r=Object.fromEntries(Object.entries({...n,...e}).filter(i=>i[1]!==void 0));this.stagedValidator=D.object(r)}return this.self()}self(){return this}export(){let e=this.validator.json;if(typeof e!="object")throw new Error("Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)");let n;if(this.stagedValidator!==void 0&&(n=this.stagedValidator.json,typeof n!="object"))throw new Error("Invalid staged validator: please make sure that the parameter of `.staged()` is valid (see https://docs.convex.dev/database/schemas)");return{indexes:this.indexes,stagedDbIndexes:this.stagedDbIndexes,searchIndexes:this.searchIndexes,stagedSearchIndexes:this.stagedSearchIndexes,vectorIndexes:this.vectorIndexes,stagedVectorIndexes:this.stagedVectorIndexes,documentType:e,stagedDocumentType:n}}};function mp(t){return Gd(t)?new Jd(t):new Jd(D.object(t))}o(mp,"defineTable");function Hv(t,e){switch(e.kind){case"object":return e.extend({_id:D.id(t),_creationTime:D.number()});case"union":return D.union(...e.members.map(n=>Hv(t,n)));case"any":return e;default:throw new Error(`Invalid validator for table "${t}": a table's documents must be objects, or a union of objects (see https://docs.convex.dev/database/schemas)`)}}o(Hv,"addSystemFields");function Qv(t,e){return Hv(t,e.validator)}o(Qv,"docValidator");function zv(t,e){let n=t.tables[e];if(n===void 0)throw new Error(`Table "${e}" is not in this schema. Tables in this schema: ${Object.keys(t.tables).join(", ")}`);return n}o(zv,"tableInSchema");var hp=class{static{o(this,"SchemaDefinition")}constructor(e,n){Nn(this,"tables"),Nn(this,"strictTableNameTypes"),Nn(this,"schemaValidation"),this.tables=e,this.schemaValidation=n?.schemaValidation===void 0?!0:n.schemaValidation}doc(e){return Qv(e,zv(this,e))}id(e){return zv(this,e),D.id(e)}export(){return JSON.stringify({tables:Object.entries(this.tables).map(([e,n])=>{let{indexes:r,stagedDbIndexes:i,searchIndexes:s,stagedSearchIndexes:a,vectorIndexes:l,stagedVectorIndexes:d,documentType:c,stagedDocumentType:u}=n.export();return{tableName:e,indexes:r,stagedDbIndexes:i,searchIndexes:s,stagedSearchIndexes:a,vectorIndexes:l,stagedVectorIndexes:d,documentType:c,stagedDocumentType:u}}),schemaValidation:this.schemaValidation})}};function Yv(t,e){return new hp(t,e)}o(Yv,"defineSchema");var xQ=Yv({_scheduled_functions:mp({name:D.string(),args:D.array(D.any()),scheduledTime:D.float64(),completedTime:D.optional(D.float64()),state:D.union(D.object({kind:D.literal("pending")}),D.object({kind:D.literal("inProgress")}),D.object({kind:D.literal("success")}),D.object({kind:D.literal("failed"),error:D.string()}),D.object({kind:D.literal("canceled")}))}),_storage:mp({sha256:D.string(),size:D.float64(),contentType:D.optional(D.string())})});var R=Qd,xt=Qd,lY=pp();var CD=/^[a-z][a-z0-9_-]{0,63}$/;function Jv(t){return CD.test(t)}o(Jv,"isTemplateConfigKey");import{createHash as qD}from"node:crypto";import{readFile as BD}from"node:fs/promises";import gp from"node:path";import{inflateRawSync as VD}from"node:zlib";var PD=/{{\s*([^{}]+?)\s*}}|<<\s*([^<>]+?)\s*>>/g,ND=/^[#/]\s*/;function DD(t){let e=t.trim(),n=e.match(/^{{\s*([^{}]+?)\s*}}$/);if(n)return n[1]?.trim()??e;let r=e.match(/^<<\s*([^<>]+?)\s*>>$/);return r?r[1]?.trim()??e:e}o(DD,"innerTemplatePlaceholder");function Zd(t){return DD(t).replace(ND,"")}o(Zd,"normalizeTemplatePlaceholderKey");function FD(t){return Zd(t).toLowerCase()}o(FD,"canonicalTemplatePlaceholderKey");function Zv(t){let e=new Map;for(let n of LD(t))e.has(n.key)||e.set(n.key,n.placeholder);return Array.from(e.entries()).sort(([n],[r])=>n.localeCompare(r,"de")).map(([,n])=>n)}o(Zv,"extractTemplatePlaceholders");function LD(t){let e=[];for(let n of t.matchAll(PD)){let r=Zd(n[1]??n[2]??"");r&&e.push({key:FD(r),placeholder:n[0].trim()})}return e}o(LD,"extractTemplatePlaceholderOccurrences");var Xv=/^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/;function MD(t){return t.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#(\d+);/g,(e,n)=>String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi,(e,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&/g,"&")}o(MD,"templateXmlText");function eS(t){return t.map(MD).join(`
|
|
70
|
+
`)}o(eS,"templateTextFromParts");var KD="application/vnd.openxmlformats-officedocument.wordprocessingml.document";async function Ai(t){let e=gp.resolve(t);if(!e.toLowerCase().endsWith(".docx"))throw new Error("Word templates must be a .docx file.");let n=new Uint8Array(await BD(e));return{file:e,bytes:n,sha256:qD("sha256").update(n).digest("base64"),placeholders:Zv(UD(n)).map(Zd)}}o(Ai,"readLocalDocx");async function ho(t,e,n,r){let i=await t.query(R.templates.roleOptions,{client:e}),s=i.find(d=>d.key===r.role);if(s===void 0)throw new Error(`Unknown leaf role "${r.role}". Available: ${i.map(d=>d.key).join(", ")}`);let a=await nS(t,e,n),{templateId:l}=await t.action(R.templateFileActions.create,{client:e,name:r.name,roleId:s.id,storageId:a,filename:gp.basename(n.file),...r.configKey===void 0?{}:{configKey:r.configKey},...r.icon===void 0?{}:{icon:r.icon},...r.fileNamePattern===void 0?{}:{fileNamePattern:r.fileNamePattern}});return l}o(ho,"uploadDocumentTemplate");async function tS(t,e,n,r){let i=await nS(t,e,r);await t.action(R.templateFileActions.replaceFile,{client:e,templateId:n,storageId:i,filename:gp.basename(r.file)})}o(tS,"replaceDocumentTemplateFile");async function nS(t,e,n){let{uploadUrl:r,uploadTicket:i}=await t.mutation(R.templates.generateUploadUrl,{client:e}),s=await t.upload(r,n.bytes,KD);return await t.mutation(R.uploads.registerUpload,{uploadTicket:i,storageId:s}),s}o(nS,"stageDocx");function UD(t){let e=jD(t,n=>Xv.test(n));if(!e.has("word/document.xml"))throw new Error("word/document.xml not found \u2014 the file is not a readable .docx.");return eS([...e.values()])}o(UD,"docxPlaceholderText");function jD(t,e){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new Error("No ZIP central directory \u2014 the file is not a readable .docx."),i=-1;for(let d=t.length-22;d>=Math.max(0,t.length-22-65535);d--)if(n.getUint32(d,!0)===101010256){i=d;break}if(i<0)throw r;let s=n.getUint16(i+10,!0),a=n.getUint32(i+16,!0),l=new Map;for(let d=0;d<s;d++){if(a+46>t.length||n.getUint32(a,!0)!==33639248)throw r;let c=n.getUint16(a+10,!0),u=n.getUint32(a+20,!0),f=n.getUint16(a+28,!0),h=n.getUint16(a+30,!0),g=n.getUint16(a+32,!0),b=n.getUint32(a+42,!0),y=new TextDecoder().decode(t.subarray(a+46,a+46+f));if(a+=46+f+h+g,!e(y))continue;if(n.getUint32(b,!0)!==67324752)throw r;let w=b+30+n.getUint16(b+26,!0)+n.getUint16(b+28,!0),S=Buffer.from(t.subarray(w,w+u));l.set(y,(c===0?S:VD(S)).toString("utf8"))}return l}o(jD,"readZipEntries");var At=["de","en"];function Jn(t,e){return At.every(n=>t[n]===e[n])}o(Jn,"sameText");function wt(t){if(t===null||typeof t!="object"||Array.isArray(t))return"not-localized";let e=t;return Object.keys(e).some(r=>!At.includes(r))?"not-localized":At.filter(r=>{let i=e[r];return typeof i!="string"||i.trim()===""})}o(wt,"missingLocales");function Ur(t){let e=wt(t);return e!=="not-localized"&&e.length===0}o(Ur,"isLocalizedText");function _t(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${n}: ${e} muss ein Objekt sein.`);return t}o(_t,"record");function Ge(t,e,n){if(typeof t!="string"||t.trim().length===0)throw new Error(`${n}: ${e} fehlt.`);return t.trim()}o(Ge,"text");function Zt(t,e,n,r){let i=wt(t);if(i==="not-localized"){let a=typeof t=="string"&&t.trim()!==""?t.trim():"\u2026";throw new Error(`${n}: ${e}: erwartet { "de": "\u2026", "en": "\u2026" } (${r} sind zweisprachig) \u2014 z. B. "name": ${JSON.stringify({de:a,en:"\u2026"})}`)}if(i.length>0)throw new Error(`${n}: ${e}.${i.join(` und ${e}.`)} ${i.length>1?"fehlen":"fehlt"} (${r} sind zweisprachig; kein R\xFCckfall auf Deutsch).`);let s=t;return{de:s.de.trim(),en:s.en.trim()}}o(Zt,"localizedName");function pn(t,e,n){if(!Array.isArray(t))throw new Error(`${n}: ${e} muss eine Liste sein.`);return t}o(pn,"list");function Xd(t,e){return pn(t,"revenueAccounts",e).map((n,r)=>{let i=_t(n,`revenueAccounts[${r}]`,e);return{code:Ge(i.code,`revenueAccounts[${r}].code`,e),name:Ge(i.name,`revenueAccounts[${r}].name`,e)}})}o(Xd,"parseRevenueAccounts");function ec(t,e){return pn(t,"billingItems",e).map((n,r)=>{let i=`billingItems[${r}]`,s=_t(n,i,e),a=Ge(s.itemType,`${i}.itemType`,e),l=Ge(s.taxTreatment,`${i}.taxTreatment`,e);if(l!=="exempt_ustg_4_nr_21"&&l!=="vat_19"&&l!=="vat_7")throw new Error(`${e}: ${i}.taxTreatment ist unbekannt.`);if(a!=="recurring"&&a!=="one_time"&&a!=="usage")throw new Error(`${e}: ${i}.itemType "${a}" ist unbekannt.`);if(s.minAmount!==void 0)throw new Error(`${e}: ${i}.minAmount wird nicht mehr unterst\xFCtzt; eine Vertragserm\xE4\xDFigung mit Untergrenze verwenden.`);let d=_t(s.price,`${i}.price`,e),c=d.effectiveFrom===void 0?{}:{effectiveFrom:Ge(d.effectiveFrom,`${i}.price.effectiveFrom`,e)},u=Ge(d.currency,`${i}.price.currency`,e),f=d.tree===void 0?(()=>{let h=Ge(d.period,`${i}.price.period`,e);if(!["month","year","once","unit"].includes(h))throw new Error(`${e}: ${i}.price.period ist unbekannt.`);return{currency:u,amount:d.amount,period:h,...c}})():(()=>{if(d.amount!==void 0||d.period!==void 0)throw new Error(`${e}: ${i}.price: tree wird nicht mit amount oder period kombiniert.`);return{currency:u,tree:_t(d.tree,`${i}.price.tree`,e),...c}})();return{key:Ge(s.key,`${i}.key`,e),name:Zt(s.name,`${i}.name`,e,"Artikelnamen"),itemType:a,revenueAccount:Ge(s.revenueAccount,`${i}.revenueAccount`,e),taxTreatment:l,config:_t(s.config??{},`${i}.config`,e),...s.programs===void 0?{}:{programs:pn(s.programs,`${i}.programs`,e).map((h,g)=>Ge(h,`${i}.programs[${g}]`,e))},price:f}})}o(ec,"parseBillingItems");var Ie="catalog",zD=["sibling","stipend","promo","needsBased","singleParent"],HD=["percent","absolute"];function yp(t,e){let n=new Set;for(let r of t){if(n.has(r))throw new Error(`${Ie}: ${e}: Schl\xFCssel "${r}" steht zweimal in der Datei.`);n.add(r)}}o(yp,"uniqueKeys");function tc(t,e,n){if(!e.includes(t))throw new Error(`${Ie}: ${n} "${t}" ist unbekannt (${e.join(", ")}).`);return t}o(tc,"oneOf");function QD(t,e){let n=_t(t,"Datei",Ie);if(n.plans!==void 0)throw new Error("catalog: plans wurden entfernt. Geb\xFChrengruppen geh\xF6ren in die Generatorrevision; Programmzuordnungen unter billingItems[].programs angeben.");let r=["revenueAccounts","billingItems","grantTemplates","documentTemplates"],i=Object.keys(n).filter(c=>!r.includes(c));if(i.length>0)throw new Error(`${Ie}: unbekannte Abschnitte ${i.join(", ")} (erlaubt: ${r.join(", ")}).`);let s=ec(n.billingItems??[],Ie).map((c,u)=>{let f=`billingItems[${u}].price`;if(!("tree"in c.price)&&(typeof c.price.amount!="number"||!Number.isFinite(c.price.amount)))throw new Error(`${Ie}: ${f}.amount muss eine Zahl sein (${JSON.stringify("amount"in c.price?c.price.amount:null)}).`);if(c.price.effectiveFrom===void 0)throw new Error(`${Ie}: ${f}.effectiveFrom fehlt \u2014 der erste Tag, ab dem der Preis gilt (YYYY-MM-DD).`);return{...c,price:"tree"in c.price?{currency:c.price.currency,tree:c.price.tree,effectiveFrom:c.price.effectiveFrom}:{currency:c.price.currency,amount:c.price.amount,effectiveFrom:c.price.effectiveFrom,period:c.price.period}}}),a=pn(n.grantTemplates??[],"grantTemplates",Ie).map((c,u)=>{let f=`grantTemplates[${u}]`,h=_t(c,f,Ie);if(h.item!==void 0||h.plan!==void 0||h.value!==void 0)throw new Error(`${Ie}: ${f}: eligibleItems, scope und rule statt item/plan/value verwenden.`);if(typeof h.retroactiveRevocation!="boolean")throw new Error(`${Ie}: ${f}.retroactiveRevocation muss true oder false sein.`);let g=tc(Ge(h.scope,`${f}.scope`,Ie),["line","aggregate"],`${f}.scope`),b=tc(Ge(h.kind,`${f}.kind`,Ie),HD,`${f}.kind`),y=_t(h.rule,`${f}.rule`,Ie);Kv(b,y);let w=tc(Ge(h.pricePeriod,`${f}.pricePeriod`,Ie),["month","year","once","unit"],`${f}.pricePeriod`);if(h.floorTotal!==void 0){if(typeof h.floorTotal!="number"||g!=="aggregate")throw new Error(`${Ie}: ${f}.floorTotal geh\xF6rt zu einer Aggregaterm\xE4\xDFigung.`);Hd(h.floorTotal)}let S=pn(h.eligibleItems,`${f}.eligibleItems`,Ie).map((A,T)=>Ge(A,`${f}.eligibleItems[${T}]`,Ie));if(S.length===0||new Set(S).size!==S.length)throw new Error(`${Ie}: ${f}.eligibleItems braucht eindeutige Artikel.`);return{key:Ge(h.key,`${f}.key`,Ie),name:Zt(h.name,`${f}.name`,Ie,"Erm\xE4\xDFigungsnamen"),eligibleItems:S,scope:g,rule:y,pricePeriod:w,...h.floorTotal===void 0?{}:{floorTotal:h.floorTotal},...h.offeredFrom===void 0?{}:{offeredFrom:Ge(h.offeredFrom,`${f}.offeredFrom`,Ie)},...h.offeredUntil===void 0?{}:{offeredUntil:Ge(h.offeredUntil,`${f}.offeredUntil`,Ie)},reason:tc(Ge(h.reason,`${f}.reason`,Ie),zD,`${f}.reason`),kind:b,eligibility:_t(h.eligibility,`${f}.eligibility`,Ie),retroactiveRevocation:h.retroactiveRevocation}}),l=pn(n.documentTemplates??[],"documentTemplates",Ie).map((c,u)=>{let f=`documentTemplates[${u}]`,h=_t(c,f,Ie),g=Ge(h.key,`${f}.key`,Ie);if(!Jv(g))throw new Error(`${Ie}: ${f}.key "${g}" ist kein g\xFCltiger Vorlagen-Schl\xFCssel (Kleinbuchstaben, Ziffern, - und _, beginnend mit einem Buchstaben).`);let b=Ts.resolve(e,Ge(h.file,`${f}.file`,Ie));if(!b.toLowerCase().endsWith(".docx"))throw new Error(`${Ie}: ${f}.file muss eine .docx sein.`);return{key:g,name:Zt(h.name,`${f}.name`,Ie,"Vorlagennamen"),file:b,role:Ge(h.role,`${f}.role`,Ie),...h.icon===void 0?{}:{icon:Ge(h.icon,`${f}.icon`,Ie)},...h.fileNamePattern===void 0?{}:{fileNamePattern:Ge(h.fileNamePattern,`${f}.fileNamePattern`,Ie)}}});yp(s.map(c=>c.key),"billingItems"),yp(a.map(c=>c.key),"grantTemplates");for(let[c,u]of s.entries()){if(u.programs===void 0)throw new Error(`${Ie}: billingItems[${c}] (${u.key}) geh\xF6rt keinem Programm \u2014 "programs" nennen (die Programm-Schl\xFCssel, die den Artikel einzeln verkaufen; [] f\xFCr einen stillgelegten Artikel) oder den Artikel in ein Paket aufnehmen.`);if(u.programs!==void 0&&new Set(u.programs).size!==u.programs.length)throw new Error(`${Ie}: billingItems[${c}].programs: ein Programm steht zweimal.`)}yp(l.map(c=>c.key),"documentTemplates");let d=Xd(n.revenueAccounts??[],Ie);if(d.length+s.length+a.length+l.length===0)throw new Error(`${Ie}: die Datei deklariert nichts (${r.join(", ")}).`);return{revenueAccounts:d,billingItems:s,grantTemplates:a,documentTemplates:l}}o(QD,"parseCatalog");function bp(t){let e=Ts.resolve(t);if(!GD(e))throw new Error(`${Ie}: ${e} gibt es nicht.`);return QD(JSON.parse(WD(e,"utf8")),Ts.dirname(e))}o(bp,"readCatalog");function YD(t){return{revenueAccounts:t.revenueAccounts,billingItems:t.billingItems.map(e=>({key:e.key,name:e.name,itemType:e.itemType,revenueAccountCode:e.revenueAccount,taxTreatment:e.taxTreatment,config:e.config,price:e.price}))}}o(YD,"billingArgs");function JD(t){return{articlePrograms:t.billingItems.map(e=>({item:e.key,programs:e.programs??[]}))}}o(JD,"planArgs");async function wp(t,e,n,r=Ai){let i=[],s=[],a=null;if(n.billingItems.length>0||n.revenueAccounts.length>0){a=YD(n);let u=await t.query(R.contractSetup.planBillingSetup,{client:e,...a});for(let f of u.rows)i.push({step:f.kind,target:f.key,action:f.action,detail:f.detail}),f.kind==="billingItem"&&f.action==="create"&&s.push(f.key)}let l=null;if(n.billingItems.length>0){l=JD(n);let u=await t.query(R.catalogPrograms.planProgramSetup,{client:e,...l,pendingItems:s});for(let f of u.rows)i.push({step:f.kind,target:f.key,action:f.action,detail:f.detail});for(let f of n.billingItems)f.programs?.length===0&&i.push({step:"billingItemProgram",target:f.key,action:"none",detail:"kein Programm verkauft den Artikel (stillgelegt?) \u2014 Finanzen zeigt \u201EKein Programm\u201C"})}let d=null;if(n.grantTemplates.length>0){d={grantTemplates:n.grantTemplates};let u=await t.query(R.contractSetup.planGrantSetup,{client:e,grantTemplates:n.grantTemplates,pendingItems:s});for(let f of u.rows)i.push({step:"grantTemplate",target:f.key,action:f.action,detail:f.detail})}let c=[];if(n.documentTemplates.length>0){let u=await t.query(R.templates.roleOptions,{client:e});for(let f of n.documentTemplates){let h=u.find(S=>S.key===f.role);if(h===void 0)throw new Error(`${Ie}: Vorlage ${f.key}: Rolle "${f.role}" ist keine Blatt-Rolle dieses Mandanten (${u.map(S=>S.key).join(", ")}).`);let g=await r(f.file),b=await t.query(R.templates.stateByConfigKey,{client:e,configKey:f.key});if(b!==null&&b.roleKey!==f.role)throw new Error(`${Ie}: Vorlage ${f.key} geh\xF6rt zur Rolle "${b.roleKey}", die Datei nennt "${f.role}" \u2014 die Rolle einer bestehenden Vorlage \xE4ndert catalog nicht (Vorlagenverwaltung).`);let y=b===null||b.sha256!==g.sha256,w=[];b!==null&&(Jn(b.name,f.name)||w.push(`Name ${b.name.de} / ${b.name.en||"\u2014"} \u2192 ${f.name.de} / ${f.name.en}`),f.icon!==void 0&&b.icon!==f.icon&&w.push(`Icon \u2192 ${f.icon}`),f.fileNamePattern!==void 0&&b.fileNamePattern!==f.fileNamePattern&&w.push("Dateinamensmuster")),c.push({declared:f,docx:g,roleId:h.id,state:b,upload:y,metadata:w}),i.push({step:"documentTemplate",target:f.key,action:b===null?"create":y||w.length>0?"update":"same",detail:b===null?`${f.name.de} \xB7 ${Ts.basename(f.file)}`:[...y?[`Datei ersetzen (${Ts.basename(f.file)})`]:[],...w].join(", ")})}}return{rows:i,billing:a,plans:l,grants:d,templates:c}}o(wp,"planCatalog");async function rS(t,e,n,r=Ai){let i=await wp(t,e,n,r),s=[];if(i.billing!==null){let a=await t.mutation(R.contractSetup.applyBillingSetup,{client:e,...i.billing});for(let l of a.rows)s.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.plans!==null){let a=await t.mutation(R.catalogPrograms.applyProgramSetup,{client:e,...i.plans});for(let l of a.rows)s.push({step:l.kind,target:l.key,action:l.action,detail:l.detail})}if(i.grants!==null){let a=await t.mutation(R.contractSetup.applyGrantSetup,{client:e,grantTemplates:i.grants.grantTemplates});for(let l of a.rows)s.push({step:"grantTemplate",target:l.key,action:l.action,detail:l.detail})}for(let a of i.templates){let{declared:l,state:d}=a;if(d===null)await ho(t,e,a.docx,{name:l.name,role:l.role,configKey:l.key,...l.icon===void 0?{}:{icon:l.icon},...l.fileNamePattern===void 0?{}:{fileNamePattern:l.fileNamePattern}});else if(a.upload&&await tS(t,e,d.templateId,a.docx),a.metadata.length>0){let c=l.icon??d.icon,u=l.fileNamePattern??d.fileNamePattern;await t.mutation(R.templates.updateMetadata,{client:e,templateId:d.templateId,name:l.name,roleId:a.roleId,configKey:l.key,...c===null?{}:{icon:c},...u===null?{}:{fileNamePattern:u}})}s.push(i.rows.find(c=>c.step==="documentTemplate"&&c.target===l.key))}return s}o(rS,"applyCatalog");async function iS(t,e){let{unkeyed:n,...r}=await t.query(R.catalogExport.exportCatalog,{client:e});return{file:{revenueAccounts:r.revenueAccounts,billingItems:r.billingItems,grantTemplates:r.grantTemplates},unkeyed:n}}o(iS,"exportCatalog");function oS(t,e,n,r,i){if(n||!r){t.write(`${JSON.stringify(e,null,2)}
|
|
71
|
+
`);return}t.write(`${ZD(r(e),i)}
|
|
72
|
+
`)}o(oS,"emit");function Dn(t){return dp(t)}o(Dn,"errorMessage");function ZD(t,e){if(t.length===0)return"(none)";let n=e??Object.keys(t[0]),r=n.map(a=>Math.max(a.length,...t.map(l=>(l[a]??"").length))),i=o(a=>a.map((l,d)=>l.padEnd(r[d])).join(" ").trimEnd(),"line"),s=[i(n),i(n.map((a,l)=>"\u2500".repeat(r[l])))];for(let a of t)s.push(i(n.map(l=>a[l]??"")));return s.join(`
|
|
73
|
+
`)}o(ZD,"renderTable");function sS(t){if(!(t instanceof Error))return t;let e=zd(t);if(e!==null&&e.message!==""){let i=new Error(e.code===null?e.message:`[${e.code}] ${e.message}`);return i.name="Refused",i}let n=dp(t);if(n===t.message)return t;let r=new Error(n);return r.name="ServerFailure",r}o(sS,"operatorError");var Re=class extends I{static{o(this,"BaseCommand")}json=p.Boolean("--json",!1,{description:"Print raw JSON instead of a table"});async catch(e){throw sS(e)}print(e,n,r){oS(this.context.stdout,e,this.json,n,r)}};import{existsSync as gm,readFileSync as cM}from"node:fs";import Di from"node:path";var Zn=[],xn=[],XD=Uint8Array,kp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ei=0,aS=kp.length;Ei<aS;++Ei)Zn[Ei]=kp[Ei],xn[kp.charCodeAt(Ei)]=Ei;var Ei,aS;xn[45]=62;xn[95]=63;function eF(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}o(eF,"getLens");function tF(t,e,n){return(e+n)*3/4-n}o(tF,"_byteLength");function go(t){var e,n=eF(t),r=n[0],i=n[1],s=new XD(tF(t,r,i)),a=0,l=i>0?r-4:r,d;for(d=0;d<l;d+=4)e=xn[t.charCodeAt(d)]<<18|xn[t.charCodeAt(d+1)]<<12|xn[t.charCodeAt(d+2)]<<6|xn[t.charCodeAt(d+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return i===2&&(e=xn[t.charCodeAt(d)]<<2|xn[t.charCodeAt(d+1)]>>4,s[a++]=e&255),i===1&&(e=xn[t.charCodeAt(d)]<<10|xn[t.charCodeAt(d+1)]<<4|xn[t.charCodeAt(d+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}o(go,"toByteArray");function nF(t){return Zn[t>>18&63]+Zn[t>>12&63]+Zn[t>>6&63]+Zn[t&63]}o(nF,"tripletToBase64");function rF(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(nF(r));return i.join("")}o(rF,"encodeChunk");function yo(t){for(var e,n=t.length,r=n%3,i=[],s=16383,a=0,l=n-r;a<l;a+=s)i.push(rF(t,a,a+s>l?l:a+s));return r===1?(e=t[n-1],i.push(Zn[e>>2]+Zn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(Zn[e>>10]+Zn[e>>4&63]+Zn[e<<2&63]+"=")),i.join("")}o(yo,"fromByteArray");function An(t){if(t===void 0)return{};if(!rc(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}o(An,"parseArgs");function nc(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}o(nc,"validateDeploymentUrl");function rc(t){let e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}o(rc,"isSimpleObject");var cS=!0,bo=BigInt("-9223372036854775808"),oc=BigInt("9223372036854775807"),Ap=BigInt("0"),iF=BigInt("8"),oF=BigInt("256"),Sp="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",Ti=class{static{o(this,"CommitTsPlaceholder")}[Symbol.toPrimitive](e){if(e==="string")return this.toString();throw new Error(Sp)}valueOf(){throw new Error(Sp)}toJSON(){throw new Error(Sp)}toString(){return"[unresolved commit timestamp]"}},uS=new Ti;function fS(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}o(fS,"isSpecial");function sF(t){t<Ap&&(t-=bo+bo);let e=t.toString(16);e.length%2===1&&(e="0"+e);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=iF;return yo(n)}o(sF,"slowBigIntToBase64");function aF(t){let e=go(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Ap,r=Ap;for(let i of e)n+=BigInt(i)*oF**r,r++;return n>oc&&(n+=bo+bo),n}o(aF,"slowBase64ToBigInt");function lF(t){if(t<bo||oc<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);let e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),yo(new Uint8Array(e))}o(lF,"modernBigIntToBase64");function dF(t){let e=go(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}o(dF,"modernBase64ToBigInt");var cF=DataView.prototype.setBigInt64?lF:sF,uF=DataView.prototype.getBigInt64?dF:aF,lS=1024;function Ep(t){if(t.length>lS)throw new Error(`Field name ${t} exceeds maximum field name length ${lS}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}o(Ep,"validateObjectField");function Ot(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Ot(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);let e=Object.entries(t);if(e.length===1){let r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return go(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return uF(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);let i=go(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);let a=new DataView(i.buffer).getFloat64(0,cS);if(!fS(a))throw new Error(`Float ${a} should be encoded as a number`);return a}if(r==="$commitTs"){if(t.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${t}`);return uS}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}let n={};for(let[r,i]of Object.entries(t))Ep(r),n[r]=Ot(i);return n}o(Ot,"jsonToConvex");var dS=16384;function Ri(t){let e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="function"?"[Function]":typeof r=="symbol"?String(r):typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>dS){let n="[...truncated]",r=dS-n.length,i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}o(Ri,"stringifyValueForError");function ic(t,e,n,r){if(t===void 0){let a=n&&` (present at path ${n} in original object ${Ri(e)})`;throw new Error(`undefined is not a valid Convex value${a}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<bo||oc<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:cF(t)}}if(typeof t=="number")if(fS(t)){let a=new ArrayBuffer(8);return new DataView(a).setFloat64(0,t,cS),{$float:yo(new Uint8Array(a))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:yo(new Uint8Array(t))};if(t instanceof Ti)return{$commitTs:null};if(Array.isArray(t))return t.map((a,l)=>ic(a,e,n+`[${l}]`,!1));if(t instanceof Set)throw new Error(xp(n,"Set",[...t],e));if(t instanceof Map)throw new Error(xp(n,"Map",[...t],e));if(!rc(t)){let a=t?.constructor?.name,l=a?`${a} `:"";throw new Error(xp(n,l,t,e))}let i={},s=Object.entries(t);s.sort(([a,l],[d,c])=>a===d?0:a<d?-1:1);for(let[a,l]of s)l!==void 0?(Ep(a),i[a]=ic(l,e,n+`.${a}`,!1)):r&&(Ep(a),i[a]=fF(l,e,n+`.${a}`));return i}o(ic,"convexToJsonInternal");function xp(t,e,n,r){return t?`${e}${Ri(n)} is not a supported Convex type (present at path ${t} in original object ${Ri(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${Ri(n)} is not a supported Convex type.`}o(xp,"errorMessageForUnsupportedType");function fF(t,e,n){if(t===void 0)return{$undefined:null};if(e===void 0)throw new Error(`Programming error. Current value is ${Ri(t)} but original value is undefined`);return ic(t,e,n,!1)}o(fF,"convexOrUndefinedToJsonInternal");function Wt(t){return ic(t,t,"",!1)}o(Wt,"convexToJson");var pF=Object.defineProperty,mF=o((t,e,n)=>e in t?pF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),He=o((t,e,n)=>mF(t,typeof e!="symbol"?e+"":e,n),"__publicField"),hF="https://docs.convex.dev/error#undefined-validator";function Is(t,e){let n=e!==void 0?` for field "${e}"`:"";throw new Error(`A validator is undefined${n} in ${t}. This is often caused by circular imports. See ${hF} for details.`)}o(Is,"throwUndefinedValidatorError");var zt=class{static{o(this,"BaseValidator")}constructor({isOptional:e}){He(this,"type"),He(this,"fieldPaths"),He(this,"isOptional"),He(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}},sc=class t extends zt{static{o(this,"VId")}constructor({isOptional:e,tableName:n}){if(super({isOptional:e}),He(this,"tableName"),He(this,"kind","id"),typeof n!="string")throw new Error("v.id(tableName) requires a string");this.tableName=n}get json(){return{type:"id",tableName:this.tableName}}optional(){return new t({isOptional:"optional",tableName:this.tableName})}asOptional(){return this.optional()}},$s=class t extends zt{static{o(this,"VFloat64")}constructor(){super(...arguments),He(this,"kind","float64")}get json(){return{type:"number"}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},_s=class t extends zt{static{o(this,"VInt64")}constructor(){super(...arguments),He(this,"kind","int64")}get json(){return{type:"bigint"}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},ac=class t extends zt{static{o(this,"VCommitTs")}constructor(){super(...arguments),He(this,"kind","commitTs")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},lc=class t extends zt{static{o(this,"VBoolean")}constructor(){super(...arguments),He(this,"kind","boolean")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},dc=class t extends zt{static{o(this,"VBytes")}constructor(){super(...arguments),He(this,"kind","bytes")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},cc=class t extends zt{static{o(this,"VString")}constructor(){super(...arguments),He(this,"kind","string")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},uc=class t extends zt{static{o(this,"VNull")}constructor(){super(...arguments),He(this,"kind","null")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},fc=class t extends zt{static{o(this,"VAny")}constructor(){super(...arguments),He(this,"kind","any")}get json(){return{type:this.kind}}optional(){return new t({isOptional:"optional"})}asOptional(){return this.optional()}},pc=class t extends zt{static{o(this,"VObject")}constructor({isOptional:e,fields:n}){super({isOptional:e}),He(this,"fields"),He(this,"kind","object"),globalThis.Object.entries(n).forEach(([r,i])=>{if(i===void 0&&Is("v.object()",r),!i.isConvexValidator)throw new Error("v.object() entries must be validators")}),this.fields=n}get json(){return{type:this.kind,value:globalThis.Object.fromEntries(globalThis.Object.entries(this.fields).map(([e,n])=>[e,{fieldType:n.json,optional:n.isOptional==="optional"}]))}}optional(){return new t({isOptional:"optional",fields:this.fields})}asOptional(){return this.optional()}omit(...e){let n={...this.fields};for(let r of e)delete n[r];return new t({isOptional:this.isOptional,fields:n})}pick(...e){let n={};for(let r of e)n[r]=this.fields[r];return new t({isOptional:this.isOptional,fields:n})}partial(){let e={};for(let[n,r]of globalThis.Object.entries(this.fields))e[n]=r.asOptional();return new t({isOptional:this.isOptional,fields:e})}extend(e){return new t({isOptional:this.isOptional,fields:{...this.fields,...e}})}},mc=class t extends zt{static{o(this,"VLiteral")}constructor({isOptional:e,value:n}){if(super({isOptional:e}),He(this,"value"),He(this,"kind","literal"),typeof n!="string"&&typeof n!="boolean"&&typeof n!="number"&&typeof n!="bigint")throw new Error("v.literal(value) must be a string, number, or boolean");this.value=n}get json(){return{type:this.kind,value:Wt(this.value)}}optional(){return new t({isOptional:"optional",value:this.value})}asOptional(){return this.optional()}},hc=class t extends zt{static{o(this,"VArray")}constructor({isOptional:e,element:n}){super({isOptional:e}),He(this,"element"),He(this,"kind","array"),n===void 0&&Is("v.array()"),this.element=n}get json(){return{type:this.kind,value:this.element.json}}optional(){return new t({isOptional:"optional",element:this.element})}asOptional(){return this.optional()}},gc=class t extends zt{static{o(this,"VRecord")}constructor({isOptional:e,key:n,value:r}){if(super({isOptional:e}),He(this,"key"),He(this,"value"),He(this,"kind","record"),n===void 0&&Is("v.record()","key"),r===void 0&&Is("v.record()","value"),n.isOptional==="optional")throw new Error("Record validator cannot have optional keys");if(r.isOptional==="optional")throw new Error("Record validator cannot have optional values");if(!n.isConvexValidator||!r.isConvexValidator)throw new Error("Key and value of v.record() must be validators");this.key=n,this.value=r}get json(){return{type:this.kind,keys:this.key.json,values:{fieldType:this.value.json,optional:!1}}}optional(){return new t({isOptional:"optional",key:this.key,value:this.value})}asOptional(){return this.optional()}},yc=class t extends zt{static{o(this,"VUnion")}constructor({isOptional:e,members:n}){super({isOptional:e}),He(this,"members"),He(this,"kind","union"),n.forEach((r,i)=>{if(r===void 0&&Is("v.union()",`member at index ${i}`),!r.isConvexValidator)throw new Error("All members of v.union() must be validators")}),this.members=n}get json(){return{type:this.kind,value:this.members.map(e=>e.json)}}optional(){return new t({isOptional:"optional",members:this.members})}asOptional(){return this.optional()}};function bc(t){return t?.isConvexValidator===!0}o(bc,"isValidator");var ve={id:o(t=>new sc({isOptional:"required",tableName:t}),"id"),null:o(()=>new uc({isOptional:"required"}),"null"),number:o(()=>new $s({isOptional:"required"}),"number"),float64:o(()=>new $s({isOptional:"required"}),"float64"),bigint:o(()=>new _s({isOptional:"required"}),"bigint"),int64:o(()=>new _s({isOptional:"required"}),"int64"),commitTs:o(()=>new ac({isOptional:"required"}),"commitTs"),boolean:o(()=>new lc({isOptional:"required"}),"boolean"),string:o(()=>new cc({isOptional:"required"}),"string"),bytes:o(()=>new dc({isOptional:"required"}),"bytes"),literal:o(t=>new mc({isOptional:"required",value:t}),"literal"),array:o(t=>new hc({isOptional:"required",element:t}),"array"),object:o(t=>new pc({isOptional:"required",fields:t}),"object"),record:o((t,e)=>new gc({isOptional:"required",key:t,value:e}),"record"),union:o((...t)=>new yc({isOptional:"required",members:t}),"union"),any:o(()=>new fc({isOptional:"required"}),"any"),optional:o(t=>t.asOptional(),"optional"),nullable:o(t=>ve.union(t,ve.null()),"nullable")};var gF=Object.defineProperty,yF=o((t,e,n)=>e in t?gF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),Rp=o((t,e,n)=>yF(t,typeof e!="symbol"?e+"":e,n),"__publicField"),pS,mS,bF=Symbol.for("ConvexError"),En=class extends(mS=Error,pS=bF,mS){static{o(this,"ConvexError")}constructor(e){super(typeof e=="string"?e:Ri(e)),Rp(this,"name","ConvexError"),Rp(this,"data"),Rp(this,pS,!0),this.data=e}};var hS=o(()=>Array.from({length:4},()=>0),"arr"),a6=hS(),l6=hS();var Xt="1.47.0";var Ii=Symbol.for("functionName");var gS=Symbol.for("toReferencePath");function kF(t){return t[gS]??null}o(kF,"extractReferencePath");function vF(t){return t.startsWith("function://")}o(vF,"isFunctionHandle");function kr(t){let e;if(typeof t=="string")vF(t)?e={functionHandle:t}:e={name:t};else if(t[Ii])e={name:t[Ii]};else{let n=kF(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}o(kr,"getFunctionAddress");var W3=ve.object({numItems:ve.number(),cursor:ve.union(ve.string(),ve.null()),endCursor:ve.optional(ve.union(ve.string(),ve.null())),id:ve.optional(ve.number()),maximumRowsRead:ve.optional(ve.number()),maximumBytesRead:ve.optional(ve.number())});function vr(t){let e=kr(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;let n=t[Ii];if(!n)throw new Error(`${t} is not a functionReference`);return n}o(vr,"getFunctionName");function Os(t){return{[Ii]:t}}o(Os,"makeFunctionReference");function bS(t=[]){let e={get(n,r){if(typeof r=="string"){let i=[...t,r];return bS(i)}else if(r===Ii){if(t.length<2){let a=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}let i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}o(bS,"createApi");var AF=bS();var EF=Symbol("var.requestId"),RF=Symbol("var.ip"),TF=Symbol("var.userAgent"),IF=Symbol("var.now"),$F=Symbol("var.convexActor"),_F={[EF]:"requestId",[RF]:"ip",[TF]:"userAgent",[IF]:"now",[$F]:"convexActor"};var OF=Object.defineProperty,CF=o((t,e,n)=>e in t?OF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),Fn=o((t,e,n)=>CF(t,typeof e!="symbol"?e+"":e,n),"__publicField"),wc=class{static{o(this,"TableDefinition")}constructor(e){Fn(this,"indexes"),Fn(this,"stagedDbIndexes"),Fn(this,"searchIndexes"),Fn(this,"stagedSearchIndexes"),Fn(this,"vectorIndexes"),Fn(this,"stagedVectorIndexes"),Fn(this,"validator"),Fn(this,"stagedValidator"),this.indexes=[],this.stagedDbIndexes=[],this.searchIndexes=[],this.stagedSearchIndexes=[],this.vectorIndexes=[],this.stagedVectorIndexes=[],this.validator=e}" indexes"(){return this.indexes}index(e,n){return Array.isArray(n)?this.indexes.push({indexDescriptor:e,fields:n}):n.staged?this.stagedDbIndexes.push({indexDescriptor:e,fields:n.fields}):this.indexes.push({indexDescriptor:e,fields:n.fields}),this}searchIndex(e,n){return n.staged?this.stagedSearchIndexes.push({indexDescriptor:e,searchField:n.searchField,filterFields:n.filterFields||[]}):this.searchIndexes.push({indexDescriptor:e,searchField:n.searchField,filterFields:n.filterFields||[]}),this}vectorIndex(e,n){return n.staged?this.stagedVectorIndexes.push({indexDescriptor:e,vectorField:n.vectorField,dimensions:n.dimensions,filterFields:n.filterFields||[]}):this.vectorIndexes.push({indexDescriptor:e,vectorField:n.vectorField,dimensions:n.dimensions,filterFields:n.filterFields||[]}),this}staged(e){if(this.stagedValidator!==void 0)throw new Error("Table cannot have more than one staged validator.");if(bc(e))this.stagedValidator=e;else{if(this.validator.kind!=="object"&&this.validator.kind!=="any")throw new Error("Specifying top-level field changes is only supported for simple table definitions. For a table defined with a union or record validator, you must stage a fully defined object or union validator.");let n=this.validator.kind==="object"?this.validator.fields:{},r=Object.fromEntries(Object.entries({...n,...e}).filter(i=>i[1]!==void 0));this.stagedValidator=ve.object(r)}return this.self()}self(){return this}export(){let e=this.validator.json;if(typeof e!="object")throw new Error("Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)");let n;if(this.stagedValidator!==void 0&&(n=this.stagedValidator.json,typeof n!="object"))throw new Error("Invalid staged validator: please make sure that the parameter of `.staged()` is valid (see https://docs.convex.dev/database/schemas)");return{indexes:this.indexes,stagedDbIndexes:this.stagedDbIndexes,searchIndexes:this.searchIndexes,stagedSearchIndexes:this.stagedSearchIndexes,vectorIndexes:this.vectorIndexes,stagedVectorIndexes:this.stagedVectorIndexes,documentType:e,stagedDocumentType:n}}};function Ip(t){return bc(t)?new wc(t):new wc(ve.object(t))}o(Ip,"defineTable");function kS(t,e){switch(e.kind){case"object":return e.extend({_id:ve.id(t),_creationTime:ve.number()});case"union":return ve.union(...e.members.map(n=>kS(t,n)));case"any":return e;default:throw new Error(`Invalid validator for table "${t}": a table's documents must be objects, or a union of objects (see https://docs.convex.dev/database/schemas)`)}}o(kS,"addSystemFields");function vS(t,e){return kS(t,e.validator)}o(vS,"docValidator");function wS(t,e){let n=t.tables[e];if(n===void 0)throw new Error(`Table "${e}" is not in this schema. Tables in this schema: ${Object.keys(t.tables).join(", ")}`);return n}o(wS,"tableInSchema");var $p=class{static{o(this,"SchemaDefinition")}constructor(e,n){Fn(this,"tables"),Fn(this,"strictTableNameTypes"),Fn(this,"schemaValidation"),this.tables=e,this.schemaValidation=n?.schemaValidation===void 0?!0:n.schemaValidation}doc(e){return vS(e,wS(this,e))}id(e){return wS(this,e),ve.id(e)}export(){return JSON.stringify({tables:Object.entries(this.tables).map(([e,n])=>{let{indexes:r,stagedDbIndexes:i,searchIndexes:s,stagedSearchIndexes:a,vectorIndexes:l,stagedVectorIndexes:d,documentType:c,stagedDocumentType:u}=n.export();return{tableName:e,indexes:r,stagedDbIndexes:i,searchIndexes:s,stagedSearchIndexes:a,vectorIndexes:l,stagedVectorIndexes:d,documentType:c,stagedDocumentType:u}}),schemaValidation:this.schemaValidation})}};function SS(t,e){return new $p(t,e)}o(SS,"defineSchema");var I5=SS({_scheduled_functions:Ip({name:ve.string(),args:ve.array(ve.any()),scheduledTime:ve.float64(),completedTime:ve.optional(ve.float64()),state:ve.union(ve.object({kind:ve.literal("pending")}),ve.object({kind:ve.literal("inProgress")}),ve.object({kind:ve.literal("success")}),ve.object({kind:ve.literal("failed"),error:ve.string()}),ve.object({kind:ve.literal("canceled")}))}),_storage:Ip({sha256:ve.string(),size:ve.float64(),contentType:ve.optional(ve.string())})});import{existsSync as Np,readFileSync as DS}from"node:fs";import Dp from"node:path";var DF=Object.defineProperty,FF=o((t,e,n)=>e in t?DF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),_p=o((t,e,n)=>FF(t,typeof e!="symbol"?e+"":e,n),"__publicField"),$i=class t{static{o(this,"Long")}constructor(e,n){_p(this,"low"),_p(this,"high"),_p(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?RS:e>=LF?MF:new t(e%Cs|0,e/Cs|0)}toString(){return(BigInt(this.high)*BigInt(Cs)+BigInt(this.low)).toString()}equals(e){return t.isLong(e)||(e=t.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return t.isLong(e)||(e=t.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?t.fromNumber(e):new t(e.low,e.high)}},RS=new $i(0,0),TS=65536,Cs=TS*TS,LF=Cs*Cs,MF=new $i(-1,-1);var Op=class extends Error{static{o(this,"InvalidTokenError")}};Op.prototype.name="InvalidTokenError";var X8=480*60*60*1e3;import{createRequire as GF}from"module";import{resolve as WF}from"path";var UF;function $S(t){UF=t}o($S,"setDefaultWebSocketConstructor");var ko=GF(WF(".")),zF=Object.create,_S=Object.defineProperty,HF=Object.getOwnPropertyDescriptor,OS=Object.getOwnPropertyNames,QF=Object.getPrototypeOf,YF=Object.prototype.hasOwnProperty,Qe=(t=>typeof ko<"u"?ko:typeof Proxy<"u"?new Proxy(t,{get:o((e,n)=>(typeof ko<"u"?ko:e)[n],"get")}):t)(function(t){if(typeof ko<"u")return ko.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Ct=o((t,e)=>o(function(){return e||(0,t[OS(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require2"),"__commonJS"),JF=o((t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of OS(e))!YF.call(t,i)&&i!==n&&_S(t,i,{get:o(()=>e[i],"get"),enumerable:!(r=HF(e,i))||r.enumerable});return t},"__copyProps"),jr=o((t,e,n)=>(n=t!=null?zF(QF(t)):{},JF(e||!t||!t.__esModule?_S(n,"default",{value:t,enumerable:!0}):n,t)),"__toESM"),Gr=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/constants.js"(t,e){"use strict";var n=["nodebuffer","arraybuffer","fragments"],r=typeof Blob<"u";r&&n.push("blob"),e.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:r,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:o(()=>{},"NOOP")}}}),ZF=Ct({"../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(t,e){var n=Qe("fs"),r=Qe("path"),i=Qe("os"),s=typeof __webpack_require__=="function"?__non_webpack_require__:Qe,a=process.config&&process.config.variables||{},l=!!process.env.PREBUILDS_ONLY,d=process.versions.modules,c=q()?"electron":M()?"node-webkit":"node",u=process.env.npm_config_arch||i.arch(),f=process.env.npm_config_platform||i.platform(),h=process.env.LIBC||(te(f)?"musl":"glibc"),g=process.env.ARM_VERSION||(u==="arm64"?"8":a.arm_version)||"",b=(process.versions.uv||"").split(".")[0];e.exports=y;function y(B){return s(y.resolve(B))}o(y,"load"),y.resolve=y.path=function(B){B=r.resolve(B||".");try{var H=s(r.join(B,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[H+"_PREBUILD"]&&(B=process.env[H+"_PREBUILD"])}catch{}if(!l){var $=S(r.join(B,"build/Release"),A);if($)return $;var _=S(r.join(B,"build/Debug"),A);if(_)return _}var j=le(B);if(j)return j;var C=le(r.dirname(process.execPath));if(C)return C;var ne=["platform="+f,"arch="+u,"runtime="+c,"abi="+d,"uv="+b,g?"armv="+g:"","libc="+h,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+ne+`
|
|
74
|
+
loaded from: `+B+`
|
|
75
|
+
`);function le(de){var $e=w(r.join(de,"prebuilds")).map(T),xe=$e.filter(N(f,u)).sort(F)[0];if(xe){var et=r.join(de,"prebuilds",xe.name),Ze=w(et).map(x),ut=Ze.filter(v(c,d)),ue=ut.sort(E(c))[0];if(ue)return r.join(et,ue.file)}}};function w(B){try{return n.readdirSync(B)}catch{return[]}}o(w,"readdirSync");function S(B,H){var $=w(B).filter(H);return $[0]&&r.join(B,$[0])}o(S,"getFirst");function A(B){return/\.node$/.test(B)}o(A,"matchBuild");function T(B){var H=B.split("-");if(H.length===2){var $=H[0],_=H[1].split("+");if($&&_.length&&_.every(Boolean))return{name:B,platform:$,architectures:_}}}o(T,"parseTuple");function N(B,H){return function($){return $==null||$.platform!==B?!1:$.architectures.includes(H)}}o(N,"matchTuple");function F(B,H){return B.architectures.length-H.architectures.length}o(F,"compareTuples");function x(B){var H=B.split("."),$=H.pop(),_={file:B,specificity:0};if($==="node"){for(var j=0;j<H.length;j++){var C=H[j];if(C==="node"||C==="electron"||C==="node-webkit")_.runtime=C;else if(C==="napi")_.napi=!0;else if(C.slice(0,3)==="abi")_.abi=C.slice(3);else if(C.slice(0,2)==="uv")_.uv=C.slice(2);else if(C.slice(0,4)==="armv")_.armv=C.slice(4);else if(C==="glibc"||C==="musl")_.libc=C;else continue;_.specificity++}return _}}o(x,"parseTags");function v(B,H){return function($){return!($==null||$.runtime&&$.runtime!==B&&!P($)||$.abi&&$.abi!==H&&!$.napi||$.uv&&$.uv!==b||$.armv&&$.armv!==g||$.libc&&$.libc!==h)}}o(v,"matchTags");function P(B){return B.runtime==="node"&&B.napi}o(P,"runtimeAgnostic");function E(B){return function(H,$){return H.runtime!==$.runtime?H.runtime===B?-1:1:H.abi!==$.abi?H.abi?-1:1:H.specificity!==$.specificity?H.specificity>$.specificity?-1:1:0}}o(E,"compareTags");function M(){return!!(process.versions&&process.versions.nw)}o(M,"isNwjs");function q(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}o(q,"isElectron");function te(B){return B==="linux"&&n.existsSync("/etc/alpine-release")}o(te,"isAlpine"),y.parseTags=x,y.matchTags=v,y.compareTags=E,y.parseTuple=T,y.matchTuple=N,y.compareTuples=F}}),XF=Ct({"../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(t,e){var n=typeof __webpack_require__=="function"?__non_webpack_require__:Qe;typeof n.addon=="function"?e.exports=n.addon.bind(n):e.exports=ZF()}}),eL=Ct({"../node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js"(t,e){"use strict";var n=o((i,s,a,l,d)=>{for(var c=0;c<d;c++)a[l+c]=i[c]^s[c&3]},"mask"),r=o((i,s)=>{let a=i.length;for(var l=0;l<a;l++)i[l]^=s[l&3]},"unmask");e.exports={mask:n,unmask:r}}}),tL=Ct({"../node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js"(t,e){"use strict";try{e.exports=XF()(__dirname)}catch{e.exports=eL()}}}),kc=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/buffer-util.js"(t,e){"use strict";var{EMPTY_BUFFER:n}=Gr(),r=Buffer[Symbol.species];function i(c,u){if(c.length===0)return n;if(c.length===1)return c[0];let f=Buffer.allocUnsafe(u),h=0;for(let g=0;g<c.length;g++){let b=c[g];f.set(b,h),h+=b.length}return h<u?new r(f.buffer,f.byteOffset,h):f}o(i,"concat");function s(c,u,f,h,g){for(let b=0;b<g;b++)f[h+b]=c[b]^u[b&3]}o(s,"_mask");function a(c,u){for(let f=0;f<c.length;f++)c[f]^=u[f&3]}o(a,"_unmask");function l(c){return c.length===c.buffer.byteLength?c.buffer:c.buffer.slice(c.byteOffset,c.byteOffset+c.length)}o(l,"toArrayBuffer");function d(c){if(d.readOnly=!0,Buffer.isBuffer(c))return c;let u;return c instanceof ArrayBuffer?u=new r(c):ArrayBuffer.isView(c)?u=new r(c.buffer,c.byteOffset,c.byteLength):(u=Buffer.from(c),d.readOnly=!1),u}if(o(d,"toBuffer"),e.exports={concat:i,mask:s,toArrayBuffer:l,toBuffer:d,unmask:a},!process.env.WS_NO_BUFFER_UTIL)try{let c=tL();e.exports.mask=function(u,f,h,g,b){b<48?s(u,f,h,g,b):c.mask(u,f,h,g,b)},e.exports.unmask=function(u,f){u.length<32?a(u,f):c.unmask(u,f)}}catch{}}}),nL=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/limiter.js"(t,e){"use strict";var n=Symbol("kDone"),r=Symbol("kRun"),i=class{static{o(this,"Limiter")}constructor(s){this[n]=()=>{this.pending--,this[r]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(s){this.jobs.push(s),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let s=this.jobs.shift();this.pending++,s(this[n])}}};e.exports=i}}),Ps=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/permessage-deflate.js"(t,e){"use strict";var n=Qe("zlib"),r=kc(),i=nL(),{kStatusCode:s}=Gr(),a=Buffer[Symbol.species],l=Buffer.from([0,0,255,255]),d=Symbol("permessage-deflate"),c=Symbol("total-length"),u=Symbol("callback"),f=Symbol("buffers"),h=Symbol("error"),g,b=class{static{o(this,"PerMessageDeflate2")}constructor(A){if(this._options=A||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!g){let T=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;g=new i(T)}}static get extensionName(){return"permessage-deflate"}offer(){let A={};return this._options.serverNoContextTakeover&&(A.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(A.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(A.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?A.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(A.client_max_window_bits=!0),A}accept(A){return A=this.normalizeParams(A),this.params=this._isServer?this.acceptAsServer(A):this.acceptAsClient(A),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let A=this._deflate[u];this._deflate.close(),this._deflate=null,A&&A(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(A){let T=this._options,N=A.find(F=>!(T.serverNoContextTakeover===!1&&F.server_no_context_takeover||F.server_max_window_bits&&(T.serverMaxWindowBits===!1||typeof T.serverMaxWindowBits=="number"&&T.serverMaxWindowBits>F.server_max_window_bits)||typeof T.clientMaxWindowBits=="number"&&!F.client_max_window_bits));if(!N)throw new Error("None of the extension offers can be accepted");return T.serverNoContextTakeover&&(N.server_no_context_takeover=!0),T.clientNoContextTakeover&&(N.client_no_context_takeover=!0),typeof T.serverMaxWindowBits=="number"&&(N.server_max_window_bits=T.serverMaxWindowBits),typeof T.clientMaxWindowBits=="number"?N.client_max_window_bits=T.clientMaxWindowBits:(N.client_max_window_bits===!0||T.clientMaxWindowBits===!1)&&delete N.client_max_window_bits,N}acceptAsClient(A){let T=A[0];if(this._options.clientNoContextTakeover===!1&&T.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!T.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(T.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&T.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return T}normalizeParams(A){return A.forEach(T=>{Object.keys(T).forEach(N=>{let F=T[N];if(F.length>1)throw new Error(`Parameter "${N}" must have only a single value`);if(F=F[0],N==="client_max_window_bits"){if(F!==!0){let x=+F;if(!Number.isInteger(x)||x<8||x>15)throw new TypeError(`Invalid value for parameter "${N}": ${F}`);F=x}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${N}": ${F}`)}else if(N==="server_max_window_bits"){let x=+F;if(!Number.isInteger(x)||x<8||x>15)throw new TypeError(`Invalid value for parameter "${N}": ${F}`);F=x}else if(N==="client_no_context_takeover"||N==="server_no_context_takeover"){if(F!==!0)throw new TypeError(`Invalid value for parameter "${N}": ${F}`)}else throw new Error(`Unknown parameter "${N}"`);T[N]=F})}),A}decompress(A,T,N){g.add(F=>{this._decompress(A,T,(x,v)=>{F(),N(x,v)})})}compress(A,T,N){g.add(F=>{this._compress(A,T,(x,v)=>{F(),N(x,v)})})}_decompress(A,T,N){let F=this._isServer?"client":"server";if(!this._inflate){let x=`${F}_max_window_bits`,v=typeof this.params[x]!="number"?n.Z_DEFAULT_WINDOWBITS:this.params[x];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:v}),this._inflate[d]=this,this._inflate[c]=0,this._inflate[f]=[],this._inflate.on("error",S),this._inflate.on("data",w)}this._inflate[u]=N,this._inflate.write(A),T&&this._inflate.write(l),this._inflate.flush(()=>{let x=this._inflate[h];if(x){this._inflate.close(),this._inflate=null,N(x);return}let v=r.concat(this._inflate[f],this._inflate[c]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[c]=0,this._inflate[f]=[],T&&this.params[`${F}_no_context_takeover`]&&this._inflate.reset()),N(null,v)})}_compress(A,T,N){let F=this._isServer?"server":"client";if(!this._deflate){let x=`${F}_max_window_bits`,v=typeof this.params[x]!="number"?n.Z_DEFAULT_WINDOWBITS:this.params[x];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:v}),this._deflate[c]=0,this._deflate[f]=[],this._deflate.on("data",y)}this._deflate[u]=N,this._deflate.write(A),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let x=r.concat(this._deflate[f],this._deflate[c]);T&&(x=new a(x.buffer,x.byteOffset,x.length-4)),this._deflate[u]=null,this._deflate[c]=0,this._deflate[f]=[],T&&this.params[`${F}_no_context_takeover`]&&this._deflate.reset(),N(null,x)})}};e.exports=b;function y(A){this[f].push(A),this[c]+=A.length}o(y,"deflateOnData");function w(A){if(this[c]+=A.length,this[d]._maxPayload<1||this[c]<=this[d]._maxPayload){this[f].push(A);return}this[h]=new RangeError("Max payload size exceeded"),this[h].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[h][s]=1009,this.removeListener("data",w),this.reset()}o(w,"inflateOnData");function S(A){if(this[d]._inflate=null,this[h]){this[u](this[h]);return}A[s]=1007,this[u](A)}o(S,"inflateOnError")}}),Ns=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/validation.js"(t,e){"use strict";var{isUtf8:n}=Qe("buffer"),{hasBlob:r}=Gr(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function s(d){return d>=1e3&&d<=1014&&d!==1004&&d!==1005&&d!==1006||d>=3e3&&d<=4999}o(s,"isValidStatusCode");function a(d){let c=d.length,u=0;for(;u<c;)if((d[u]&128)===0)u++;else if((d[u]&224)===192){if(u+1===c||(d[u+1]&192)!==128||(d[u]&254)===192)return!1;u+=2}else if((d[u]&240)===224){if(u+2>=c||(d[u+1]&192)!==128||(d[u+2]&192)!==128||d[u]===224&&(d[u+1]&224)===128||d[u]===237&&(d[u+1]&224)===160)return!1;u+=3}else if((d[u]&248)===240){if(u+3>=c||(d[u+1]&192)!==128||(d[u+2]&192)!==128||(d[u+3]&192)!==128||d[u]===240&&(d[u+1]&240)===128||d[u]===244&&d[u+1]>143||d[u]>244)return!1;u+=4}else return!1;return!0}o(a,"_isValidUTF8");function l(d){return r&&typeof d=="object"&&typeof d.arrayBuffer=="function"&&typeof d.type=="string"&&typeof d.stream=="function"&&(d[Symbol.toStringTag]==="Blob"||d[Symbol.toStringTag]==="File")}if(o(l,"isBlob"),e.exports={isBlob:l,isValidStatusCode:s,isValidUTF8:a,tokenChars:i},n)e.exports.isValidUTF8=function(d){return d.length<24?a(d):n(d)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let d=Qe("utf-8-validate");e.exports.isValidUTF8=function(c){return c.length<32?a(c):d(c)}}catch{}}}),CS=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/receiver.js"(t,e){"use strict";var{Writable:n}=Qe("stream"),r=Ps(),{BINARY_TYPES:i,EMPTY_BUFFER:s,kStatusCode:a,kWebSocket:l}=Gr(),{concat:d,toArrayBuffer:c,unmask:u}=kc(),{isValidStatusCode:f,isValidUTF8:h}=Ns(),g=Buffer[Symbol.species],b=0,y=1,w=2,S=3,A=4,T=5,N=6,F=class extends n{static{o(this,"Receiver2")}constructor(x={}){super(),this._allowSynchronousEvents=x.allowSynchronousEvents!==void 0?x.allowSynchronousEvents:!0,this._binaryType=x.binaryType||i[0],this._extensions=x.extensions||{},this._isServer=!!x.isServer,this._maxBufferedChunks=x.maxBufferedChunks|0,this._maxFragments=x.maxFragments|0,this._maxPayload=x.maxPayload|0,this._skipUTF8Validation=!!x.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=b}_write(x,v,P){if(this._opcode===8&&this._state==b)return P();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){P(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=x.length,this._buffers.push(x),this.startLoop(P)}consume(x){if(this._bufferedBytes-=x,x===this._buffers[0].length)return this._buffers.shift();if(x<this._buffers[0].length){let P=this._buffers[0];return this._buffers[0]=new g(P.buffer,P.byteOffset+x,P.length-x),new g(P.buffer,P.byteOffset,x)}let v=Buffer.allocUnsafe(x);do{let P=this._buffers[0],E=v.length-x;x>=P.length?v.set(this._buffers.shift(),E):(v.set(new Uint8Array(P.buffer,P.byteOffset,x),E),this._buffers[0]=new g(P.buffer,P.byteOffset+x,P.length-x)),x-=P.length}while(x>0);return v}startLoop(x){this._loop=!0;do switch(this._state){case b:this.getInfo(x);break;case y:this.getPayloadLength16(x);break;case w:this.getPayloadLength64(x);break;case S:this.getMask();break;case A:this.getData(x);break;case T:case N:this._loop=!1;return}while(this._loop);this._errored||x()}getInfo(x){if(this._bufferedBytes<2){this._loop=!1;return}let v=this.consume(2);if((v[0]&48)!==0){let E=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");x(E);return}let P=(v[0]&64)===64;if(P&&!this._extensions[r.extensionName]){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(this._fin=(v[0]&128)===128,this._opcode=v[0]&15,this._payloadLength=v[1]&127,this._opcode===0){if(P){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(!this._fragmented){let E=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let E=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}this._compressed=P}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let E=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");x(E);return}if(P){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let E=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");x(E);return}}else{let E=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(v[1]&128)===128,this._isServer){if(!this._masked){let E=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");x(E);return}}else if(this._masked){let E=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");x(E);return}this._payloadLength===126?this._state=y:this._payloadLength===127?this._state=w:this.haveLength(x)}getPayloadLength16(x){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(x)}getPayloadLength64(x){if(this._bufferedBytes<8){this._loop=!1;return}let v=this.consume(8),P=v.readUInt32BE(0);if(P>Math.pow(2,21)-1){let E=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");x(E);return}this._payloadLength=P*Math.pow(2,32)+v.readUInt32BE(4),this.haveLength(x)}haveLength(x){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let v=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");x(v);return}this._masked?this._state=S:this._state=A}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=A}getData(x){let v=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}v=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(v,this._mask)}if(this._opcode>7){this.controlMessage(v,x);return}if(this._compressed){this._state=T,this.decompress(v,x);return}if(v.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let P=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");x(P);return}this._messageLength=this._totalPayloadLength,this._fragments.push(v)}this.dataMessage(x)}decompress(x,v){this._extensions[r.extensionName].decompress(x,this._fin,(E,M)=>{if(E)return v(E);if(M.length){if(this._messageLength+=M.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let q=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");v(q);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let q=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");v(q);return}this._fragments.push(M)}this.dataMessage(v),this._state===b&&this.startLoop(v)})}dataMessage(x){if(!this._fin){this._state=b;return}let v=this._messageLength,P=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let E;this._binaryType==="nodebuffer"?E=d(P,v):this._binaryType==="arraybuffer"?E=c(d(P,v)):this._binaryType==="blob"?E=new Blob(P):E=P,this._allowSynchronousEvents?(this.emit("message",E,!0),this._state=b):(this._state=N,setImmediate(()=>{this.emit("message",E,!0),this._state=b,this.startLoop(x)}))}else{let E=d(P,v);if(!this._skipUTF8Validation&&!h(E)){let M=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");x(M);return}this._state===T||this._allowSynchronousEvents?(this.emit("message",E,!1),this._state=b):(this._state=N,setImmediate(()=>{this.emit("message",E,!1),this._state=b,this.startLoop(x)}))}}controlMessage(x,v){if(this._opcode===8){if(x.length===0)this._loop=!1,this.emit("conclude",1005,s),this.end();else{let P=x.readUInt16BE(0);if(!f(P)){let M=this.createError(RangeError,`invalid status code ${P}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");v(M);return}let E=new g(x.buffer,x.byteOffset+2,x.length-2);if(!this._skipUTF8Validation&&!h(E)){let M=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");v(M);return}this._loop=!1,this.emit("conclude",P,E),this.end()}this._state=b;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",x),this._state=b):(this._state=N,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",x),this._state=b,this.startLoop(v)}))}createError(x,v,P,E,M){this._loop=!1,this._errored=!0;let q=new x(P?`Invalid WebSocket frame: ${v}`:v);return Error.captureStackTrace(q,this.createError),q.code=M,q[a]=E,q}};e.exports=F}}),PS=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/sender.js"(t,e){"use strict";var{Duplex:n}=Qe("stream"),{randomFillSync:r}=Qe("crypto"),{types:{isUint8Array:i}}=Qe("util"),s=Ps(),{EMPTY_BUFFER:a,kWebSocket:l,NOOP:d}=Gr(),{isBlob:c,isValidStatusCode:u}=Ns(),{mask:f,toBuffer:h}=kc(),g=Symbol("kByteLength"),b=Buffer.alloc(4),y=8*1024,w,S=y,A=0,T=1,N=2,F=class _i{static{o(this,"_Sender")}constructor(E,M,q){this._extensions=M||{},q&&(this._generateMask=q,this._maskBuffer=Buffer.alloc(4)),this._socket=E,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=A,this.onerror=d,this[l]=void 0}static frame(E,M){let q,te=!1,B=2,H=!1;M.mask&&(q=M.maskBuffer||b,M.generateMask?M.generateMask(q):(S===y&&(w===void 0&&(w=Buffer.alloc(y)),r(w,0,y),S=0),q[0]=w[S++],q[1]=w[S++],q[2]=w[S++],q[3]=w[S++]),H=(q[0]|q[1]|q[2]|q[3])===0,B=6);let $;typeof E=="string"?(!M.mask||H)&&M[g]!==void 0?$=M[g]:(E=Buffer.from(E),$=E.length):($=E.length,te=M.mask&&M.readOnly&&!H);let _=$;$>=65536?(B+=8,_=127):$>125&&(B+=2,_=126);let j=Buffer.allocUnsafe(te?$+B:B);return j[0]=M.fin?M.opcode|128:M.opcode,M.rsv1&&(j[0]|=64),j[1]=_,_===126?j.writeUInt16BE($,2):_===127&&(j[2]=j[3]=0,j.writeUIntBE($,4,6)),M.mask?(j[1]|=128,j[B-4]=q[0],j[B-3]=q[1],j[B-2]=q[2],j[B-1]=q[3],H?[j,E]:te?(f(E,q,j,B,$),[j]):(f(E,q,E,0,$),[j,E])):[j,E]}close(E,M,q,te){let B;if(E===void 0)B=a;else{if(typeof E!="number"||!u(E))throw new TypeError("First argument must be a valid error code number");if(M===void 0||!M.length)B=Buffer.allocUnsafe(2),B.writeUInt16BE(E,0);else{let $=Buffer.byteLength(M);if($>123)throw new RangeError("The message must not be greater than 123 bytes");if(B=Buffer.allocUnsafe(2+$),B.writeUInt16BE(E,0),typeof M=="string")B.write(M,2);else if(i(M))B.set(M,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let H={[g]:B.length,fin:!0,generateMask:this._generateMask,mask:q,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==A?this.enqueue([this.dispatch,B,!1,H,te]):this.sendFrame(_i.frame(B,H),te)}ping(E,M,q){let te,B;if(typeof E=="string"?(te=Buffer.byteLength(E),B=!1):c(E)?(te=E.size,B=!1):(E=h(E),te=E.length,B=h.readOnly),te>125)throw new RangeError("The data size must not be greater than 125 bytes");let H={[g]:te,fin:!0,generateMask:this._generateMask,mask:M,maskBuffer:this._maskBuffer,opcode:9,readOnly:B,rsv1:!1};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,!1,H,q]):this.getBlobData(E,!1,H,q):this._state!==A?this.enqueue([this.dispatch,E,!1,H,q]):this.sendFrame(_i.frame(E,H),q)}pong(E,M,q){let te,B;if(typeof E=="string"?(te=Buffer.byteLength(E),B=!1):c(E)?(te=E.size,B=!1):(E=h(E),te=E.length,B=h.readOnly),te>125)throw new RangeError("The data size must not be greater than 125 bytes");let H={[g]:te,fin:!0,generateMask:this._generateMask,mask:M,maskBuffer:this._maskBuffer,opcode:10,readOnly:B,rsv1:!1};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,!1,H,q]):this.getBlobData(E,!1,H,q):this._state!==A?this.enqueue([this.dispatch,E,!1,H,q]):this.sendFrame(_i.frame(E,H),q)}send(E,M,q){let te=this._extensions[s.extensionName],B=M.binary?2:1,H=M.compress,$,_;typeof E=="string"?($=Buffer.byteLength(E),_=!1):c(E)?($=E.size,_=!1):(E=h(E),$=E.length,_=h.readOnly),this._firstFragment?(this._firstFragment=!1,H&&te&&te.params[te._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(H=$>=te._threshold),this._compress=H):(H=!1,B=0),M.fin&&(this._firstFragment=!0);let j={[g]:$,fin:M.fin,generateMask:this._generateMask,mask:M.mask,maskBuffer:this._maskBuffer,opcode:B,readOnly:_,rsv1:H};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,this._compress,j,q]):this.getBlobData(E,this._compress,j,q):this._state!==A?this.enqueue([this.dispatch,E,this._compress,j,q]):this.dispatch(E,this._compress,j,q)}getBlobData(E,M,q,te){this._bufferedBytes+=q[g],this._state=N,E.arrayBuffer().then(B=>{if(this._socket.destroyed){let $=new Error("The socket was closed while the blob was being read");process.nextTick(x,this,$,te);return}this._bufferedBytes-=q[g];let H=h(B);M?this.dispatch(H,M,q,te):(this._state=A,this.sendFrame(_i.frame(H,q),te),this.dequeue())}).catch(B=>{process.nextTick(v,this,B,te)})}dispatch(E,M,q,te){if(!M){this.sendFrame(_i.frame(E,q),te);return}let B=this._extensions[s.extensionName];this._bufferedBytes+=q[g],this._state=T,B.compress(E,q.fin,(H,$)=>{if(this._socket.destroyed){let _=new Error("The socket was closed while data was being compressed");x(this,_,te);return}this._bufferedBytes-=q[g],this._state=A,q.readOnly=!1,this.sendFrame(_i.frame($,q),te),this.dequeue()})}dequeue(){for(;this._state===A&&this._queue.length;){let E=this._queue.shift();this._bufferedBytes-=E[3][g],Reflect.apply(E[0],this,E.slice(1))}}enqueue(E){this._bufferedBytes+=E[3][g],this._queue.push(E)}sendFrame(E,M){E.length===2?(this._socket.cork(),this._socket.write(E[0]),this._socket.write(E[1],M),this._socket.uncork()):this._socket.write(E[0],M)}};e.exports=F;function x(P,E,M){typeof M=="function"&&M(E);for(let q=0;q<P._queue.length;q++){let te=P._queue[q],B=te[te.length-1];typeof B=="function"&&B(E)}}o(x,"callCallbacks");function v(P,E,M){x(P,E,M),P.onerror(E)}o(v,"onError")}}),rL=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/event-target.js"(t,e){"use strict";var{kForOnEventAttribute:n,kListener:r}=Gr(),i=Symbol("kCode"),s=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),d=Symbol("kReason"),c=Symbol("kTarget"),u=Symbol("kType"),f=Symbol("kWasClean"),h=class{static{o(this,"Event")}constructor(A){this[c]=null,this[u]=A}get target(){return this[c]}get type(){return this[u]}};Object.defineProperty(h.prototype,"target",{enumerable:!0}),Object.defineProperty(h.prototype,"type",{enumerable:!0});var g=class extends h{static{o(this,"CloseEvent")}constructor(A,T={}){super(A),this[i]=T.code===void 0?0:T.code,this[d]=T.reason===void 0?"":T.reason,this[f]=T.wasClean===void 0?!1:T.wasClean}get code(){return this[i]}get reason(){return this[d]}get wasClean(){return this[f]}};Object.defineProperty(g.prototype,"code",{enumerable:!0}),Object.defineProperty(g.prototype,"reason",{enumerable:!0}),Object.defineProperty(g.prototype,"wasClean",{enumerable:!0});var b=class extends h{static{o(this,"ErrorEvent")}constructor(A,T={}){super(A),this[a]=T.error===void 0?null:T.error,this[l]=T.message===void 0?"":T.message}get error(){return this[a]}get message(){return this[l]}};Object.defineProperty(b.prototype,"error",{enumerable:!0}),Object.defineProperty(b.prototype,"message",{enumerable:!0});var y=class extends h{static{o(this,"MessageEvent")}constructor(A,T={}){super(A),this[s]=T.data===void 0?null:T.data}get data(){return this[s]}};Object.defineProperty(y.prototype,"data",{enumerable:!0});var w={addEventListener(A,T,N={}){for(let x of this.listeners(A))if(!N[n]&&x[r]===T&&!x[n])return;let F;if(A==="message")F=o(function(v,P){let E=new y("message",{data:P?v:v.toString()});E[c]=this,S(T,this,E)},"onMessage");else if(A==="close")F=o(function(v,P){let E=new g("close",{code:v,reason:P.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});E[c]=this,S(T,this,E)},"onClose");else if(A==="error")F=o(function(v){let P=new b("error",{error:v,message:v.message});P[c]=this,S(T,this,P)},"onError");else if(A==="open")F=o(function(){let v=new h("open");v[c]=this,S(T,this,v)},"onOpen");else return;F[n]=!!N[n],F[r]=T,N.once?this.once(A,F):this.on(A,F)},removeEventListener(A,T){for(let N of this.listeners(A))if(N[r]===T&&!N[n]){this.removeListener(A,N);break}}};e.exports={CloseEvent:g,ErrorEvent:b,Event:h,EventTarget:w,MessageEvent:y};function S(A,T,N){typeof A=="object"&&A.handleEvent?A.handleEvent.call(A,N):A.call(T,N)}o(S,"callListener")}}),Cp=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/extension.js"(t,e){"use strict";var{tokenChars:n}=Ns();function r(a,l,d){a[l]===void 0?a[l]=[d]:a[l].push(d)}o(r,"push");function i(a){let l=Object.create(null),d=Object.create(null),c=!1,u=!1,f=!1,h,g,b=-1,y=-1,w=-1,S=0;for(;S<a.length;S++)if(y=a.charCodeAt(S),h===void 0)if(w===-1&&n[y]===1)b===-1&&(b=S);else if(S!==0&&(y===32||y===9))w===-1&&b!==-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S);let T=a.slice(b,w);y===44?(r(l,T,d),d=Object.create(null)):h=T,b=w=-1}else throw new SyntaxError(`Unexpected character at index ${S}`);else if(g===void 0)if(w===-1&&n[y]===1)b===-1&&(b=S);else if(y===32||y===9)w===-1&&b!==-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S),r(d,a.slice(b,w),!0),y===44&&(r(l,h,d),d=Object.create(null),h=void 0),b=w=-1}else if(y===61&&b!==-1&&w===-1)g=a.slice(b,S),b=w=-1;else throw new SyntaxError(`Unexpected character at index ${S}`);else if(u){if(n[y]!==1)throw new SyntaxError(`Unexpected character at index ${S}`);b===-1?b=S:c||(c=!0),u=!1}else if(f)if(n[y]===1)b===-1&&(b=S);else if(y===34&&b!==-1)f=!1,w=S;else if(y===92)u=!0;else throw new SyntaxError(`Unexpected character at index ${S}`);else if(y===34&&a.charCodeAt(S-1)===61)f=!0;else if(w===-1&&n[y]===1)b===-1&&(b=S);else if(b!==-1&&(y===32||y===9))w===-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S);let T=a.slice(b,w);c&&(T=T.replace(/\\/g,""),c=!1),r(d,g,T),y===44&&(r(l,h,d),d=Object.create(null),h=void 0),g=void 0,b=w=-1}else throw new SyntaxError(`Unexpected character at index ${S}`);if(b===-1||f||y===32||y===9)throw new SyntaxError("Unexpected end of input");w===-1&&(w=S);let A=a.slice(b,w);return h===void 0?r(l,A,d):(g===void 0?r(d,A,!0):c?r(d,g,A.replace(/\\/g,"")):r(d,g,A),r(l,h,d)),l}o(i,"parse");function s(a){return Object.keys(a).map(l=>{let d=a[l];return Array.isArray(d)||(d=[d]),d.map(c=>[l].concat(Object.keys(c).map(u=>{let f=c[u];return Array.isArray(f)||(f=[f]),f.map(h=>h===!0?u:`${u}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}o(s,"format"),e.exports={format:s,parse:i}}}),Pp=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket.js"(t,e){"use strict";var n=Qe("events"),r=Qe("https"),i=Qe("http"),s=Qe("net"),a=Qe("tls"),{randomBytes:l,createHash:d}=Qe("crypto"),{Duplex:c,Readable:u}=Qe("stream"),{URL:f}=Qe("url"),h=Ps(),g=CS(),b=PS(),{isBlob:y}=Ns(),{BINARY_TYPES:w,CLOSE_TIMEOUT:S,EMPTY_BUFFER:A,GUID:T,kForOnEventAttribute:N,kListener:F,kStatusCode:x,kWebSocket:v,NOOP:P}=Gr(),{EventTarget:{addEventListener:E,removeEventListener:M}}=rL(),{format:q,parse:te}=Cp(),{toBuffer:B}=kc(),H=Symbol("kAborted"),$=[8,13],_=["CONNECTING","OPEN","CLOSING","CLOSED"],j=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,C=class ot extends n{static{o(this,"_WebSocket")}constructor(L,X,oe){super(),this._binaryType=w[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=A,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=ot.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,L!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,X===void 0?X=[]:Array.isArray(X)||(typeof X=="object"&&X!==null?(oe=X,X=[]):X=[X]),ne(this,L,X,oe)):(this._autoPong=oe.autoPong,this._closeTimeout=oe.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(L){w.includes(L)&&(this._binaryType=L,this._receiver&&(this._receiver._binaryType=L))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(L,X,oe){let Q=new g({allowSynchronousEvents:oe.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:oe.maxBufferedChunks,maxFragments:oe.maxFragments,maxPayload:oe.maxPayload,skipUTF8Validation:oe.skipUTF8Validation}),me=new b(L,this._extensions,oe.generateMask);this._receiver=Q,this._sender=me,this._socket=L,Q[v]=this,me[v]=this,L[v]=this,Q.on("conclude",Ze),Q.on("drain",ut),Q.on("error",ue),Q.on("message",tt),Q.on("ping",Pe),Q.on("pong",Be),me.onerror=Lr,L.setTimeout&&L.setTimeout(0),L.setNoDelay&&L.setNoDelay(),X.length>0&&L.unshift(X),L.on("close",Gn),L.on("data",rn),L.on("end",on),L.on("error",Wn),this._readyState=ot.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=ot.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[h.extensionName]&&this._extensions[h.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=ot.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(L,X){if(this.readyState!==ot.CLOSED){if(this.readyState===ot.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===ot.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=ot.CLOSING,this._sender.close(L,X,!this._isServer,oe=>{oe||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pn(this)}}pause(){this.readyState===ot.CONNECTING||this.readyState===ot.CLOSED||(this._paused=!0,this._socket.pause())}ping(L,X,oe){if(this.readyState===ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof L=="function"?(oe=L,L=X=void 0):typeof X=="function"&&(oe=X,X=void 0),typeof L=="number"&&(L=L.toString()),this.readyState!==ot.OPEN){et(this,L,oe);return}X===void 0&&(X=!this._isServer),this._sender.ping(L||A,X,oe)}pong(L,X,oe){if(this.readyState===ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof L=="function"?(oe=L,L=X=void 0):typeof X=="function"&&(oe=X,X=void 0),typeof L=="number"&&(L=L.toString()),this.readyState!==ot.OPEN){et(this,L,oe);return}X===void 0&&(X=!this._isServer),this._sender.pong(L||A,X,oe)}resume(){this.readyState===ot.CONNECTING||this.readyState===ot.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(L,X,oe){if(this.readyState===ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof X=="function"&&(oe=X,X={}),typeof L=="number"&&(L=L.toString()),this.readyState!==ot.OPEN){et(this,L,oe);return}let Q={binary:typeof L!="string",mask:!this._isServer,compress:!0,fin:!0,...X};this._extensions[h.extensionName]||(Q.compress=!1),this._sender.send(L||A,Q,oe)}terminate(){if(this.readyState!==ot.CLOSED){if(this.readyState===ot.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=ot.CLOSING,this._socket.destroy())}}};Object.defineProperty(C,"CONNECTING",{enumerable:!0,value:_.indexOf("CONNECTING")}),Object.defineProperty(C.prototype,"CONNECTING",{enumerable:!0,value:_.indexOf("CONNECTING")}),Object.defineProperty(C,"OPEN",{enumerable:!0,value:_.indexOf("OPEN")}),Object.defineProperty(C.prototype,"OPEN",{enumerable:!0,value:_.indexOf("OPEN")}),Object.defineProperty(C,"CLOSING",{enumerable:!0,value:_.indexOf("CLOSING")}),Object.defineProperty(C.prototype,"CLOSING",{enumerable:!0,value:_.indexOf("CLOSING")}),Object.defineProperty(C,"CLOSED",{enumerable:!0,value:_.indexOf("CLOSED")}),Object.defineProperty(C.prototype,"CLOSED",{enumerable:!0,value:_.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(O=>{Object.defineProperty(C.prototype,O,{enumerable:!0})}),["open","error","close","message"].forEach(O=>{Object.defineProperty(C.prototype,`on${O}`,{enumerable:!0,get(){for(let L of this.listeners(O))if(L[N])return L[F];return null},set(L){for(let X of this.listeners(O))if(X[N]){this.removeListener(O,X);break}typeof L=="function"&&this.addEventListener(O,L,{[N]:!0})}})}),C.prototype.addEventListener=E,C.prototype.removeEventListener=M,e.exports=C;function ne(O,L,X,oe){let Q={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:S,protocolVersion:$[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...oe,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(O._autoPong=Q.autoPong,O._closeTimeout=Q.closeTimeout,!$.includes(Q.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Q.protocolVersion} (supported versions: ${$.join(", ")})`);let me;if(L instanceof f)me=L;else try{me=new f(L)}catch{throw new SyntaxError(`Invalid URL: ${L}`)}me.protocol==="http:"?me.protocol="ws:":me.protocol==="https:"&&(me.protocol="wss:"),O._url=me.href;let $t=me.protocol==="wss:",yt=me.protocol==="ws+unix:",Yt;if(me.protocol!=="ws:"&&!$t&&!yt?Yt=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:yt&&!me.pathname?Yt="The URL's pathname is empty":me.hash&&(Yt="The URL contains a fragment identifier"),Yt){let k=new SyntaxError(Yt);if(O._redirects===0)throw k;le(O,k);return}let yr=$t?443:80,m=l(16).toString("base64"),U=$t?r.request:i.request,J=new Set,Z;if(Q.createConnection=Q.createConnection||($t?$e:de),Q.defaultPort=Q.defaultPort||yr,Q.port=me.port||yr,Q.host=me.hostname.startsWith("[")?me.hostname.slice(1,-1):me.hostname,Q.headers={...Q.headers,"Sec-WebSocket-Version":Q.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},Q.path=me.pathname+me.search,Q.timeout=Q.handshakeTimeout,Q.perMessageDeflate&&(Z=new h({...Q.perMessageDeflate,isServer:!1,maxPayload:Q.maxPayload}),Q.headers["Sec-WebSocket-Extensions"]=q({[h.extensionName]:Z.offer()})),X.length){for(let k of X){if(typeof k!="string"||!j.test(k)||J.has(k))throw new SyntaxError("An invalid or duplicated subprotocol was specified");J.add(k)}Q.headers["Sec-WebSocket-Protocol"]=X.join(",")}if(Q.origin&&(Q.protocolVersion<13?Q.headers["Sec-WebSocket-Origin"]=Q.origin:Q.headers.Origin=Q.origin),(me.username||me.password)&&(Q.auth=`${me.username}:${me.password}`),yt){let k=Q.path.split(":");Q.socketPath=k[0],Q.path=k[1]}let G;if(Q.followRedirects){if(O._redirects===0){O._originalIpc=yt,O._originalSecure=$t,O._originalHostOrSocketPath=yt?Q.socketPath:me.host;let k=oe&&oe.headers;if(oe={...oe,headers:{}},k)for(let[K,z]of Object.entries(k))oe.headers[K.toLowerCase()]=z}else if(O.listenerCount("redirect")===0){let k=yt?O._originalIpc?Q.socketPath===O._originalHostOrSocketPath:!1:O._originalIpc?!1:me.host===O._originalHostOrSocketPath;(!k||O._originalSecure&&!$t)&&(delete Q.headers.authorization,delete Q.headers.cookie,k||delete Q.headers.host,Q.auth=void 0)}Q.auth&&!oe.headers.authorization&&(oe.headers.authorization="Basic "+Buffer.from(Q.auth).toString("base64")),G=O._req=U(Q),O._redirects&&O.emit("redirect",O.url,G)}else G=O._req=U(Q);Q.timeout&&G.on("timeout",()=>{xe(O,G,"Opening handshake has timed out")}),G.on("error",k=>{G===null||G[H]||(G=O._req=null,le(O,k))}),G.on("response",k=>{let K=k.headers.location,z=k.statusCode;if(K&&Q.followRedirects&&z>=300&&z<400){if(++O._redirects>Q.maxRedirects){xe(O,G,"Maximum redirects exceeded");return}G.abort();let ee;try{ee=new f(K,L)}catch{let re=new SyntaxError(`Invalid URL: ${K}`);le(O,re);return}ne(O,ee,X,oe)}else O.emit("unexpected-response",G,k)||xe(O,G,`Unexpected server response: ${k.statusCode}`)}),G.on("upgrade",(k,K,z)=>{if(O.emit("upgrade",k),O.readyState!==C.CONNECTING)return;G=O._req=null;let ee=k.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){xe(O,K,"Invalid Upgrade header");return}let ie=d("sha1").update(m+T).digest("base64");if(k.headers["sec-websocket-accept"]!==ie){xe(O,K,"Invalid Sec-WebSocket-Accept header");return}let re=k.headers["sec-websocket-protocol"],Y;if(re!==void 0?J.size?J.has(re)||(Y="Server sent an invalid subprotocol"):Y="Server sent a subprotocol but none was requested":J.size&&(Y="Server sent no subprotocol"),Y){xe(O,K,Y);return}re&&(O._protocol=re);let ae=k.headers["sec-websocket-extensions"];if(ae!==void 0){if(!Z){xe(O,K,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let pe;try{pe=te(ae)}catch{xe(O,K,"Invalid Sec-WebSocket-Extensions header");return}let be=Object.keys(pe);if(be.length!==1||be[0]!==h.extensionName){xe(O,K,"Server indicated an extension that was not requested");return}try{Z.accept(pe[h.extensionName])}catch{xe(O,K,"Invalid Sec-WebSocket-Extensions header");return}O._extensions[h.extensionName]=Z}O.setSocket(K,z,{allowSynchronousEvents:Q.allowSynchronousEvents,generateMask:Q.generateMask,maxBufferedChunks:Q.maxBufferedChunks,maxFragments:Q.maxFragments,maxPayload:Q.maxPayload,skipUTF8Validation:Q.skipUTF8Validation})}),Q.finishRequest?Q.finishRequest(G,O):G.end()}o(ne,"initAsClient");function le(O,L){O._readyState=C.CLOSING,O._errorEmitted=!0,O.emit("error",L),O.emitClose()}o(le,"emitErrorAndClose");function de(O){return O.path=O.socketPath,s.connect(O)}o(de,"netConnect");function $e(O){return O.path=void 0,!O.servername&&O.servername!==""&&(O.servername=s.isIP(O.host)?"":O.host),a.connect(O)}o($e,"tlsConnect");function xe(O,L,X){O._readyState=C.CLOSING;let oe=new Error(X);Error.captureStackTrace(oe,xe),L.setHeader?(L[H]=!0,L.abort(),L.socket&&!L.socket.destroyed&&L.socket.destroy(),process.nextTick(le,O,oe)):(L.destroy(oe),L.once("error",O.emit.bind(O,"error")),L.once("close",O.emitClose.bind(O)))}o(xe,"abortHandshake");function et(O,L,X){if(L){let oe=y(L)?L.size:B(L).length;O._socket?O._sender._bufferedBytes+=oe:O._bufferedAmount+=oe}if(X){let oe=new Error(`WebSocket is not open: readyState ${O.readyState} (${_[O.readyState]})`);process.nextTick(X,oe)}}o(et,"sendAfterClose");function Ze(O,L){let X=this[v];X._closeFrameReceived=!0,X._closeMessage=L,X._closeCode=O,X._socket[v]!==void 0&&(X._socket.removeListener("data",rn),process.nextTick(Ut,X._socket),O===1005?X.close():X.close(O,L))}o(Ze,"receiverOnConclude");function ut(){let O=this[v];O.isPaused||O._socket.resume()}o(ut,"receiverOnDrain");function ue(O){let L=this[v];L._socket[v]!==void 0&&(L._socket.removeListener("data",rn),process.nextTick(Ut,L._socket),L.close(O[x])),L._errorEmitted||(L._errorEmitted=!0,L.emit("error",O))}o(ue,"receiverOnError");function ft(){this[v].emitClose()}o(ft,"receiverOnFinish");function tt(O,L){this[v].emit("message",O,L)}o(tt,"receiverOnMessage");function Pe(O){let L=this[v];L._autoPong&&L.pong(O,!this._isServer,P),L.emit("ping",O)}o(Pe,"receiverOnPing");function Be(O){this[v].emit("pong",O)}o(Be,"receiverOnPong");function Ut(O){O.resume()}o(Ut,"resume");function Lr(O){let L=this[v];L.readyState!==C.CLOSED&&(L.readyState===C.OPEN&&(L._readyState=C.CLOSING,Pn(L)),this._socket.end(),L._errorEmitted||(L._errorEmitted=!0,L.emit("error",O)))}o(Lr,"senderOnError");function Pn(O){O._closeTimer=setTimeout(O._socket.destroy.bind(O._socket),O._closeTimeout)}o(Pn,"setCloseTimer");function Gn(){let O=this[v];if(this.removeListener("close",Gn),this.removeListener("data",rn),this.removeListener("end",on),O._readyState=C.CLOSING,!this._readableState.endEmitted&&!O._closeFrameReceived&&!O._receiver._writableState.errorEmitted&&this._readableState.length!==0){let L=this.read(this._readableState.length);O._receiver.write(L)}O._receiver.end(),this[v]=void 0,clearTimeout(O._closeTimer),O._receiver._writableState.finished||O._receiver._writableState.errorEmitted?O.emitClose():(O._receiver.on("error",ft),O._receiver.on("finish",ft))}o(Gn,"socketOnClose");function rn(O){this[v]._receiver.write(O)||this.pause()}o(rn,"socketOnData");function on(){let O=this[v];O._readyState=C.CLOSING,O._receiver.end(),this.end()}o(on,"socketOnEnd");function Wn(){let O=this[v];this.removeListener("error",Wn),this.on("error",P),O&&(O._readyState=C.CLOSING,this.destroy())}o(Wn,"socketOnError")}}),iL=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/stream.js"(t,e){"use strict";var n=Pp(),{Duplex:r}=Qe("stream");function i(d){d.emit("close")}o(i,"emitClose");function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}o(s,"duplexOnEnd");function a(d){this.removeListener("error",a),this.destroy(),this.listenerCount("error")===0&&this.emit("error",d)}o(a,"duplexOnError");function l(d,c){let u=!0,f=new r({...c,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return d.on("message",o(function(g,b){let y=!b&&f._readableState.objectMode?g.toString():g;f.push(y)||d.pause()},"message")),d.once("error",o(function(g){f.destroyed||(u=!1,f.destroy(g))},"error")),d.once("close",o(function(){f.destroyed||f.push(null)},"close")),f._destroy=function(h,g){if(d.readyState===d.CLOSED){g(h),process.nextTick(i,f);return}let b=!1;d.once("error",o(function(w){b=!0,g(w)},"error")),d.once("close",o(function(){b||g(h),process.nextTick(i,f)},"close")),u&&d.terminate()},f._final=function(h){if(d.readyState===d.CONNECTING){d.once("open",o(function(){f._final(h)},"open"));return}d._socket!==null&&(d._socket._writableState.finished?(h(),f._readableState.endEmitted&&f.destroy()):(d._socket.once("finish",o(function(){h()},"finish")),d.close()))},f._read=function(){d.isPaused&&d.resume()},f._write=function(h,g,b){if(d.readyState===d.CONNECTING){d.once("open",o(function(){f._write(h,g,b)},"open"));return}d.send(h,b)},f.on("end",s),f.on("error",a),f}o(l,"createWebSocketStream2"),e.exports=l}}),NS=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/subprotocol.js"(t,e){"use strict";var{tokenChars:n}=Ns();function r(i){let s=new Set,a=-1,l=-1,d=0;for(d;d<i.length;d++){let u=i.charCodeAt(d);if(l===-1&&n[u]===1)a===-1&&(a=d);else if(d!==0&&(u===32||u===9))l===-1&&a!==-1&&(l=d);else if(u===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let f=i.slice(a,l);if(s.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);s.add(f),a=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`)}if(a===-1||l!==-1)throw new SyntaxError("Unexpected end of input");let c=i.slice(a,d);if(s.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return s.add(c),s}o(r,"parse"),e.exports={parse:r}}}),oL=Ct({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket-server.js"(t,e){"use strict";var n=Qe("events"),r=Qe("http"),{Duplex:i}=Qe("stream"),{createHash:s}=Qe("crypto"),a=Cp(),l=Ps(),d=NS(),c=Pp(),{CLOSE_TIMEOUT:u,GUID:f,kWebSocket:h}=Gr(),g=/^[+/0-9A-Za-z]{22}==$/,b=0,y=1,w=2,S=class extends n{static{o(this,"WebSocketServer2")}constructor(v,P){if(super(),v={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...v},v.port==null&&!v.server&&!v.noServer||v.port!=null&&(v.server||v.noServer)||v.server&&v.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(v.port!=null?(this._server=r.createServer((E,M)=>{let q=r.STATUS_CODES[426];M.writeHead(426,{"Content-Length":q.length,"Content-Type":"text/plain"}),M.end(q)}),this._server.listen(v.port,v.host,v.backlog,P)):v.server&&(this._server=v.server),this._server){let E=this.emit.bind(this,"connection");this._removeListeners=A(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:o((M,q,te)=>{this.handleUpgrade(M,q,te,E)},"upgrade")})}v.perMessageDeflate===!0&&(v.perMessageDeflate={}),v.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=v,this._state=b}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(v){if(this._state===w){v&&this.once("close",()=>{v(new Error("The server is not running"))}),process.nextTick(T,this);return}if(v&&this.once("close",v),this._state!==y)if(this._state=y,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(T,this):process.nextTick(T,this);else{let P=this._server;this._removeListeners(),this._removeListeners=this._server=null,P.close(()=>{T(this)})}}shouldHandle(v){if(this.options.path){let P=v.url.indexOf("?");if((P!==-1?v.url.slice(0,P):v.url)!==this.options.path)return!1}return!0}handleUpgrade(v,P,E,M){P.on("error",N);let q=v.headers["sec-websocket-key"],te=v.headers.upgrade,B=+v.headers["sec-websocket-version"];if(v.method!=="GET"){x(this,v,P,405,"Invalid HTTP method");return}if(te===void 0||te.toLowerCase()!=="websocket"){x(this,v,P,400,"Invalid Upgrade header");return}if(q===void 0||!g.test(q)){x(this,v,P,400,"Missing or invalid Sec-WebSocket-Key header");return}if(B!==13&&B!==8){x(this,v,P,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(v)){F(P,400);return}let H=v.headers["sec-websocket-protocol"],$=new Set;if(H!==void 0)try{$=d.parse(H)}catch{x(this,v,P,400,"Invalid Sec-WebSocket-Protocol header");return}let _=v.headers["sec-websocket-extensions"],j={};if(this.options.perMessageDeflate&&_!==void 0){let C=new l({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let ne=a.parse(_);ne[l.extensionName]&&(C.accept(ne[l.extensionName]),j[l.extensionName]=C)}catch{x(this,v,P,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:v.headers[`${B===8?"sec-websocket-origin":"origin"}`],secure:!!(v.socket.authorized||v.socket.encrypted),req:v};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(ne,le,de,$e)=>{if(!ne)return F(P,le||401,de,$e);this.completeUpgrade(j,q,$,v,P,E,M)});return}if(!this.options.verifyClient(C))return F(P,401)}this.completeUpgrade(j,q,$,v,P,E,M)}completeUpgrade(v,P,E,M,q,te,B){if(!q.readable||!q.writable)return q.destroy();if(q[h])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>b)return F(q,503);let $=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(P+f).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(E.size){let j=this.options.handleProtocols?this.options.handleProtocols(E,M):E.values().next().value;j&&($.push(`Sec-WebSocket-Protocol: ${j}`),_._protocol=j)}if(v[l.extensionName]){let j=v[l.extensionName].params,C=a.format({[l.extensionName]:[j]});$.push(`Sec-WebSocket-Extensions: ${C}`),_._extensions=v}this.emit("headers",$,M),q.write($.concat(`\r
|
|
76
|
+
`).join(`\r
|
|
77
|
+
`)),q.removeListener("error",N),_.setSocket(q,te,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(_),_.on("close",()=>{this.clients.delete(_),this._shouldEmitClose&&!this.clients.size&&process.nextTick(T,this)})),B(_,M)}};e.exports=S;function A(v,P){for(let E of Object.keys(P))v.on(E,P[E]);return o(function(){for(let M of Object.keys(P))v.removeListener(M,P[M])},"removeListeners")}o(A,"addListeners");function T(v){v._state=w,v.emit("close")}o(T,"emitClose");function N(){this.destroy()}o(N,"socketOnError");function F(v,P,E,M){E=E||r.STATUS_CODES[P],M={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(E),...M},v.once("finish",v.destroy),v.end(`HTTP/1.1 ${P} ${r.STATUS_CODES[P]}\r
|
|
78
|
+
`+Object.keys(M).map(q=>`${q}: ${M[q]}`).join(`\r
|
|
79
|
+
`)+`\r
|
|
80
|
+
\r
|
|
81
|
+
`+E)}o(F,"abortHandshake");function x(v,P,E,M,q,te){if(v.listenerCount("wsClientError")){let B=new Error(q);Error.captureStackTrace(B,x),v.emit("wsClientError",B,E,P)}else F(E,M,q,te)}o(x,"abortHandshakeOrEmitwsClientError")}}),Z9=jr(iL(),1),X9=jr(Cp(),1),eZ=jr(Ps(),1),tZ=jr(CS(),1),nZ=jr(PS(),1),rZ=jr(NS(),1),sL=jr(Pp(),1),iZ=jr(oL(),1),aL=sL.default,lL=aL;$S(lL);function Fp({cwd:t=process.cwd(),env:e=process.env}={}){if(e.CONVEX_URL)return e.CONVEX_URL;for(let n of[".env.development.local",".env.local"]){let r=Dp.resolve(t,n);if(Np(r)){let i=LS(r,"VITE_CONVEX_URL");if(i)return i}}throw new Error("Could not resolve the Convex URL. Looked in $CONVEX_URL, .env.development.local, and .env.local (VITE_CONVEX_URL). Start the local backend with 'pnpm dev' (rdu) in this worktree, then retry.")}o(Fp,"resolveConvexUrl");function FS({cwd:t=process.cwd(),env:e=process.env}={}){if(e.PLEXUS_CONVEX_ADMIN_KEY)return e.PLEXUS_CONVEX_ADMIN_KEY;if(e.CONVEX_ADMIN_KEY)return e.CONVEX_ADMIN_KEY;let n=Dp.resolve(t,".env.local"),r=Np(n)?LS(n,"CONVEX_DEPLOYMENT")?.replace(/^anonymous:/,""):void 0;if(!r)throw new Error("Missing CONVEX_DEPLOYMENT in .env.local. Start local dev before importing.");let i=e.HOME??process.env.HOME;if(!i)throw new Error("Missing HOME; cannot locate rdu Convex config.");let s=Dp.resolve(i,".convex","anonymous-convex-backend-state",r,"config.json");if(!Np(s))throw new Error(`Missing rdu Convex config at ${s}. Start local dev before importing.`);let a=JSON.parse(DS(s,"utf8"));if(!a.adminKey)throw new Error("Local Convex admin key is missing.");return a.adminKey}o(FS,"readAdminKey");function LS(t,e){return DS(t,"utf8").match(new RegExp(`^${e}=(.+)$`,"m"))?.[1]?.trim()}o(LS,"readEnvValue");import{existsSync as Rx,readFileSync as Tx}from"node:fs";import gL from"node:os";import yL from"node:path";function cL(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}o(cL,"getDefaultExportFromCjs");var Ht={},vc={},Wr={},MS;function Ds(){if(MS)return Wr;MS=1;function t(a){return typeof a>"u"||a===null}o(t,"isNothing");function e(a){return typeof a=="object"&&a!==null}o(e,"isObject");function n(a){return Array.isArray(a)?a:t(a)?[]:[a]}o(n,"toArray");function r(a,l){if(l){let d=Object.keys(l);for(let c=0,u=d.length;c<u;c+=1){let f=d[c];a[f]=l[f]}}return a}o(r,"extend");function i(a,l){let d="";for(let c=0;c<l;c+=1)d+=a;return d}o(i,"repeat");function s(a){return a===0&&Number.NEGATIVE_INFINITY===1/a}return o(s,"isNegativeZero"),Wr.isNothing=t,Wr.isObject=e,Wr.toArray=n,Wr.repeat=i,Wr.isNegativeZero=s,Wr.extend=r,Wr}o(Ds,"requireCommon");var Lp,qS;function Fs(){if(qS)return Lp;qS=1;function t(n,r){let i="",s=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(i+='in "'+n.mark.name+'" '),i+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!r&&n.mark.snippet&&(i+=`
|
|
82
|
+
|
|
83
|
+
`+n.mark.snippet),s+" "+i):s}o(t,"formatError");function e(n,r){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=r,this.message=t(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return o(e,"YAMLException2"),e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e.prototype.toString=o(function(r){return this.name+": "+t(this,r)},"toString"),Lp=e,Lp}o(Fs,"requireException");var Mp,BS;function uL(){if(BS)return Mp;BS=1;let t=Ds();function e(i,s,a,l,d){let c="",u="",f=Math.floor(d/2)-1;return l-s>f&&(c=" ... ",s=l-f+c.length),a-l>f&&(u=" ...",a=l+f-u.length),{str:c+i.slice(s,a).replace(/\t/g,"\u2192")+u,pos:l-s+c.length}}o(e,"getLine");function n(i,s){return t.repeat(" ",s-i.length)+i}o(n,"padStart");function r(i,s){if(s=Object.create(s||null),!i.buffer)return null;s.maxLength||(s.maxLength=79),typeof s.indent!="number"&&(s.indent=1),typeof s.linesBefore!="number"&&(s.linesBefore=3),typeof s.linesAfter!="number"&&(s.linesAfter=2);let a=/\r?\n|\r|\0/g,l=[0],d=[],c,u=-1;for(;c=a.exec(i.buffer);)d.push(c.index),l.push(c.index+c[0].length),i.position<=c.index&&u<0&&(u=l.length-2);u<0&&(u=l.length-1);let f="",h=Math.min(i.line+s.linesAfter,d.length).toString().length,g=s.maxLength-(s.indent+h+3);for(let y=1;y<=s.linesBefore&&!(u-y<0);y++){let w=e(i.buffer,l[u-y],d[u-y],i.position-(l[u]-l[u-y]),g);f=t.repeat(" ",s.indent)+n((i.line-y+1).toString(),h)+" | "+w.str+`
|
|
84
|
+
`+f}let b=e(i.buffer,l[u],d[u],i.position,g);f+=t.repeat(" ",s.indent)+n((i.line+1).toString(),h)+" | "+b.str+`
|
|
85
|
+
`,f+=t.repeat("-",s.indent+h+3+b.pos)+`^
|
|
86
|
+
`;for(let y=1;y<=s.linesAfter&&!(u+y>=d.length);y++){let w=e(i.buffer,l[u+y],d[u+y],i.position-(l[u]-l[u+y]),g);f+=t.repeat(" ",s.indent)+n((i.line+y+1).toString(),h)+" | "+w.str+`
|
|
87
|
+
`}return f.replace(/\n$/,"")}return o(r,"makeSnippet"),Mp=r,Mp}o(uL,"requireSnippet");var qp,VS;function en(){if(VS)return qp;VS=1;let t=Fs(),e=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function r(s){let a={};return s!==null&&Object.keys(s).forEach(function(l){s[l].forEach(function(d){a[String(d)]=l})}),a}o(r,"compileStyleAliases");function i(s,a){if(a=a||{},Object.keys(a).forEach(function(l){if(e.indexOf(l)===-1)throw new t('Unknown option "'+l+'" is met in definition of "'+s+'" YAML type.')}),this.options=a,this.tag=s,this.kind=a.kind||null,this.resolve=a.resolve||function(){return!0},this.construct=a.construct||function(l){return l},this.instanceOf=a.instanceOf||null,this.predicate=a.predicate||null,this.represent=a.represent||null,this.representName=a.representName||null,this.defaultStyle=a.defaultStyle||null,this.multi=a.multi||!1,this.styleAliases=r(a.styleAliases||null),n.indexOf(this.kind)===-1)throw new t('Unknown kind "'+this.kind+'" is specified for "'+s+'" YAML type.')}return o(i,"Type2"),qp=i,qp}o(en,"requireType");var Bp,KS;function dx(){if(KS)return Bp;KS=1;let t=Fs(),e=en();function n(s,a){let l=[];return s[a].forEach(function(d){let c=l.length;l.forEach(function(u,f){u.tag===d.tag&&u.kind===d.kind&&u.multi===d.multi&&(c=f)}),l[c]=d}),l}o(n,"compileList");function r(){let s={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function a(l){l.multi?(s.multi[l.kind].push(l),s.multi.fallback.push(l)):s[l.kind][l.tag]=s.fallback[l.tag]=l}o(a,"collectType");for(let l=0,d=arguments.length;l<d;l+=1)arguments[l].forEach(a);return s}o(r,"compileMap");function i(s){return this.extend(s)}return o(i,"Schema2"),i.prototype.extend=o(function(a){let l=[],d=[];if(a instanceof e)d.push(a);else if(Array.isArray(a))d=d.concat(a);else if(a&&(Array.isArray(a.implicit)||Array.isArray(a.explicit)))a.implicit&&(l=l.concat(a.implicit)),a.explicit&&(d=d.concat(a.explicit));else throw new t("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.forEach(function(u){if(!(u instanceof e))throw new t("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(u.loadKind&&u.loadKind!=="scalar")throw new t("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(u.multi)throw new t("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),d.forEach(function(u){if(!(u instanceof e))throw new t("Specified list of YAML types (or a single Type object) contains a non-Type object.")});let c=Object.create(i.prototype);return c.implicit=(this.implicit||[]).concat(l),c.explicit=(this.explicit||[]).concat(d),c.compiledImplicit=n(c,"implicit"),c.compiledExplicit=n(c,"explicit"),c.compiledTypeMap=r(c.compiledImplicit,c.compiledExplicit),c},"extend"),Bp=i,Bp}o(dx,"requireSchema");var Vp,US;function cx(){if(US)return Vp;US=1;let t=en();return Vp=new t("tag:yaml.org,2002:str",{kind:"scalar",construct:o(function(e){return e!==null?e:""},"construct")}),Vp}o(cx,"requireStr");var Kp,jS;function ux(){if(jS)return Kp;jS=1;let t=en();return Kp=new t("tag:yaml.org,2002:seq",{kind:"sequence",construct:o(function(e){return e!==null?e:[]},"construct")}),Kp}o(ux,"requireSeq");var Up,GS;function fx(){if(GS)return Up;GS=1;let t=en();return Up=new t("tag:yaml.org,2002:map",{kind:"mapping",construct:o(function(e){return e!==null?e:{}},"construct")}),Up}o(fx,"requireMap");var jp,WS;function px(){if(WS)return jp;WS=1;let t=dx();return jp=new t({explicit:[cx(),ux(),fx()]}),jp}o(px,"requireFailsafe");var Gp,zS;function mx(){if(zS)return Gp;zS=1;let t=en();function e(i){if(i===null)return!0;let s=i.length;return s===1&&i==="~"||s===4&&(i==="null"||i==="Null"||i==="NULL")}o(e,"resolveYamlNull");function n(){return null}o(n,"constructYamlNull");function r(i){return i===null}return o(r,"isNull"),Gp=new t("tag:yaml.org,2002:null",{kind:"scalar",resolve:e,construct:n,predicate:r,represent:{canonical:o(function(){return"~"},"canonical"),lowercase:o(function(){return"null"},"lowercase"),uppercase:o(function(){return"NULL"},"uppercase"),camelcase:o(function(){return"Null"},"camelcase"),empty:o(function(){return""},"empty")},defaultStyle:"lowercase"}),Gp}o(mx,"require_null");var Wp,HS;function hx(){if(HS)return Wp;HS=1;let t=en();function e(i){if(i===null)return!1;let s=i.length;return s===4&&(i==="true"||i==="True"||i==="TRUE")||s===5&&(i==="false"||i==="False"||i==="FALSE")}o(e,"resolveYamlBoolean");function n(i){return i==="true"||i==="True"||i==="TRUE"}o(n,"constructYamlBoolean");function r(i){return Object.prototype.toString.call(i)==="[object Boolean]"}return o(r,"isBoolean"),Wp=new t("tag:yaml.org,2002:bool",{kind:"scalar",resolve:e,construct:n,predicate:r,represent:{lowercase:o(function(i){return i?"true":"false"},"lowercase"),uppercase:o(function(i){return i?"TRUE":"FALSE"},"uppercase"),camelcase:o(function(i){return i?"True":"False"},"camelcase")},defaultStyle:"lowercase"}),Wp}o(hx,"requireBool");var zp,QS;function gx(){if(QS)return zp;QS=1;let t=Ds(),e=en();function n(c){return c>=48&&c<=57||c>=65&&c<=70||c>=97&&c<=102}o(n,"isHexCode");function r(c){return c>=48&&c<=55}o(r,"isOctCode");function i(c){return c>=48&&c<=57}o(i,"isDecCode");function s(c){if(c===null)return!1;let u=c.length,f=0,h=!1;if(!u)return!1;let g=c[f];if((g==="-"||g==="+")&&(g=c[++f]),g==="0"){if(f+1===u)return!0;if(g=c[++f],g==="b"){for(f++;f<u;f++){if(g=c[f],g!=="0"&&g!=="1")return!1;h=!0}return h&&isFinite(a(c))}if(g==="x"){for(f++;f<u;f++){if(!n(c.charCodeAt(f)))return!1;h=!0}return h&&isFinite(a(c))}if(g==="o"){for(f++;f<u;f++){if(!r(c.charCodeAt(f)))return!1;h=!0}return h&&isFinite(a(c))}}for(;f<u;f++){if(!i(c.charCodeAt(f)))return!1;h=!0}return h?isFinite(a(c)):!1}o(s,"resolveYamlInteger");function a(c){let u=c,f=1,h=u[0];if((h==="-"||h==="+")&&(h==="-"&&(f=-1),u=u.slice(1),h=u[0]),u==="0")return 0;if(h==="0"){if(u[1]==="b")return f*parseInt(u.slice(2),2);if(u[1]==="x")return f*parseInt(u.slice(2),16);if(u[1]==="o")return f*parseInt(u.slice(2),8)}return f*parseInt(u,10)}o(a,"parseYamlInteger");function l(c){return a(c)}o(l,"constructYamlInteger");function d(c){return Object.prototype.toString.call(c)==="[object Number]"&&c%1===0&&!t.isNegativeZero(c)}return o(d,"isInteger"),zp=new e("tag:yaml.org,2002:int",{kind:"scalar",resolve:s,construct:l,predicate:d,represent:{binary:o(function(c){return c>=0?"0b"+c.toString(2):"-0b"+c.toString(2).slice(1)},"binary"),octal:o(function(c){return c>=0?"0o"+c.toString(8):"-0o"+c.toString(8).slice(1)},"octal"),decimal:o(function(c){return c.toString(10)},"decimal"),hexadecimal:o(function(c){return c>=0?"0x"+c.toString(16).toUpperCase():"-0x"+c.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),zp}o(gx,"requireInt");var Hp,YS;function yx(){if(YS)return Hp;YS=1;let t=Ds(),e=en(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),r=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function i(c){return c===null||!n.test(c)?!1:isFinite(parseFloat(c,10))?!0:r.test(c)}o(i,"resolveYamlFloat");function s(c){let u=c.toLowerCase(),f=u[0]==="-"?-1:1;return"+-".indexOf(u[0])>=0&&(u=u.slice(1)),u===".inf"?f===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:u===".nan"?NaN:f*parseFloat(u,10)}o(s,"constructYamlFloat");let a=/^[-+]?[0-9]+e/;function l(c,u){if(isNaN(c))switch(u){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===c)switch(u){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===c)switch(u){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(t.isNegativeZero(c))return"-0.0";let f=c.toString(10);return a.test(f)?f.replace("e",".e"):f}o(l,"representYamlFloat");function d(c){return Object.prototype.toString.call(c)==="[object Number]"&&(c%1!==0||t.isNegativeZero(c))}return o(d,"isFloat"),Hp=new e("tag:yaml.org,2002:float",{kind:"scalar",resolve:i,construct:s,predicate:d,represent:l,defaultStyle:"lowercase"}),Hp}o(yx,"requireFloat");var Qp,JS;function bx(){return JS||(JS=1,Qp=px().extend({implicit:[mx(),hx(),gx(),yx()]})),Qp}o(bx,"requireJson");var Yp,ZS;function wx(){return ZS||(ZS=1,Yp=bx()),Yp}o(wx,"requireCore");var Jp,XS;function kx(){if(XS)return Jp;XS=1;let t=en(),e=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function r(a){return a===null?!1:e.exec(a)!==null||n.exec(a)!==null}o(r,"resolveYamlTimestamp");function i(a){let l=0,d=null,c=e.exec(a);if(c===null&&(c=n.exec(a)),c===null)throw new Error("Date resolve error");let u=+c[1],f=+c[2]-1,h=+c[3];if(!c[4])return new Date(Date.UTC(u,f,h));let g=+c[4],b=+c[5],y=+c[6];if(c[7]){for(l=c[7].slice(0,3);l.length<3;)l+="0";l=+l}if(c[9]){let S=+c[10],A=+(c[11]||0);d=(S*60+A)*6e4,c[9]==="-"&&(d=-d)}let w=new Date(Date.UTC(u,f,h,g,b,y,l));return d&&w.setTime(w.getTime()-d),w}o(i,"constructYamlTimestamp");function s(a){return a.toISOString()}return o(s,"representYamlTimestamp"),Jp=new t("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:r,construct:i,instanceOf:Date,represent:s}),Jp}o(kx,"requireTimestamp");var Zp,ex;function vx(){if(ex)return Zp;ex=1;let t=en();function e(n){return n==="<<"||n===null}return o(e,"resolveYamlMerge"),Zp=new t("tag:yaml.org,2002:merge",{kind:"scalar",resolve:e}),Zp}o(vx,"requireMerge");var Xp,tx;function Sx(){if(tx)return Xp;tx=1;let t=en(),e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
88
|
+
\r`;function n(a){if(a===null)return!1;let l=0,d=a.length,c=e;for(let u=0;u<d;u++){let f=c.indexOf(a.charAt(u));if(!(f>64)){if(f<0)return!1;l+=6}}return l%8===0}o(n,"resolveYamlBinary");function r(a){let l=a.replace(/[\r\n=]/g,""),d=l.length,c=e,u=0,f=[];for(let g=0;g<d;g++)g%4===0&&g&&(f.push(u>>16&255),f.push(u>>8&255),f.push(u&255)),u=u<<6|c.indexOf(l.charAt(g));let h=d%4*6;return h===0?(f.push(u>>16&255),f.push(u>>8&255),f.push(u&255)):h===18?(f.push(u>>10&255),f.push(u>>2&255)):h===12&&f.push(u>>4&255),new Uint8Array(f)}o(r,"constructYamlBinary");function i(a){let l="",d=0,c=a.length,u=e;for(let h=0;h<c;h++)h%3===0&&h&&(l+=u[d>>18&63],l+=u[d>>12&63],l+=u[d>>6&63],l+=u[d&63]),d=(d<<8)+a[h];let f=c%3;return f===0?(l+=u[d>>18&63],l+=u[d>>12&63],l+=u[d>>6&63],l+=u[d&63]):f===2?(l+=u[d>>10&63],l+=u[d>>4&63],l+=u[d<<2&63],l+=u[64]):f===1&&(l+=u[d>>2&63],l+=u[d<<4&63],l+=u[64],l+=u[64]),l}o(i,"representYamlBinary");function s(a){return Object.prototype.toString.call(a)==="[object Uint8Array]"}return o(s,"isBinary"),Xp=new t("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:r,predicate:s,represent:i}),Xp}o(Sx,"requireBinary");var em,nx;function xx(){if(nx)return em;nx=1;let t=en(),e=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function r(s){if(s===null)return!0;let a={},l=s;for(let d=0,c=l.length;d<c;d+=1){let u=l[d],f=!1;if(n.call(u)!=="[object Object]")return!1;let h;for(h in u)if(e.call(u,h))if(!f)f=!0;else return!1;if(!f||e.call(a,h))return!1;Object.defineProperty(a,h,{value:!0})}return!0}o(r,"resolveYamlOmap");function i(s){return s!==null?s:[]}return o(i,"constructYamlOmap"),em=new t("tag:yaml.org,2002:omap",{kind:"sequence",resolve:r,construct:i}),em}o(xx,"requireOmap");var tm,rx;function Ax(){if(rx)return tm;rx=1;let t=en(),e=Object.prototype.toString;function n(i){if(i===null)return!0;let s=i,a=new Array(s.length);for(let l=0,d=s.length;l<d;l+=1){let c=s[l];if(e.call(c)!=="[object Object]")return!1;let u=Object.keys(c);if(u.length!==1)return!1;a[l]=[u[0],c[u[0]]]}return!0}o(n,"resolveYamlPairs");function r(i){if(i===null)return[];let s=i,a=new Array(s.length);for(let l=0,d=s.length;l<d;l+=1){let c=s[l],u=Object.keys(c);a[l]=[u[0],c[u[0]]]}return a}return o(r,"constructYamlPairs"),tm=new t("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:r}),tm}o(Ax,"requirePairs");var nm,ix;function Ex(){if(ix)return nm;ix=1;let t=en(),e=Object.prototype.hasOwnProperty;function n(i){if(i===null)return!0;let s=i;for(let a in s)if(e.call(s,a)&&s[a]!==null)return!1;return!0}o(n,"resolveYamlSet");function r(i){return i!==null?i:{}}return o(r,"constructYamlSet"),nm=new t("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:r}),nm}o(Ex,"requireSet");var rm,ox;function om(){return ox||(ox=1,rm=wx().extend({implicit:[kx(),vx()],explicit:[Sx(),xx(),Ax(),Ex()]})),rm}o(om,"require_default");var sx;function fL(){if(sx)return vc;sx=1;let t=Ds(),e=Fs(),n=uL(),r=om(),i=Object.prototype.hasOwnProperty,s=1,a=2,l=3,d=4,c=1,u=2,f=3,h=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,g=/[\x85\u2028\u2029]/,b=/[,\[\]{}]/,y=/^(?:!|!!|![0-9A-Za-z-]+!)$/,w=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function S(m){return Object.prototype.toString.call(m)}o(S,"_class");function A(m){return m===10||m===13}o(A,"isEol");function T(m){return m===9||m===32}o(T,"isWhiteSpace");function N(m){return m===9||m===32||m===10||m===13}o(N,"isWsOrEol");function F(m){return m===44||m===91||m===93||m===123||m===125}o(F,"isFlowIndicator");function x(m){if(m>=48&&m<=57)return m-48;let U=m|32;return U>=97&&U<=102?U-97+10:-1}o(x,"fromHexCode");function v(m){return m===120?2:m===117?4:m===85?8:0}o(v,"escapedHexLen");function P(m){return m>=48&&m<=57?m-48:-1}o(P,"fromDecimalCode");function E(m){switch(m){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
89
|
+
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}o(E,"simpleEscapeSequence");function M(m){return m<=65535?String.fromCharCode(m):String.fromCharCode((m-65536>>10)+55296,(m-65536&1023)+56320)}o(M,"charFromCodepoint");function q(m,U,J){U==="__proto__"?Object.defineProperty(m,U,{configurable:!0,enumerable:!0,writable:!0,value:J}):m[U]=J}o(q,"setProperty");let te=new Array(256),B=new Array(256);for(let m=0;m<256;m++)te[m]=E(m)?1:0,B[m]=E(m);function H(m,U){this.input=m,this.filename=U.filename||null,this.schema=U.schema||r,this.onWarning=U.onWarning||null,this.legacy=U.legacy||!1,this.json=U.json||!1,this.listener=U.listener||null,this.maxDepth=typeof U.maxDepth=="number"?U.maxDepth:100,this.maxTotalMergeKeys=typeof U.maxTotalMergeKeys=="number"?U.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=m.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}o(H,"State");function $(m,U){let J={name:m.filename,buffer:m.input.slice(0,-1),position:m.position,line:m.line,column:m.position-m.lineStart};return J.snippet=n(J),new e(U,J)}o($,"generateError");function _(m,U){throw $(m,U)}o(_,"throwError");function j(m,U){m.onWarning&&m.onWarning.call(null,$(m,U))}o(j,"throwWarning");function C(m,U,J){let Z=m.anchorMapTransactions;if(Z.length!==0){let G=Z[Z.length-1];i.call(G,U)||(G[U]={existed:i.call(m.anchorMap,U),value:m.anchorMap[U]})}m.anchorMap[U]=J}o(C,"storeAnchor");function ne(m){m.anchorMapTransactions.push(Object.create(null))}o(ne,"beginAnchorTransaction");function le(m){let U=m.anchorMapTransactions.pop(),J=m.anchorMapTransactions;if(J.length===0)return;let Z=J[J.length-1],G=Object.keys(U);for(let k=0,K=G.length;k<K;k+=1){let z=G[k];i.call(Z,z)||(Z[z]=U[z])}}o(le,"commitAnchorTransaction");function de(m){let U=m.anchorMapTransactions.pop(),J=Object.keys(U);for(let Z=J.length-1;Z>=0;Z-=1){let G=U[J[Z]];G.existed?m.anchorMap[J[Z]]=G.value:delete m.anchorMap[J[Z]]}}o(de,"rollbackAnchorTransaction");function $e(m){return{position:m.position,line:m.line,lineStart:m.lineStart,lineIndent:m.lineIndent,firstTabInLine:m.firstTabInLine,tag:m.tag,anchor:m.anchor,kind:m.kind,result:m.result}}o($e,"snapshotState");function xe(m,U){m.position=U.position,m.line=U.line,m.lineStart=U.lineStart,m.lineIndent=U.lineIndent,m.firstTabInLine=U.firstTabInLine,m.tag=U.tag,m.anchor=U.anchor,m.kind=U.kind,m.result=U.result}o(xe,"restoreState");let et={YAML:o(function(U,J,Z){U.version!==null&&_(U,"duplication of %YAML directive"),Z.length!==1&&_(U,"YAML directive accepts exactly one argument");let G=/^([0-9]+)\.([0-9]+)$/.exec(Z[0]);G===null&&_(U,"ill-formed argument of the YAML directive");let k=parseInt(G[1],10),K=parseInt(G[2],10);k!==1&&_(U,"unacceptable YAML version of the document"),U.version=Z[0],U.checkLineBreaks=K<2,K!==1&&K!==2&&j(U,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:o(function(U,J,Z){let G;Z.length!==2&&_(U,"TAG directive accepts exactly two arguments");let k=Z[0];G=Z[1],y.test(k)||_(U,"ill-formed tag handle (first argument) of the TAG directive"),i.call(U.tagMap,k)&&_(U,'there is a previously declared suffix for "'+k+'" tag handle'),w.test(G)||_(U,"ill-formed tag prefix (second argument) of the TAG directive");try{G=decodeURIComponent(G)}catch{_(U,"tag prefix is malformed: "+G)}U.tagMap[k]=G},"handleTagDirective")};function Ze(m,U,J,Z){if(U<J){let G=m.input.slice(U,J);if(Z)for(let k=0,K=G.length;k<K;k+=1){let z=G.charCodeAt(k);z===9||z>=32&&z<=1114111||_(m,"expected valid JSON character")}else h.test(G)&&_(m,"the stream contains non-printable characters");m.result+=G}}o(Ze,"captureSegment");function ut(m){m.totalMergeKeys++,m.maxTotalMergeKeys!==-1&&m.totalMergeKeys>m.maxTotalMergeKeys&&_(m,"merge keys exceeded maxTotalMergeKeys ("+m.maxTotalMergeKeys+")")}o(ut,"chargeMergeWork");function ue(m,U,J,Z){t.isObject(J)||_(m,"cannot merge mappings; the provided source object is unacceptable"),ut(m);let G=Object.keys(J);for(let k=0,K=G.length;k<K;k+=1){let z=G[k];ut(m),i.call(U,z)||(q(U,z,J[z]),Z[z]=!0)}}o(ue,"mergeMappings");function ft(m,U,J,Z,G,k,K,z,ee){if(Array.isArray(G)){G=Array.prototype.slice.call(G);for(let ie=0,re=G.length;ie<re;ie+=1)Array.isArray(G[ie])&&_(m,"nested arrays are not supported inside keys"),typeof G=="object"&&S(G[ie])==="[object Object]"&&(G[ie]="[object Object]")}if(typeof G=="object"&&S(G)==="[object Object]"&&(G="[object Object]"),G=String(G),U===null&&(U={}),Z==="tag:yaml.org,2002:merge")if(Array.isArray(k)){k.length>100&&_(m,"abnormal merge sequence size");for(let ie=0,re=k.length;ie<re;ie+=1)ue(m,U,k[ie],J)}else ue(m,U,k,J);else!m.json&&!i.call(J,G)&&i.call(U,G)&&(m.line=K||m.line,m.lineStart=z||m.lineStart,m.position=ee||m.position,_(m,"duplicated mapping key")),q(U,G,k),delete J[G];return U}o(ft,"storeMappingPair");function tt(m){let U=m.input.charCodeAt(m.position);U===10?m.position++:U===13?(m.position++,m.input.charCodeAt(m.position)===10&&m.position++):_(m,"a line break is expected"),m.line+=1,m.lineStart=m.position,m.firstTabInLine=-1}o(tt,"readLineBreak");function Pe(m,U,J){let Z=0,G=m.input.charCodeAt(m.position);for(;G!==0;){for(;T(G);)G===9&&m.firstTabInLine===-1&&(m.firstTabInLine=m.position),G=m.input.charCodeAt(++m.position);if(U&&G===35)do G=m.input.charCodeAt(++m.position);while(G!==10&&G!==13&&G!==0);if(A(G))for(tt(m),G=m.input.charCodeAt(m.position),Z++,m.lineIndent=0;G===32;)m.lineIndent++,G=m.input.charCodeAt(++m.position);else break}return J!==-1&&Z!==0&&m.lineIndent<J&&j(m,"deficient indentation"),Z}o(Pe,"skipSeparationSpace");function Be(m){let U=m.position,J=m.input.charCodeAt(U);return!!((J===45||J===46)&&J===m.input.charCodeAt(U+1)&&J===m.input.charCodeAt(U+2)&&(U+=3,J=m.input.charCodeAt(U),J===0||N(J)))}o(Be,"testDocumentSeparator");function Ut(m,U){U===1?m.result+=" ":U>1&&(m.result+=t.repeat(`
|
|
90
|
+
`,U-1))}o(Ut,"writeFoldedLines");function Lr(m,U,J){let Z,G,k,K,z,ee,ie=m.kind,re=m.result,Y=m.input.charCodeAt(m.position);if(N(Y)||F(Y)||Y===35||Y===38||Y===42||Y===33||Y===124||Y===62||Y===39||Y===34||Y===37||Y===64||Y===96)return!1;if(Y===63||Y===45){let ae=m.input.charCodeAt(m.position+1);if(N(ae)||J&&F(ae))return!1}for(m.kind="scalar",m.result="",Z=G=m.position,k=!1;Y!==0;){if(Y===58){let ae=m.input.charCodeAt(m.position+1);if(N(ae)||J&&F(ae))break}else if(Y===35){let ae=m.input.charCodeAt(m.position-1);if(N(ae))break}else{if(m.position===m.lineStart&&Be(m)||J&&F(Y))break;if(A(Y))if(K=m.line,z=m.lineStart,ee=m.lineIndent,Pe(m,!1,-1),m.lineIndent>=U){k=!0,Y=m.input.charCodeAt(m.position);continue}else{m.position=G,m.line=K,m.lineStart=z,m.lineIndent=ee;break}}k&&(Ze(m,Z,G,!1),Ut(m,m.line-K),Z=G=m.position,k=!1),T(Y)||(G=m.position+1),Y=m.input.charCodeAt(++m.position)}return Ze(m,Z,G,!1),m.result?!0:(m.kind=ie,m.result=re,!1)}o(Lr,"readPlainScalar");function Pn(m,U){let J,Z,G=m.input.charCodeAt(m.position);if(G!==39)return!1;for(m.kind="scalar",m.result="",m.position++,J=Z=m.position;(G=m.input.charCodeAt(m.position))!==0;)if(G===39)if(Ze(m,J,m.position,!0),G=m.input.charCodeAt(++m.position),G===39)J=m.position,m.position++,Z=m.position;else return!0;else A(G)?(Ze(m,J,Z,!0),Ut(m,Pe(m,!1,U)),J=Z=m.position):m.position===m.lineStart&&Be(m)?_(m,"unexpected end of the document within a single quoted scalar"):(m.position++,T(G)||(Z=m.position));_(m,"unexpected end of the stream within a single quoted scalar")}o(Pn,"readSingleQuotedScalar");function Gn(m,U){let J,Z,G,k=m.input.charCodeAt(m.position);if(k!==34)return!1;for(m.kind="scalar",m.result="",m.position++,J=Z=m.position;(k=m.input.charCodeAt(m.position))!==0;){if(k===34)return Ze(m,J,m.position,!0),m.position++,!0;if(k===92){if(Ze(m,J,m.position,!0),k=m.input.charCodeAt(++m.position),A(k))Pe(m,!1,U);else if(k<256&&te[k])m.result+=B[k],m.position++;else if((G=v(k))>0){let K=G,z=0;for(;K>0;K--)k=m.input.charCodeAt(++m.position),(G=x(k))>=0?z=(z<<4)+G:_(m,"expected hexadecimal character");m.result+=M(z),m.position++}else _(m,"unknown escape sequence");J=Z=m.position}else A(k)?(Ze(m,J,Z,!0),Ut(m,Pe(m,!1,U)),J=Z=m.position):m.position===m.lineStart&&Be(m)?_(m,"unexpected end of the document within a double quoted scalar"):(m.position++,T(k)||(Z=m.position))}_(m,"unexpected end of the stream within a double quoted scalar")}o(Gn,"readDoubleQuotedScalar");function rn(m,U){let J=!0,Z,G,k,K=m.tag,z,ee=m.anchor,ie,re,Y,ae,pe=Object.create(null),be,ye,Ae,Oe=m.input.charCodeAt(m.position);if(Oe===91)ie=93,ae=!1,z=[];else if(Oe===123)ie=125,ae=!0,z={};else return!1;for(m.anchor!==null&&C(m,m.anchor,z),Oe=m.input.charCodeAt(++m.position);Oe!==0;){if(Pe(m,!0,U),Oe=m.input.charCodeAt(m.position),Oe===ie)return m.position++,m.tag=K,m.anchor=ee,m.kind=ae?"mapping":"sequence",m.result=z,!0;if(J?Oe===44&&_(m,"expected the node content, but found ','"):_(m,"missed comma between flow collection entries"),ye=be=Ae=null,re=Y=!1,Oe===63){let Mr=m.input.charCodeAt(m.position+1);N(Mr)&&(re=Y=!0,m.position++,Pe(m,!0,U))}Z=m.line,G=m.lineStart,k=m.position,me(m,U,s,!1,!0),ye=m.tag,be=m.result,Pe(m,!0,U),Oe=m.input.charCodeAt(m.position),(Y||m.line===Z)&&Oe===58&&(re=!0,Oe=m.input.charCodeAt(++m.position),Pe(m,!0,U),me(m,U,s,!1,!0),Ae=m.result),ae?ft(m,z,pe,ye,be,Ae,Z,G,k):re?z.push(ft(m,null,pe,ye,be,Ae,Z,G,k)):z.push(be),Pe(m,!0,U),Oe=m.input.charCodeAt(m.position),Oe===44?(J=!0,Oe=m.input.charCodeAt(++m.position)):J=!1}_(m,"unexpected end of the stream within a flow collection")}o(rn,"readFlowCollection");function on(m,U){let J,Z=c,G=!1,k=!1,K=U,z=0,ee=!1,ie,re=m.input.charCodeAt(m.position);if(re===124)J=!1;else if(re===62)J=!0;else return!1;for(m.kind="scalar",m.result="";re!==0;)if(re=m.input.charCodeAt(++m.position),re===43||re===45)c===Z?Z=re===43?f:u:_(m,"repeat of a chomping mode identifier");else if((ie=P(re))>=0)ie===0?_(m,"bad explicit indentation width of a block scalar; it cannot be less than one"):k?_(m,"repeat of an indentation width identifier"):(K=U+ie-1,k=!0);else break;if(T(re)){do re=m.input.charCodeAt(++m.position);while(T(re));if(re===35)do re=m.input.charCodeAt(++m.position);while(!A(re)&&re!==0)}for(;re!==0;){for(tt(m),m.lineIndent=0,re=m.input.charCodeAt(m.position);(!k||m.lineIndent<K)&&re===32;)m.lineIndent++,re=m.input.charCodeAt(++m.position);if(!k&&m.lineIndent>K&&(K=m.lineIndent),A(re)){z++;continue}if(!k&&K===0&&_(m,"missing indentation for block scalar"),m.lineIndent<K){Z===f?m.result+=t.repeat(`
|
|
91
|
+
`,G?1+z:z):Z===c&&G&&(m.result+=`
|
|
92
|
+
`);break}J?T(re)?(ee=!0,m.result+=t.repeat(`
|
|
93
|
+
`,G?1+z:z)):ee?(ee=!1,m.result+=t.repeat(`
|
|
94
|
+
`,z+1)):z===0?G&&(m.result+=" "):m.result+=t.repeat(`
|
|
95
|
+
`,z):m.result+=t.repeat(`
|
|
96
|
+
`,G?1+z:z),G=!0,k=!0,z=0;let Y=m.position;for(;!A(re)&&re!==0;)re=m.input.charCodeAt(++m.position);Ze(m,Y,m.position,!1)}return!0}o(on,"readBlockScalar");function Wn(m,U){let J=m.tag,Z=m.anchor,G=[],k=!1;if(m.firstTabInLine!==-1)return!1;m.anchor!==null&&C(m,m.anchor,G);let K=m.input.charCodeAt(m.position);for(;K!==0&&(m.firstTabInLine!==-1&&(m.position=m.firstTabInLine,_(m,"tab characters must not be used in indentation")),K===45);){let z=m.input.charCodeAt(m.position+1);if(!N(z))break;if(k=!0,m.position++,Pe(m,!0,-1)&&m.lineIndent<=U){G.push(null),K=m.input.charCodeAt(m.position);continue}let ee=m.line;if(me(m,U,l,!1,!0),G.push(m.result),Pe(m,!0,-1),K=m.input.charCodeAt(m.position),(m.line===ee||m.lineIndent>U)&&K!==0)_(m,"bad indentation of a sequence entry");else if(m.lineIndent<U)break}return k?(m.tag=J,m.anchor=Z,m.kind="sequence",m.result=G,!0):!1}o(Wn,"readBlockSequence");function O(m,U,J){let Z,G,k,K,z=m.tag,ee=m.anchor,ie={},re=Object.create(null),Y=null,ae=null,pe=null,be=!1,ye=!1;if(m.firstTabInLine!==-1)return!1;m.anchor!==null&&C(m,m.anchor,ie);let Ae=m.input.charCodeAt(m.position);for(;Ae!==0;){!be&&m.firstTabInLine!==-1&&(m.position=m.firstTabInLine,_(m,"tab characters must not be used in indentation"));let Oe=m.input.charCodeAt(m.position+1),Mr=m.line;if((Ae===63||Ae===58)&&N(Oe))Ae===63?(be&&(ft(m,ie,re,Y,ae,null,G,k,K),Y=ae=pe=null),ye=!0,be=!0,Z=!0):be?(be=!1,Z=!0):_(m,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),m.position+=1,Ae=Oe;else{if(G=m.line,k=m.lineStart,K=m.position,!me(m,J,a,!1,!0))break;if(m.line===Mr){for(Ae=m.input.charCodeAt(m.position);T(Ae);)Ae=m.input.charCodeAt(++m.position);if(Ae===58)Ae=m.input.charCodeAt(++m.position),N(Ae)||_(m,"a whitespace character is expected after the key-value separator within a block mapping"),be&&(ft(m,ie,re,Y,ae,null,G,k,K),Y=ae=pe=null),ye=!0,be=!1,Z=!1,Y=m.tag,ae=m.result;else if(ye)_(m,"can not read an implicit mapping pair; a colon is missed");else return m.tag=z,m.anchor=ee,!0}else if(ye)_(m,"can not read a block mapping entry; a multiline key may not be an implicit key");else return m.tag=z,m.anchor=ee,!0}if((m.line===Mr||m.lineIndent>U)&&(be&&(G=m.line,k=m.lineStart,K=m.position),me(m,U,d,!0,Z)&&(be?ae=m.result:pe=m.result),be||(ft(m,ie,re,Y,ae,pe,G,k,K),Y=ae=pe=null),Pe(m,!0,-1),Ae=m.input.charCodeAt(m.position)),(m.line===Mr||m.lineIndent>U)&&Ae!==0)_(m,"bad indentation of a mapping entry");else if(m.lineIndent<U)break}return be&&ft(m,ie,re,Y,ae,null,G,k,K),ye&&(m.tag=z,m.anchor=ee,m.kind="mapping",m.result=ie),ye}o(O,"readBlockMapping");function L(m){let U=!1,J=!1,Z,G,k=m.input.charCodeAt(m.position);if(k!==33)return!1;m.tag!==null&&_(m,"duplication of a tag property"),k=m.input.charCodeAt(++m.position),k===60?(U=!0,k=m.input.charCodeAt(++m.position)):k===33?(J=!0,Z="!!",k=m.input.charCodeAt(++m.position)):Z="!";let K=m.position;if(U){do k=m.input.charCodeAt(++m.position);while(k!==0&&k!==62);m.position<m.length?(G=m.input.slice(K,m.position),k=m.input.charCodeAt(++m.position)):_(m,"unexpected end of the stream within a verbatim tag")}else{for(;k!==0&&!N(k);)k===33&&(J?_(m,"tag suffix cannot contain exclamation marks"):(Z=m.input.slice(K-1,m.position+1),y.test(Z)||_(m,"named tag handle cannot contain such characters"),J=!0,K=m.position+1)),k=m.input.charCodeAt(++m.position);G=m.input.slice(K,m.position),b.test(G)&&_(m,"tag suffix cannot contain flow indicator characters")}G&&!w.test(G)&&_(m,"tag name cannot contain such characters: "+G);try{G=decodeURIComponent(G)}catch{_(m,"tag name is malformed: "+G)}return U?m.tag=G:i.call(m.tagMap,Z)?m.tag=m.tagMap[Z]+G:Z==="!"?m.tag="!"+G:Z==="!!"?m.tag="tag:yaml.org,2002:"+G:_(m,'undeclared tag handle "'+Z+'"'),!0}o(L,"readTagProperty");function X(m){let U=m.input.charCodeAt(m.position);if(U!==38)return!1;m.anchor!==null&&_(m,"duplication of an anchor property"),U=m.input.charCodeAt(++m.position);let J=m.position;for(;U!==0&&!N(U)&&!F(U);)U=m.input.charCodeAt(++m.position);return m.position===J&&_(m,"name of an anchor node must contain at least one character"),m.anchor=m.input.slice(J,m.position),!0}o(X,"readAnchorProperty");function oe(m){let U=m.input.charCodeAt(m.position);if(U!==42)return!1;U=m.input.charCodeAt(++m.position);let J=m.position;for(;U!==0&&!N(U)&&!F(U);)U=m.input.charCodeAt(++m.position);m.position===J&&_(m,"name of an alias node must contain at least one character");let Z=m.input.slice(J,m.position);return i.call(m.anchorMap,Z)||_(m,'unidentified alias "'+Z+'"'),m.result=m.anchorMap[Z],Pe(m,!0,-1),!0}o(oe,"readAlias");function Q(m,U,J,Z){let G=$e(m);return ne(m),xe(m,U),m.tag=null,m.anchor=null,m.kind=null,m.result=null,O(m,J,Z)&&m.kind==="mapping"?(le(m),!0):(de(m),xe(m,G),!1)}o(Q,"tryReadBlockMappingFromProperty");function me(m,U,J,Z,G){let k,K,z=1,ee=!1,ie=!1,re=null,Y,ae,pe;m.depth>=m.maxDepth&&_(m,"nesting exceeded maxDepth ("+m.maxDepth+")"),m.depth+=1,m.listener!==null&&m.listener("open",m),m.tag=null,m.anchor=null,m.kind=null,m.result=null;let be=k=K=d===J||l===J;if(Z&&Pe(m,!0,-1)&&(ee=!0,m.lineIndent>U?z=1:m.lineIndent===U?z=0:m.lineIndent<U&&(z=-1)),z===1)for(;;){let ye=m.input.charCodeAt(m.position),Ae=$e(m);if(ee&&(ye===33&&m.tag!==null||ye===38&&m.anchor!==null)||!L(m)&&!X(m))break;re===null&&(re=Ae),Pe(m,!0,-1)?(ee=!0,K=be,m.lineIndent>U?z=1:m.lineIndent===U?z=0:m.lineIndent<U&&(z=-1)):K=!1}if(K&&(K=ee||G),z===1||d===J)if(s===J||a===J?ae=U:ae=U+1,pe=m.position-m.lineStart,z===1)if(K&&(Wn(m,pe)||O(m,pe,ae))||rn(m,ae))ie=!0;else{let ye=m.input.charCodeAt(m.position);re!==null&&be&&!K&&ye!==124&&ye!==62&&Q(m,re,re.position-re.lineStart,ae)||k&&on(m,ae)||Pn(m,ae)||Gn(m,ae)?ie=!0:oe(m)?(ie=!0,(m.tag!==null||m.anchor!==null)&&_(m,"alias node should not have any properties")):Lr(m,ae,s===J)&&(ie=!0,m.tag===null&&(m.tag="?")),m.anchor!==null&&C(m,m.anchor,m.result)}else z===0&&(ie=K&&Wn(m,pe));if(m.tag===null)m.anchor!==null&&C(m,m.anchor,m.result);else if(m.tag==="?"){m.result!==null&&m.kind!=="scalar"&&_(m,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+m.kind+'"');for(let ye=0,Ae=m.implicitTypes.length;ye<Ae;ye+=1)if(Y=m.implicitTypes[ye],Y.resolve(m.result)){m.result=Y.construct(m.result),m.tag=Y.tag,m.anchor!==null&&C(m,m.anchor,m.result);break}}else if(m.tag!=="!"){if(i.call(m.typeMap[m.kind||"fallback"],m.tag))Y=m.typeMap[m.kind||"fallback"][m.tag];else{Y=null;let ye=m.typeMap.multi[m.kind||"fallback"];for(let Ae=0,Oe=ye.length;Ae<Oe;Ae+=1)if(m.tag.slice(0,ye[Ae].tag.length)===ye[Ae].tag){Y=ye[Ae];break}}Y||_(m,"unknown tag !<"+m.tag+">"),m.result!==null&&Y.kind!==m.kind&&_(m,"unacceptable node kind for !<"+m.tag+'> tag; it should be "'+Y.kind+'", not "'+m.kind+'"'),Y.resolve(m.result,m.tag)?(m.result=Y.construct(m.result,m.tag),m.anchor!==null&&C(m,m.anchor,m.result)):_(m,"cannot resolve a node with !<"+m.tag+"> explicit tag")}return m.listener!==null&&m.listener("close",m),m.depth-=1,m.tag!==null||m.anchor!==null||ie}o(me,"composeNode");function $t(m){let U=m.position,J=!1,Z;for(m.version=null,m.checkLineBreaks=m.legacy,m.tagMap=Object.create(null),m.anchorMap=Object.create(null);(Z=m.input.charCodeAt(m.position))!==0&&(Pe(m,!0,-1),Z=m.input.charCodeAt(m.position),!(m.lineIndent>0||Z!==37));){J=!0,Z=m.input.charCodeAt(++m.position);let G=m.position;for(;Z!==0&&!N(Z);)Z=m.input.charCodeAt(++m.position);let k=m.input.slice(G,m.position),K=[];for(k.length<1&&_(m,"directive name must not be less than one character in length");Z!==0;){for(;T(Z);)Z=m.input.charCodeAt(++m.position);if(Z===35){do Z=m.input.charCodeAt(++m.position);while(Z!==0&&!A(Z));break}if(A(Z))break;for(G=m.position;Z!==0&&!N(Z);)Z=m.input.charCodeAt(++m.position);K.push(m.input.slice(G,m.position))}Z!==0&&tt(m),i.call(et,k)?et[k](m,k,K):j(m,'unknown document directive "'+k+'"')}if(Pe(m,!0,-1),m.lineIndent===0&&m.input.charCodeAt(m.position)===45&&m.input.charCodeAt(m.position+1)===45&&m.input.charCodeAt(m.position+2)===45?(m.position+=3,Pe(m,!0,-1)):J&&_(m,"directives end mark is expected"),me(m,m.lineIndent-1,d,!1,!0),Pe(m,!0,-1),m.checkLineBreaks&&g.test(m.input.slice(U,m.position))&&j(m,"non-ASCII line breaks are interpreted as content"),m.documents.push(m.result),m.position===m.lineStart&&Be(m)){m.input.charCodeAt(m.position)===46&&(m.position+=3,Pe(m,!0,-1));return}m.position<m.length-1&&_(m,"end of the stream or a document separator is expected")}o($t,"readDocument");function yt(m,U){m=String(m),U=U||{},m.length!==0&&(m.charCodeAt(m.length-1)!==10&&m.charCodeAt(m.length-1)!==13&&(m+=`
|
|
97
|
+
`),m.charCodeAt(0)===65279&&(m=m.slice(1)));let J=new H(m,U),Z=m.indexOf("\0");for(Z!==-1&&(J.position=Z,_(J,"null byte is not allowed in input")),J.input+="\0";J.input.charCodeAt(J.position)===32;)J.lineIndent+=1,J.position+=1;for(;J.position<J.length-1;)$t(J);return J.documents}o(yt,"loadDocuments");function Yt(m,U,J){U!==null&&typeof U=="object"&&typeof J>"u"&&(J=U,U=null);let Z=yt(m,J);if(typeof U!="function")return Z;for(let G=0,k=Z.length;G<k;G+=1)U(Z[G])}o(Yt,"loadAll2");function yr(m,U){let J=yt(m,U);if(J.length!==0){if(J.length===1)return J[0];throw new e("expected a single document in the stream, but found more")}}return o(yr,"load2"),vc.loadAll=Yt,vc.load=yr,vc}o(fL,"requireLoader");var im={},ax;function pL(){if(ax)return im;ax=1;let t=Ds(),e=Fs(),n=om(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,s=65279,a=9,l=10,d=13,c=32,u=33,f=34,h=35,g=37,b=38,y=39,w=42,S=44,A=45,T=58,N=61,F=62,x=63,v=64,P=91,E=93,M=96,q=123,te=124,B=125,H={};H[0]="\\0",H[7]="\\a",H[8]="\\b",H[9]="\\t",H[10]="\\n",H[11]="\\v",H[12]="\\f",H[13]="\\r",H[27]="\\e",H[34]='\\"',H[92]="\\\\",H[133]="\\N",H[160]="\\_",H[8232]="\\L",H[8233]="\\P";let $=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],_=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function j(k,K){if(K===null)return{};let z={},ee=Object.keys(K);for(let ie=0,re=ee.length;ie<re;ie+=1){let Y=ee[ie],ae=String(K[Y]);Y.slice(0,2)==="!!"&&(Y="tag:yaml.org,2002:"+Y.slice(2));let pe=k.compiledTypeMap.fallback[Y];pe&&i.call(pe.styleAliases,ae)&&(ae=pe.styleAliases[ae]),z[Y]=ae}return z}o(j,"compileStyleMap");function C(k){let K,z,ee=k.toString(16).toUpperCase();if(k<=255)K="x",z=2;else if(k<=65535)K="u",z=4;else if(k<=4294967295)K="U",z=8;else throw new e("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+K+t.repeat("0",z-ee.length)+ee}o(C,"encodeHex");let ne=1,le=2;function de(k){this.schema=k.schema||n,this.indent=Math.max(1,k.indent||2),this.noArrayIndent=k.noArrayIndent||!1,this.skipInvalid=k.skipInvalid||!1,this.flowLevel=t.isNothing(k.flowLevel)?-1:k.flowLevel,this.styleMap=j(this.schema,k.styles||null),this.sortKeys=k.sortKeys||!1,this.lineWidth=k.lineWidth||80,this.noRefs=k.noRefs||!1,this.noCompatMode=k.noCompatMode||!1,this.condenseFlow=k.condenseFlow||!1,this.quotingType=k.quotingType==='"'?le:ne,this.forceQuotes=k.forceQuotes||!1,this.replacer=typeof k.replacer=="function"?k.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}o(de,"State");function $e(k,K){let z=t.repeat(" ",K),ee=0,ie="",re=k.length;for(;ee<re;){let Y,ae=k.indexOf(`
|
|
98
|
+
`,ee);ae===-1?(Y=k.slice(ee),ee=re):(Y=k.slice(ee,ae+1),ee=ae+1),Y.length&&Y!==`
|
|
99
|
+
`&&(ie+=z),ie+=Y}return ie}o($e,"indentString");function xe(k,K){return`
|
|
100
|
+
`+t.repeat(" ",k.indent*K)}o(xe,"generateNextLine");function et(k,K){for(let z=0,ee=k.implicitTypes.length;z<ee;z+=1)if(k.implicitTypes[z].resolve(K))return!0;return!1}o(et,"testImplicitResolving");function Ze(k){return k===c||k===a}o(Ze,"isWhitespace");function ut(k){return k>=32&&k<=126||k>=161&&k<=55295&&k!==8232&&k!==8233||k>=57344&&k<=65533&&k!==s||k>=65536&&k<=1114111}o(ut,"isPrintable");function ue(k){return ut(k)&&k!==s&&k!==d&&k!==l}o(ue,"isNsCharOrWhitespace");function ft(k,K,z){let ee=ue(k),ie=ee&&!Ze(k);return(z?ee:ee&&k!==S&&k!==P&&k!==E&&k!==q&&k!==B)&&k!==h&&!(K===T&&!ie)||ue(K)&&!Ze(K)&&k===h||K===T&&ie}o(ft,"isPlainSafe");function tt(k){return ut(k)&&k!==s&&!Ze(k)&&k!==A&&k!==x&&k!==T&&k!==S&&k!==P&&k!==E&&k!==q&&k!==B&&k!==h&&k!==b&&k!==w&&k!==u&&k!==te&&k!==N&&k!==F&&k!==y&&k!==f&&k!==g&&k!==v&&k!==M}o(tt,"isPlainSafeFirst");function Pe(k){return!Ze(k)&&k!==T}o(Pe,"isPlainSafeLast");function Be(k,K){let z=k.charCodeAt(K),ee;return z>=55296&&z<=56319&&K+1<k.length&&(ee=k.charCodeAt(K+1),ee>=56320&&ee<=57343)?(z-55296)*1024+ee-56320+65536:z}o(Be,"codePointAt");function Ut(k){return/^\n* /.test(k)}o(Ut,"needIndentIndicator");let Lr=1,Pn=2,Gn=3,rn=4,on=5;function Wn(k,K,z,ee,ie,re,Y,ae){let pe,be=0,ye=null,Ae=!1,Oe=!1,Mr=ee!==-1,ps=-1,ms=tt(Be(k,0))&&Pe(Be(k,k.length-1));if(K||Y)for(pe=0;pe<k.length;be>=65536?pe+=2:pe++){if(be=Be(k,pe),!ut(be))return on;ms=ms&&ft(be,ye,ae),ye=be}else{for(pe=0;pe<k.length;be>=65536?pe+=2:pe++){if(be=Be(k,pe),be===l)Ae=!0,Mr&&(Oe=Oe||pe-ps-1>ee&&k[ps+1]!==" ",ps=pe);else if(!ut(be))return on;ms=ms&&ft(be,ye,ae),ye=be}Oe=Oe||Mr&&pe-ps-1>ee&&k[ps+1]!==" "}return!Ae&&!Oe?ms&&!Y&&!ie(k)?Lr:re===le?on:Pn:z>9&&Ut(k)?on:Y?re===le?on:Pn:Oe?rn:Gn}o(Wn,"chooseScalarStyle");function O(k,K,z,ee,ie){k.dump=(function(){if(K.length===0)return k.quotingType===le?'""':"''";if(!k.noCompatMode&&($.indexOf(K)!==-1||_.test(K)))return k.quotingType===le?'"'+K+'"':"'"+K+"'";let re=k.indent*Math.max(1,z),Y=k.lineWidth===-1?-1:Math.max(Math.min(k.lineWidth,40),k.lineWidth-re),ae=ee||k.flowLevel>-1&&z>=k.flowLevel;function pe(be){return et(k,be)}switch(o(pe,"testAmbiguity"),Wn(K,ae,k.indent,Y,pe,k.quotingType,k.forceQuotes&&!ee,ie)){case Lr:return K;case Pn:return"'"+K.replace(/'/g,"''")+"'";case Gn:return"|"+L(K,k.indent)+X($e(K,re));case rn:return">"+L(K,k.indent)+X($e(oe(K,Y),re));case on:return'"'+me(K)+'"';default:throw new e("impossible error: invalid scalar style")}})()}o(O,"writeScalar");function L(k,K){let z=Ut(k)?String(K):"",ee=k[k.length-1]===`
|
|
101
|
+
`,re=ee&&(k[k.length-2]===`
|
|
102
|
+
`||k===`
|
|
103
|
+
`)?"+":ee?"":"-";return z+re+`
|
|
104
|
+
`}o(L,"blockHeader");function X(k){return k[k.length-1]===`
|
|
105
|
+
`?k.slice(0,-1):k}o(X,"dropEndingNewline");function oe(k,K){let z=/(\n+)([^\n]*)/g,ee=(function(){let ae=k.indexOf(`
|
|
106
|
+
`);return ae=ae!==-1?ae:k.length,z.lastIndex=ae,Q(k.slice(0,ae),K)})(),ie=k[0]===`
|
|
107
|
+
`||k[0]===" ",re,Y;for(;Y=z.exec(k);){let ae=Y[1],pe=Y[2];re=pe[0]===" ",ee+=ae+(!ie&&!re&&pe!==""?`
|
|
108
|
+
`:"")+Q(pe,K),ie=re}return ee}o(oe,"foldString");function Q(k,K){if(k===""||k[0]===" ")return k;let z=/ [^ ]/g,ee,ie=0,re,Y=0,ae=0,pe="";for(;ee=z.exec(k);)ae=ee.index,ae-ie>K&&(re=Y>ie?Y:ae,pe+=`
|
|
109
|
+
`+k.slice(ie,re),ie=re+1),Y=ae;return pe+=`
|
|
110
|
+
`,k.length-ie>K&&Y>ie?pe+=k.slice(ie,Y)+`
|
|
111
|
+
`+k.slice(Y+1):pe+=k.slice(ie),pe.slice(1)}o(Q,"foldLine");function me(k){let K="",z=0;for(let ee=0;ee<k.length;z>=65536?ee+=2:ee++){z=Be(k,ee);let ie=H[z];!ie&&ut(z)?(K+=k[ee],z>=65536&&(K+=k[ee+1])):K+=ie||C(z)}return K}o(me,"escapeString");function $t(k,K,z){let ee="",ie=k.tag;for(let re=0,Y=z.length;re<Y;re+=1){let ae=z[re];k.replacer&&(ae=k.replacer.call(z,String(re),ae)),(U(k,K,ae,!1,!1)||typeof ae>"u"&&U(k,K,null,!1,!1))&&(ee!==""&&(ee+=","+(k.condenseFlow?"":" ")),ee+=k.dump)}k.tag=ie,k.dump="["+ee+"]"}o($t,"writeFlowSequence");function yt(k,K,z,ee){let ie="",re=k.tag;for(let Y=0,ae=z.length;Y<ae;Y+=1){let pe=z[Y];k.replacer&&(pe=k.replacer.call(z,String(Y),pe)),(U(k,K+1,pe,!0,!0,!1,!0)||typeof pe>"u"&&U(k,K+1,null,!0,!0,!1,!0))&&((!ee||ie!=="")&&(ie+=xe(k,K)),k.dump&&l===k.dump.charCodeAt(0)?ie+="-":ie+="- ",ie+=k.dump)}k.tag=re,k.dump=ie||"[]"}o(yt,"writeBlockSequence");function Yt(k,K,z){let ee="",ie=k.tag,re=Object.keys(z);for(let Y=0,ae=re.length;Y<ae;Y+=1){let pe="";ee!==""&&(pe+=", "),k.condenseFlow&&(pe+='"');let be=re[Y],ye=z[be];k.replacer&&(ye=k.replacer.call(z,be,ye)),U(k,K,be,!1,!1)&&(k.dump.length>1024&&(pe+="? "),pe+=k.dump+(k.condenseFlow?'"':"")+":"+(k.condenseFlow?"":" "),U(k,K,ye,!1,!1)&&(pe+=k.dump,ee+=pe))}k.tag=ie,k.dump="{"+ee+"}"}o(Yt,"writeFlowMapping");function yr(k,K,z,ee){let ie="",re=k.tag,Y=Object.keys(z);if(k.sortKeys===!0)Y.sort();else if(typeof k.sortKeys=="function")Y.sort(k.sortKeys);else if(k.sortKeys)throw new e("sortKeys must be a boolean or a function");for(let ae=0,pe=Y.length;ae<pe;ae+=1){let be="";(!ee||ie!=="")&&(be+=xe(k,K));let ye=Y[ae],Ae=z[ye];if(k.replacer&&(Ae=k.replacer.call(z,ye,Ae)),!U(k,K+1,ye,!0,!0,!0))continue;let Oe=k.tag!==null&&k.tag!=="?"||k.dump&&k.dump.length>1024;Oe&&(k.dump&&l===k.dump.charCodeAt(0)?be+="?":be+="? "),be+=k.dump,Oe&&(be+=xe(k,K)),U(k,K+1,Ae,!0,Oe)&&(k.dump&&l===k.dump.charCodeAt(0)?be+=":":be+=": ",be+=k.dump,ie+=be)}k.tag=re,k.dump=ie||"{}"}o(yr,"writeBlockMapping");function m(k,K,z){let ee=z?k.explicitTypes:k.implicitTypes;for(let ie=0,re=ee.length;ie<re;ie+=1){let Y=ee[ie];if((Y.instanceOf||Y.predicate)&&(!Y.instanceOf||typeof K=="object"&&K instanceof Y.instanceOf)&&(!Y.predicate||Y.predicate(K))){if(z?Y.multi&&Y.representName?k.tag=Y.representName(K):k.tag=Y.tag:k.tag="?",Y.represent){let ae=k.styleMap[Y.tag]||Y.defaultStyle,pe;if(r.call(Y.represent)==="[object Function]")pe=Y.represent(K,ae);else if(i.call(Y.represent,ae))pe=Y.represent[ae](K,ae);else throw new e("!<"+Y.tag+'> tag resolver accepts not "'+ae+'" style');k.dump=pe}return!0}}return!1}o(m,"detectType");function U(k,K,z,ee,ie,re,Y){k.tag=null,k.dump=z,m(k,z,!1)||m(k,z,!0);let ae=r.call(k.dump),pe=ee;ee&&(ee=k.flowLevel<0||k.flowLevel>K);let be=ae==="[object Object]"||ae==="[object Array]",ye,Ae;if(be&&(ye=k.duplicates.indexOf(z),Ae=ye!==-1),(k.tag!==null&&k.tag!=="?"||Ae||k.indent!==2&&K>0)&&(ie=!1),Ae&&k.usedDuplicates[ye])k.dump="*ref_"+ye;else{if(be&&Ae&&!k.usedDuplicates[ye]&&(k.usedDuplicates[ye]=!0),ae==="[object Object]")ee&&Object.keys(k.dump).length!==0?(yr(k,K,k.dump,ie),Ae&&(k.dump="&ref_"+ye+k.dump)):(Yt(k,K,k.dump),Ae&&(k.dump="&ref_"+ye+" "+k.dump));else if(ae==="[object Array]")ee&&k.dump.length!==0?(k.noArrayIndent&&!Y&&K>0?yt(k,K-1,k.dump,ie):yt(k,K,k.dump,ie),Ae&&(k.dump="&ref_"+ye+k.dump)):($t(k,K,k.dump),Ae&&(k.dump="&ref_"+ye+" "+k.dump));else if(ae==="[object String]")k.tag!=="?"&&O(k,k.dump,K,re,pe);else{if(ae==="[object Undefined]")return!1;if(k.skipInvalid)return!1;throw new e("unacceptable kind of an object to dump "+ae)}if(k.tag!==null&&k.tag!=="?"){let Oe=encodeURI(k.tag[0]==="!"?k.tag.slice(1):k.tag).replace(/!/g,"%21");k.tag[0]==="!"?Oe="!"+Oe:Oe.slice(0,18)==="tag:yaml.org,2002:"?Oe="!!"+Oe.slice(18):Oe="!<"+Oe+">",k.dump=Oe+" "+k.dump}}return!0}o(U,"writeNode");function J(k,K){let z=[],ee=[];Z(k,z,ee);let ie=ee.length;for(let re=0;re<ie;re+=1)K.duplicates.push(z[ee[re]]);K.usedDuplicates=new Array(ie)}o(J,"getDuplicateReferences");function Z(k,K,z){if(k!==null&&typeof k=="object"){let ee=K.indexOf(k);if(ee!==-1)z.indexOf(ee)===-1&&z.push(ee);else if(K.push(k),Array.isArray(k))for(let ie=0,re=k.length;ie<re;ie+=1)Z(k[ie],K,z);else{let ie=Object.keys(k);for(let re=0,Y=ie.length;re<Y;re+=1)Z(k[ie[re]],K,z)}}}o(Z,"inspectNode");function G(k,K){K=K||{};let z=new de(K);z.noRefs||J(k,z);let ee=k;return z.replacer&&(ee=z.replacer.call({"":ee},"",ee)),U(z,0,ee,!0,!0)?z.dump+`
|
|
112
|
+
`:""}return o(G,"dump2"),im.dump=G,im}o(pL,"requireDumper");var lx;function mL(){if(lx)return Ht;lx=1;let t=fL(),e=pL();function n(r,i){return function(){throw new Error("Function yaml."+r+" is removed in js-yaml 4. Use yaml."+i+" instead, which is now safe by default.")}}return o(n,"renamed"),Ht.Type=en(),Ht.Schema=dx(),Ht.FAILSAFE_SCHEMA=px(),Ht.JSON_SCHEMA=bx(),Ht.CORE_SCHEMA=wx(),Ht.DEFAULT_SCHEMA=om(),Ht.load=t.load,Ht.loadAll=t.loadAll,Ht.dump=e.dump,Ht.YAMLException=Fs(),Ht.types={binary:Sx(),float:yx(),map:fx(),null:mx(),pairs:Ax(),set:Ex(),timestamp:kx(),bool:hx(),int:gx(),merge:vx(),omap:xx(),seq:ux(),str:cx()},Ht.safeLoad=n("safeLoad","load"),Ht.safeLoadAll=n("safeLoadAll","loadAll"),Ht.safeDump=n("safeDump","dump"),Ht}o(mL,"requireJsYaml");var hL=mL(),zr=cL(hL),{Type:DZ,Schema:FZ,FAILSAFE_SCHEMA:LZ,JSON_SCHEMA:MZ,CORE_SCHEMA:qZ,DEFAULT_SCHEMA:BZ,load:VZ,loadAll:KZ,dump:UZ,YAMLException:jZ,types:GZ,safeLoad:WZ,safeLoadAll:zZ,safeDump:HZ}=zr;function Ix(t){return yL.join(gL.homedir(),".config","agent-tools",t.configFile)}o(Ix,"configPath");function Sc(t,e={}){let n=Ix(t),r=t.envPrefix,i=o(s=>process.env[`${r}_${s}`],"fromEnv");if(Rx(n)){let a=zr.load(Tx(n,"utf8"))?.[t.yamlKey];if(!a)throw new Error(`${t.name}: config ${n} has no top-level "${t.yamlKey}" key.`);let l=a.environments??{},d=e.env??i("ENV")??a.default_env??t.defaultEnv,c=l[d];if(!c){let u=Object.keys(l).join(", ")||"(none)";throw new Error(`${t.name}: unknown environment "${d}" in ${n}. Available: ${u}.`)}return{env:d,convexUrl:c.convex_url,siteUrl:c.site_url,token:c.token,tenant:e.tenant??i("TENANT")??a.default_tenant,source:"yaml"}}return{env:e.env??i("ENV")??t.defaultEnv,convexUrl:i("CONVEX_URL"),siteUrl:i("SITE_URL"),token:i("TOKEN"),tenant:e.tenant??i("TENANT"),source:"env"}}o(Sc,"loadEnvConfig");function sm(t){try{let e=new URL(t.trim());return e.hostname=e.hostname.replace(/\.$/,""),e.origin.toLowerCase()}catch{return t.trim().toLowerCase().replace(/\/+$/,"")}}o(sm,"normalizeUrl");function $x(t){let e=sm,n=Ix(t),r=new Set;if(Rx(n)){let a=zr.load(Tx(n,"utf8"))?.[t.yamlKey]?.environments?.prod;if(!a?.convex_url)throw new Error(`${t.name}: ${n} names no environments.prod.convex_url \u2014 a write cannot tell whether its target is production. Add the prod entry.`);return r.add(e(a.convex_url)),r}let i=t.envPrefix;if(process.env[`${i}_ENV`]==="prod"&&process.env[`${i}_CONVEX_URL`])return r.add(e(process.env[`${i}_CONVEX_URL`])),r;throw new Error(`${t.name}: no ${n} \u2014 a write cannot tell whether its target is production. Create the file with an environments.prod entry.`)}o($x,"knownProdConvexUrls");import{lookup as bL}from"node:dns/promises";import{isIP as _x}from"node:net";import{networkInterfaces as wL}from"node:os";function Ox(t,e){if(t===void 0)throw new Error(`${e} writes \u2014 name the environment with --env local|staging|prod (the configured default is not enough).`)}o(Ox,"requireExplicitEnv");function lm(t,e){return t.env==="prod"?!0:t.convexUrl!==void 0&&e.has(sm(t.convexUrl))}o(lm,"isProdTarget");function Cx(t,e,n,r){let i=lm(t,e);if(i&&!n)throw new Error(`${r} writes to PRODUCTION (env "${t.env}" \u2192 ${t.convexUrl??"?"}) \u2014 add --allow-prod if that is really meant.`);if(!i&&n)throw new Error(`${r}: --allow-prod is only for a production target (env "${t.env}" is not one).`)}o(Cx,"assertProdAllowed");var kL={async lookup(t){return(await bL(t,{all:!0,verbatim:!0})).map(e=>e.address)},ownAddresses(){let t=new Set;for(let e of Object.values(wL()))for(let n of e??[])t.add(am(n.address));return t}};function am(t){let e=t.toLowerCase().replace(/%.*$/,"").replace(/^\[|\]$/g,""),n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(e);if(n?.[1]!==void 0)return n[1];let r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(r?.[1]!==void 0&&r[2]!==void 0){let i=parseInt(r[1],16),s=parseInt(r[2],16);return`${i>>8}.${i&255}.${s>>8}.${s&255}`}return e}o(am,"normalizeAddress");function vL(t){return t==="::1"||_x(t)===4&&t.startsWith("127.")}o(vL,"isLoopbackAddress");async function dm(t,e=kL){let n;try{n=new URL(t).hostname}catch{throw new Error(`plexus: env "local" resolved "${t}", which is not a URL \u2014 refusing the local bootstrap.`)}let r=am(n),i;try{i=_x(r)!==0?[r]:(await e.lookup(n)).map(am)}catch(l){throw new Error(`plexus: env "local" points at ${t}, whose host does not resolve (${l.message}) \u2014 refusing the local bootstrap.`,{cause:l})}let s=e.ownAddresses(),a=i.filter(l=>!vL(l)&&!s.has(l));if(i.length===0||a.length>0)throw new Error(`plexus: env "local" points at ${t} (${a.join(", ")||"no address"}), which is not this machine \u2014 the local admin-key bootstrap runs only against this machine. Use --env staging|prod (with a token) for a remote deployment, or unset PLEXUS_CONVEX_URL.`)}o(dm,"requireThisMachineForLocalBootstrap");var SL=Object.defineProperty,xL=o((t,e,n)=>e in t?SL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),Px=o((t,e,n)=>xL(t,typeof e!="symbol"?e+"":e,n),"__publicField"),AL="color:rgb(0, 145, 255)";function EL(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}o(EL,"prefix_for_source");var xc=class{static{o(this,"DefaultLogger")}constructor(e){Px(this,"_onLogLineFuncs"),Px(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(let n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(let n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(let n of Object.values(this._onLogLineFuncs))n("error",...e)}};function cm(t){let e=new xc(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}o(cm,"instantiateDefaultLogger");function um(t){return new xc(t)}o(um,"instantiateNoopLogger");function Oi(t,e,n,r,i){let s=EL(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){let a=i.match(/^\[.*?\] /);if(a===null){t.error(`[CONVEX ${s}(${r})] Could not parse console.log`);return}let l=i.slice(1,a[0].length-2),d=i.slice(a[0].length);t.log(`%c[CONVEX ${s}(${r})] [${l}]`,AL,d)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}o(Oi,"logForFunction");var IL=Object.defineProperty,$L=o((t,e,n)=>e in t?IL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),fm=o((t,e,n)=>$L(t,typeof e!="symbol"?e+"":e,n),"__publicField"),Ci=class t{static{o(this,"Long")}constructor(e,n){fm(this,"low"),fm(this,"high"),fm(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?Fx:e>=_L?OL:new t(e%Ls|0,e/Ls|0)}toString(){return(BigInt(this.high)*BigInt(Ls)+BigInt(this.low)).toString()}equals(e){return t.isLong(e)||(e=t.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return t.isLong(e)||(e=t.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?t.fromNumber(e):new t(e.low,e.high)}},Fx=new Ci(0,0),Lx=65536,Ls=Lx*Lx,_L=Ls*Ls,OL=new Ci(-1,-1);var pm=class extends Error{static{o(this,"InvalidTokenError")}};pm.prototype.name="InvalidTokenError";var YX=480*60*60*1e3;import{createRequire as FL}from"module";import{resolve as LL}from"path";var NL;function Mx(t){NL=t}o(Mx,"setDefaultWebSocketConstructor");var vo=FL(LL(".")),ML=Object.create,qx=Object.defineProperty,qL=Object.getOwnPropertyDescriptor,Bx=Object.getOwnPropertyNames,BL=Object.getPrototypeOf,VL=Object.prototype.hasOwnProperty,Ye=(t=>typeof vo<"u"?vo:typeof Proxy<"u"?new Proxy(t,{get:o((e,n)=>(typeof vo<"u"?vo:e)[n],"get")}):t)(function(t){if(typeof vo<"u")return vo.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Pt=o((t,e)=>o(function(){return e||(0,t[Bx(t)[0]])((e={exports:{}}).exports,e),e.exports},"__require2"),"__commonJS"),KL=o((t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bx(e))!VL.call(t,i)&&i!==n&&qx(t,i,{get:o(()=>e[i],"get"),enumerable:!(r=qL(e,i))||r.enumerable});return t},"__copyProps"),Hr=o((t,e,n)=>(n=t!=null?ML(BL(t)):{},KL(e||!t||!t.__esModule?qx(n,"default",{value:t,enumerable:!0}):n,t)),"__toESM"),Qr=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/constants.js"(t,e){"use strict";var n=["nodebuffer","arraybuffer","fragments"],r=typeof Blob<"u";r&&n.push("blob"),e.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:r,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:o(()=>{},"NOOP")}}}),UL=Pt({"../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(t,e){var n=Ye("fs"),r=Ye("path"),i=Ye("os"),s=typeof __webpack_require__=="function"?__non_webpack_require__:Ye,a=process.config&&process.config.variables||{},l=!!process.env.PREBUILDS_ONLY,d=process.versions.modules,c=q()?"electron":M()?"node-webkit":"node",u=process.env.npm_config_arch||i.arch(),f=process.env.npm_config_platform||i.platform(),h=process.env.LIBC||(te(f)?"musl":"glibc"),g=process.env.ARM_VERSION||(u==="arm64"?"8":a.arm_version)||"",b=(process.versions.uv||"").split(".")[0];e.exports=y;function y(B){return s(y.resolve(B))}o(y,"load"),y.resolve=y.path=function(B){B=r.resolve(B||".");try{var H=s(r.join(B,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[H+"_PREBUILD"]&&(B=process.env[H+"_PREBUILD"])}catch{}if(!l){var $=S(r.join(B,"build/Release"),A);if($)return $;var _=S(r.join(B,"build/Debug"),A);if(_)return _}var j=le(B);if(j)return j;var C=le(r.dirname(process.execPath));if(C)return C;var ne=["platform="+f,"arch="+u,"runtime="+c,"abi="+d,"uv="+b,g?"armv="+g:"","libc="+h,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+ne+`
|
|
113
|
+
loaded from: `+B+`
|
|
114
|
+
`);function le(de){var $e=w(r.join(de,"prebuilds")).map(T),xe=$e.filter(N(f,u)).sort(F)[0];if(xe){var et=r.join(de,"prebuilds",xe.name),Ze=w(et).map(x),ut=Ze.filter(v(c,d)),ue=ut.sort(E(c))[0];if(ue)return r.join(et,ue.file)}}};function w(B){try{return n.readdirSync(B)}catch{return[]}}o(w,"readdirSync");function S(B,H){var $=w(B).filter(H);return $[0]&&r.join(B,$[0])}o(S,"getFirst");function A(B){return/\.node$/.test(B)}o(A,"matchBuild");function T(B){var H=B.split("-");if(H.length===2){var $=H[0],_=H[1].split("+");if($&&_.length&&_.every(Boolean))return{name:B,platform:$,architectures:_}}}o(T,"parseTuple");function N(B,H){return function($){return $==null||$.platform!==B?!1:$.architectures.includes(H)}}o(N,"matchTuple");function F(B,H){return B.architectures.length-H.architectures.length}o(F,"compareTuples");function x(B){var H=B.split("."),$=H.pop(),_={file:B,specificity:0};if($==="node"){for(var j=0;j<H.length;j++){var C=H[j];if(C==="node"||C==="electron"||C==="node-webkit")_.runtime=C;else if(C==="napi")_.napi=!0;else if(C.slice(0,3)==="abi")_.abi=C.slice(3);else if(C.slice(0,2)==="uv")_.uv=C.slice(2);else if(C.slice(0,4)==="armv")_.armv=C.slice(4);else if(C==="glibc"||C==="musl")_.libc=C;else continue;_.specificity++}return _}}o(x,"parseTags");function v(B,H){return function($){return!($==null||$.runtime&&$.runtime!==B&&!P($)||$.abi&&$.abi!==H&&!$.napi||$.uv&&$.uv!==b||$.armv&&$.armv!==g||$.libc&&$.libc!==h)}}o(v,"matchTags");function P(B){return B.runtime==="node"&&B.napi}o(P,"runtimeAgnostic");function E(B){return function(H,$){return H.runtime!==$.runtime?H.runtime===B?-1:1:H.abi!==$.abi?H.abi?-1:1:H.specificity!==$.specificity?H.specificity>$.specificity?-1:1:0}}o(E,"compareTags");function M(){return!!(process.versions&&process.versions.nw)}o(M,"isNwjs");function q(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}o(q,"isElectron");function te(B){return B==="linux"&&n.existsSync("/etc/alpine-release")}o(te,"isAlpine"),y.parseTags=x,y.matchTags=v,y.compareTags=E,y.parseTuple=T,y.matchTuple=N,y.compareTuples=F}}),jL=Pt({"../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(t,e){var n=typeof __webpack_require__=="function"?__non_webpack_require__:Ye;typeof n.addon=="function"?e.exports=n.addon.bind(n):e.exports=UL()}}),GL=Pt({"../node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js"(t,e){"use strict";var n=o((i,s,a,l,d)=>{for(var c=0;c<d;c++)a[l+c]=i[c]^s[c&3]},"mask"),r=o((i,s)=>{let a=i.length;for(var l=0;l<a;l++)i[l]^=s[l&3]},"unmask");e.exports={mask:n,unmask:r}}}),WL=Pt({"../node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js"(t,e){"use strict";try{e.exports=jL()(__dirname)}catch{e.exports=GL()}}}),Ac=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/buffer-util.js"(t,e){"use strict";var{EMPTY_BUFFER:n}=Qr(),r=Buffer[Symbol.species];function i(c,u){if(c.length===0)return n;if(c.length===1)return c[0];let f=Buffer.allocUnsafe(u),h=0;for(let g=0;g<c.length;g++){let b=c[g];f.set(b,h),h+=b.length}return h<u?new r(f.buffer,f.byteOffset,h):f}o(i,"concat");function s(c,u,f,h,g){for(let b=0;b<g;b++)f[h+b]=c[b]^u[b&3]}o(s,"_mask");function a(c,u){for(let f=0;f<c.length;f++)c[f]^=u[f&3]}o(a,"_unmask");function l(c){return c.length===c.buffer.byteLength?c.buffer:c.buffer.slice(c.byteOffset,c.byteOffset+c.length)}o(l,"toArrayBuffer");function d(c){if(d.readOnly=!0,Buffer.isBuffer(c))return c;let u;return c instanceof ArrayBuffer?u=new r(c):ArrayBuffer.isView(c)?u=new r(c.buffer,c.byteOffset,c.byteLength):(u=Buffer.from(c),d.readOnly=!1),u}if(o(d,"toBuffer"),e.exports={concat:i,mask:s,toArrayBuffer:l,toBuffer:d,unmask:a},!process.env.WS_NO_BUFFER_UTIL)try{let c=WL();e.exports.mask=function(u,f,h,g,b){b<48?s(u,f,h,g,b):c.mask(u,f,h,g,b)},e.exports.unmask=function(u,f){u.length<32?a(u,f):c.unmask(u,f)}}catch{}}}),zL=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/limiter.js"(t,e){"use strict";var n=Symbol("kDone"),r=Symbol("kRun"),i=class{static{o(this,"Limiter")}constructor(s){this[n]=()=>{this.pending--,this[r]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(s){this.jobs.push(s),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let s=this.jobs.shift();this.pending++,s(this[n])}}};e.exports=i}}),Ms=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/permessage-deflate.js"(t,e){"use strict";var n=Ye("zlib"),r=Ac(),i=zL(),{kStatusCode:s}=Qr(),a=Buffer[Symbol.species],l=Buffer.from([0,0,255,255]),d=Symbol("permessage-deflate"),c=Symbol("total-length"),u=Symbol("callback"),f=Symbol("buffers"),h=Symbol("error"),g,b=class{static{o(this,"PerMessageDeflate2")}constructor(A){if(this._options=A||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!g){let T=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;g=new i(T)}}static get extensionName(){return"permessage-deflate"}offer(){let A={};return this._options.serverNoContextTakeover&&(A.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(A.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(A.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?A.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(A.client_max_window_bits=!0),A}accept(A){return A=this.normalizeParams(A),this.params=this._isServer?this.acceptAsServer(A):this.acceptAsClient(A),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let A=this._deflate[u];this._deflate.close(),this._deflate=null,A&&A(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(A){let T=this._options,N=A.find(F=>!(T.serverNoContextTakeover===!1&&F.server_no_context_takeover||F.server_max_window_bits&&(T.serverMaxWindowBits===!1||typeof T.serverMaxWindowBits=="number"&&T.serverMaxWindowBits>F.server_max_window_bits)||typeof T.clientMaxWindowBits=="number"&&!F.client_max_window_bits));if(!N)throw new Error("None of the extension offers can be accepted");return T.serverNoContextTakeover&&(N.server_no_context_takeover=!0),T.clientNoContextTakeover&&(N.client_no_context_takeover=!0),typeof T.serverMaxWindowBits=="number"&&(N.server_max_window_bits=T.serverMaxWindowBits),typeof T.clientMaxWindowBits=="number"?N.client_max_window_bits=T.clientMaxWindowBits:(N.client_max_window_bits===!0||T.clientMaxWindowBits===!1)&&delete N.client_max_window_bits,N}acceptAsClient(A){let T=A[0];if(this._options.clientNoContextTakeover===!1&&T.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!T.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(T.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&T.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return T}normalizeParams(A){return A.forEach(T=>{Object.keys(T).forEach(N=>{let F=T[N];if(F.length>1)throw new Error(`Parameter "${N}" must have only a single value`);if(F=F[0],N==="client_max_window_bits"){if(F!==!0){let x=+F;if(!Number.isInteger(x)||x<8||x>15)throw new TypeError(`Invalid value for parameter "${N}": ${F}`);F=x}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${N}": ${F}`)}else if(N==="server_max_window_bits"){let x=+F;if(!Number.isInteger(x)||x<8||x>15)throw new TypeError(`Invalid value for parameter "${N}": ${F}`);F=x}else if(N==="client_no_context_takeover"||N==="server_no_context_takeover"){if(F!==!0)throw new TypeError(`Invalid value for parameter "${N}": ${F}`)}else throw new Error(`Unknown parameter "${N}"`);T[N]=F})}),A}decompress(A,T,N){g.add(F=>{this._decompress(A,T,(x,v)=>{F(),N(x,v)})})}compress(A,T,N){g.add(F=>{this._compress(A,T,(x,v)=>{F(),N(x,v)})})}_decompress(A,T,N){let F=this._isServer?"client":"server";if(!this._inflate){let x=`${F}_max_window_bits`,v=typeof this.params[x]!="number"?n.Z_DEFAULT_WINDOWBITS:this.params[x];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:v}),this._inflate[d]=this,this._inflate[c]=0,this._inflate[f]=[],this._inflate.on("error",S),this._inflate.on("data",w)}this._inflate[u]=N,this._inflate.write(A),T&&this._inflate.write(l),this._inflate.flush(()=>{let x=this._inflate[h];if(x){this._inflate.close(),this._inflate=null,N(x);return}let v=r.concat(this._inflate[f],this._inflate[c]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[c]=0,this._inflate[f]=[],T&&this.params[`${F}_no_context_takeover`]&&this._inflate.reset()),N(null,v)})}_compress(A,T,N){let F=this._isServer?"server":"client";if(!this._deflate){let x=`${F}_max_window_bits`,v=typeof this.params[x]!="number"?n.Z_DEFAULT_WINDOWBITS:this.params[x];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:v}),this._deflate[c]=0,this._deflate[f]=[],this._deflate.on("data",y)}this._deflate[u]=N,this._deflate.write(A),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let x=r.concat(this._deflate[f],this._deflate[c]);T&&(x=new a(x.buffer,x.byteOffset,x.length-4)),this._deflate[u]=null,this._deflate[c]=0,this._deflate[f]=[],T&&this.params[`${F}_no_context_takeover`]&&this._deflate.reset(),N(null,x)})}};e.exports=b;function y(A){this[f].push(A),this[c]+=A.length}o(y,"deflateOnData");function w(A){if(this[c]+=A.length,this[d]._maxPayload<1||this[c]<=this[d]._maxPayload){this[f].push(A);return}this[h]=new RangeError("Max payload size exceeded"),this[h].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[h][s]=1009,this.removeListener("data",w),this.reset()}o(w,"inflateOnData");function S(A){if(this[d]._inflate=null,this[h]){this[u](this[h]);return}A[s]=1007,this[u](A)}o(S,"inflateOnError")}}),qs=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/validation.js"(t,e){"use strict";var{isUtf8:n}=Ye("buffer"),{hasBlob:r}=Qr(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function s(d){return d>=1e3&&d<=1014&&d!==1004&&d!==1005&&d!==1006||d>=3e3&&d<=4999}o(s,"isValidStatusCode");function a(d){let c=d.length,u=0;for(;u<c;)if((d[u]&128)===0)u++;else if((d[u]&224)===192){if(u+1===c||(d[u+1]&192)!==128||(d[u]&254)===192)return!1;u+=2}else if((d[u]&240)===224){if(u+2>=c||(d[u+1]&192)!==128||(d[u+2]&192)!==128||d[u]===224&&(d[u+1]&224)===128||d[u]===237&&(d[u+1]&224)===160)return!1;u+=3}else if((d[u]&248)===240){if(u+3>=c||(d[u+1]&192)!==128||(d[u+2]&192)!==128||(d[u+3]&192)!==128||d[u]===240&&(d[u+1]&240)===128||d[u]===244&&d[u+1]>143||d[u]>244)return!1;u+=4}else return!1;return!0}o(a,"_isValidUTF8");function l(d){return r&&typeof d=="object"&&typeof d.arrayBuffer=="function"&&typeof d.type=="string"&&typeof d.stream=="function"&&(d[Symbol.toStringTag]==="Blob"||d[Symbol.toStringTag]==="File")}if(o(l,"isBlob"),e.exports={isBlob:l,isValidStatusCode:s,isValidUTF8:a,tokenChars:i},n)e.exports.isValidUTF8=function(d){return d.length<24?a(d):n(d)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let d=Ye("utf-8-validate");e.exports.isValidUTF8=function(c){return c.length<32?a(c):d(c)}}catch{}}}),Vx=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/receiver.js"(t,e){"use strict";var{Writable:n}=Ye("stream"),r=Ms(),{BINARY_TYPES:i,EMPTY_BUFFER:s,kStatusCode:a,kWebSocket:l}=Qr(),{concat:d,toArrayBuffer:c,unmask:u}=Ac(),{isValidStatusCode:f,isValidUTF8:h}=qs(),g=Buffer[Symbol.species],b=0,y=1,w=2,S=3,A=4,T=5,N=6,F=class extends n{static{o(this,"Receiver2")}constructor(x={}){super(),this._allowSynchronousEvents=x.allowSynchronousEvents!==void 0?x.allowSynchronousEvents:!0,this._binaryType=x.binaryType||i[0],this._extensions=x.extensions||{},this._isServer=!!x.isServer,this._maxBufferedChunks=x.maxBufferedChunks|0,this._maxFragments=x.maxFragments|0,this._maxPayload=x.maxPayload|0,this._skipUTF8Validation=!!x.skipUTF8Validation,this[l]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=b}_write(x,v,P){if(this._opcode===8&&this._state==b)return P();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){P(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=x.length,this._buffers.push(x),this.startLoop(P)}consume(x){if(this._bufferedBytes-=x,x===this._buffers[0].length)return this._buffers.shift();if(x<this._buffers[0].length){let P=this._buffers[0];return this._buffers[0]=new g(P.buffer,P.byteOffset+x,P.length-x),new g(P.buffer,P.byteOffset,x)}let v=Buffer.allocUnsafe(x);do{let P=this._buffers[0],E=v.length-x;x>=P.length?v.set(this._buffers.shift(),E):(v.set(new Uint8Array(P.buffer,P.byteOffset,x),E),this._buffers[0]=new g(P.buffer,P.byteOffset+x,P.length-x)),x-=P.length}while(x>0);return v}startLoop(x){this._loop=!0;do switch(this._state){case b:this.getInfo(x);break;case y:this.getPayloadLength16(x);break;case w:this.getPayloadLength64(x);break;case S:this.getMask();break;case A:this.getData(x);break;case T:case N:this._loop=!1;return}while(this._loop);this._errored||x()}getInfo(x){if(this._bufferedBytes<2){this._loop=!1;return}let v=this.consume(2);if((v[0]&48)!==0){let E=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");x(E);return}let P=(v[0]&64)===64;if(P&&!this._extensions[r.extensionName]){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(this._fin=(v[0]&128)===128,this._opcode=v[0]&15,this._payloadLength=v[1]&127,this._opcode===0){if(P){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(!this._fragmented){let E=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let E=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}this._compressed=P}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let E=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");x(E);return}if(P){let E=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");x(E);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let E=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");x(E);return}}else{let E=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");x(E);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(v[1]&128)===128,this._isServer){if(!this._masked){let E=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");x(E);return}}else if(this._masked){let E=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");x(E);return}this._payloadLength===126?this._state=y:this._payloadLength===127?this._state=w:this.haveLength(x)}getPayloadLength16(x){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(x)}getPayloadLength64(x){if(this._bufferedBytes<8){this._loop=!1;return}let v=this.consume(8),P=v.readUInt32BE(0);if(P>Math.pow(2,21)-1){let E=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");x(E);return}this._payloadLength=P*Math.pow(2,32)+v.readUInt32BE(4),this.haveLength(x)}haveLength(x){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let v=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");x(v);return}this._masked?this._state=S:this._state=A}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=A}getData(x){let v=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}v=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(v,this._mask)}if(this._opcode>7){this.controlMessage(v,x);return}if(this._compressed){this._state=T,this.decompress(v,x);return}if(v.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let P=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");x(P);return}this._messageLength=this._totalPayloadLength,this._fragments.push(v)}this.dataMessage(x)}decompress(x,v){this._extensions[r.extensionName].decompress(x,this._fin,(E,M)=>{if(E)return v(E);if(M.length){if(this._messageLength+=M.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let q=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");v(q);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let q=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");v(q);return}this._fragments.push(M)}this.dataMessage(v),this._state===b&&this.startLoop(v)})}dataMessage(x){if(!this._fin){this._state=b;return}let v=this._messageLength,P=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let E;this._binaryType==="nodebuffer"?E=d(P,v):this._binaryType==="arraybuffer"?E=c(d(P,v)):this._binaryType==="blob"?E=new Blob(P):E=P,this._allowSynchronousEvents?(this.emit("message",E,!0),this._state=b):(this._state=N,setImmediate(()=>{this.emit("message",E,!0),this._state=b,this.startLoop(x)}))}else{let E=d(P,v);if(!this._skipUTF8Validation&&!h(E)){let M=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");x(M);return}this._state===T||this._allowSynchronousEvents?(this.emit("message",E,!1),this._state=b):(this._state=N,setImmediate(()=>{this.emit("message",E,!1),this._state=b,this.startLoop(x)}))}}controlMessage(x,v){if(this._opcode===8){if(x.length===0)this._loop=!1,this.emit("conclude",1005,s),this.end();else{let P=x.readUInt16BE(0);if(!f(P)){let M=this.createError(RangeError,`invalid status code ${P}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");v(M);return}let E=new g(x.buffer,x.byteOffset+2,x.length-2);if(!this._skipUTF8Validation&&!h(E)){let M=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");v(M);return}this._loop=!1,this.emit("conclude",P,E),this.end()}this._state=b;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",x),this._state=b):(this._state=N,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",x),this._state=b,this.startLoop(v)}))}createError(x,v,P,E,M){this._loop=!1,this._errored=!0;let q=new x(P?`Invalid WebSocket frame: ${v}`:v);return Error.captureStackTrace(q,this.createError),q.code=M,q[a]=E,q}};e.exports=F}}),Kx=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/sender.js"(t,e){"use strict";var{Duplex:n}=Ye("stream"),{randomFillSync:r}=Ye("crypto"),{types:{isUint8Array:i}}=Ye("util"),s=Ms(),{EMPTY_BUFFER:a,kWebSocket:l,NOOP:d}=Qr(),{isBlob:c,isValidStatusCode:u}=qs(),{mask:f,toBuffer:h}=Ac(),g=Symbol("kByteLength"),b=Buffer.alloc(4),y=8*1024,w,S=y,A=0,T=1,N=2,F=class Pi{static{o(this,"_Sender")}constructor(E,M,q){this._extensions=M||{},q&&(this._generateMask=q,this._maskBuffer=Buffer.alloc(4)),this._socket=E,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=A,this.onerror=d,this[l]=void 0}static frame(E,M){let q,te=!1,B=2,H=!1;M.mask&&(q=M.maskBuffer||b,M.generateMask?M.generateMask(q):(S===y&&(w===void 0&&(w=Buffer.alloc(y)),r(w,0,y),S=0),q[0]=w[S++],q[1]=w[S++],q[2]=w[S++],q[3]=w[S++]),H=(q[0]|q[1]|q[2]|q[3])===0,B=6);let $;typeof E=="string"?(!M.mask||H)&&M[g]!==void 0?$=M[g]:(E=Buffer.from(E),$=E.length):($=E.length,te=M.mask&&M.readOnly&&!H);let _=$;$>=65536?(B+=8,_=127):$>125&&(B+=2,_=126);let j=Buffer.allocUnsafe(te?$+B:B);return j[0]=M.fin?M.opcode|128:M.opcode,M.rsv1&&(j[0]|=64),j[1]=_,_===126?j.writeUInt16BE($,2):_===127&&(j[2]=j[3]=0,j.writeUIntBE($,4,6)),M.mask?(j[1]|=128,j[B-4]=q[0],j[B-3]=q[1],j[B-2]=q[2],j[B-1]=q[3],H?[j,E]:te?(f(E,q,j,B,$),[j]):(f(E,q,E,0,$),[j,E])):[j,E]}close(E,M,q,te){let B;if(E===void 0)B=a;else{if(typeof E!="number"||!u(E))throw new TypeError("First argument must be a valid error code number");if(M===void 0||!M.length)B=Buffer.allocUnsafe(2),B.writeUInt16BE(E,0);else{let $=Buffer.byteLength(M);if($>123)throw new RangeError("The message must not be greater than 123 bytes");if(B=Buffer.allocUnsafe(2+$),B.writeUInt16BE(E,0),typeof M=="string")B.write(M,2);else if(i(M))B.set(M,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let H={[g]:B.length,fin:!0,generateMask:this._generateMask,mask:q,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==A?this.enqueue([this.dispatch,B,!1,H,te]):this.sendFrame(Pi.frame(B,H),te)}ping(E,M,q){let te,B;if(typeof E=="string"?(te=Buffer.byteLength(E),B=!1):c(E)?(te=E.size,B=!1):(E=h(E),te=E.length,B=h.readOnly),te>125)throw new RangeError("The data size must not be greater than 125 bytes");let H={[g]:te,fin:!0,generateMask:this._generateMask,mask:M,maskBuffer:this._maskBuffer,opcode:9,readOnly:B,rsv1:!1};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,!1,H,q]):this.getBlobData(E,!1,H,q):this._state!==A?this.enqueue([this.dispatch,E,!1,H,q]):this.sendFrame(Pi.frame(E,H),q)}pong(E,M,q){let te,B;if(typeof E=="string"?(te=Buffer.byteLength(E),B=!1):c(E)?(te=E.size,B=!1):(E=h(E),te=E.length,B=h.readOnly),te>125)throw new RangeError("The data size must not be greater than 125 bytes");let H={[g]:te,fin:!0,generateMask:this._generateMask,mask:M,maskBuffer:this._maskBuffer,opcode:10,readOnly:B,rsv1:!1};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,!1,H,q]):this.getBlobData(E,!1,H,q):this._state!==A?this.enqueue([this.dispatch,E,!1,H,q]):this.sendFrame(Pi.frame(E,H),q)}send(E,M,q){let te=this._extensions[s.extensionName],B=M.binary?2:1,H=M.compress,$,_;typeof E=="string"?($=Buffer.byteLength(E),_=!1):c(E)?($=E.size,_=!1):(E=h(E),$=E.length,_=h.readOnly),this._firstFragment?(this._firstFragment=!1,H&&te&&te.params[te._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(H=$>=te._threshold),this._compress=H):(H=!1,B=0),M.fin&&(this._firstFragment=!0);let j={[g]:$,fin:M.fin,generateMask:this._generateMask,mask:M.mask,maskBuffer:this._maskBuffer,opcode:B,readOnly:_,rsv1:H};c(E)?this._state!==A?this.enqueue([this.getBlobData,E,this._compress,j,q]):this.getBlobData(E,this._compress,j,q):this._state!==A?this.enqueue([this.dispatch,E,this._compress,j,q]):this.dispatch(E,this._compress,j,q)}getBlobData(E,M,q,te){this._bufferedBytes+=q[g],this._state=N,E.arrayBuffer().then(B=>{if(this._socket.destroyed){let $=new Error("The socket was closed while the blob was being read");process.nextTick(x,this,$,te);return}this._bufferedBytes-=q[g];let H=h(B);M?this.dispatch(H,M,q,te):(this._state=A,this.sendFrame(Pi.frame(H,q),te),this.dequeue())}).catch(B=>{process.nextTick(v,this,B,te)})}dispatch(E,M,q,te){if(!M){this.sendFrame(Pi.frame(E,q),te);return}let B=this._extensions[s.extensionName];this._bufferedBytes+=q[g],this._state=T,B.compress(E,q.fin,(H,$)=>{if(this._socket.destroyed){let _=new Error("The socket was closed while data was being compressed");x(this,_,te);return}this._bufferedBytes-=q[g],this._state=A,q.readOnly=!1,this.sendFrame(Pi.frame($,q),te),this.dequeue()})}dequeue(){for(;this._state===A&&this._queue.length;){let E=this._queue.shift();this._bufferedBytes-=E[3][g],Reflect.apply(E[0],this,E.slice(1))}}enqueue(E){this._bufferedBytes+=E[3][g],this._queue.push(E)}sendFrame(E,M){E.length===2?(this._socket.cork(),this._socket.write(E[0]),this._socket.write(E[1],M),this._socket.uncork()):this._socket.write(E[0],M)}};e.exports=F;function x(P,E,M){typeof M=="function"&&M(E);for(let q=0;q<P._queue.length;q++){let te=P._queue[q],B=te[te.length-1];typeof B=="function"&&B(E)}}o(x,"callCallbacks");function v(P,E,M){x(P,E,M),P.onerror(E)}o(v,"onError")}}),HL=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/event-target.js"(t,e){"use strict";var{kForOnEventAttribute:n,kListener:r}=Qr(),i=Symbol("kCode"),s=Symbol("kData"),a=Symbol("kError"),l=Symbol("kMessage"),d=Symbol("kReason"),c=Symbol("kTarget"),u=Symbol("kType"),f=Symbol("kWasClean"),h=class{static{o(this,"Event")}constructor(A){this[c]=null,this[u]=A}get target(){return this[c]}get type(){return this[u]}};Object.defineProperty(h.prototype,"target",{enumerable:!0}),Object.defineProperty(h.prototype,"type",{enumerable:!0});var g=class extends h{static{o(this,"CloseEvent")}constructor(A,T={}){super(A),this[i]=T.code===void 0?0:T.code,this[d]=T.reason===void 0?"":T.reason,this[f]=T.wasClean===void 0?!1:T.wasClean}get code(){return this[i]}get reason(){return this[d]}get wasClean(){return this[f]}};Object.defineProperty(g.prototype,"code",{enumerable:!0}),Object.defineProperty(g.prototype,"reason",{enumerable:!0}),Object.defineProperty(g.prototype,"wasClean",{enumerable:!0});var b=class extends h{static{o(this,"ErrorEvent")}constructor(A,T={}){super(A),this[a]=T.error===void 0?null:T.error,this[l]=T.message===void 0?"":T.message}get error(){return this[a]}get message(){return this[l]}};Object.defineProperty(b.prototype,"error",{enumerable:!0}),Object.defineProperty(b.prototype,"message",{enumerable:!0});var y=class extends h{static{o(this,"MessageEvent")}constructor(A,T={}){super(A),this[s]=T.data===void 0?null:T.data}get data(){return this[s]}};Object.defineProperty(y.prototype,"data",{enumerable:!0});var w={addEventListener(A,T,N={}){for(let x of this.listeners(A))if(!N[n]&&x[r]===T&&!x[n])return;let F;if(A==="message")F=o(function(v,P){let E=new y("message",{data:P?v:v.toString()});E[c]=this,S(T,this,E)},"onMessage");else if(A==="close")F=o(function(v,P){let E=new g("close",{code:v,reason:P.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});E[c]=this,S(T,this,E)},"onClose");else if(A==="error")F=o(function(v){let P=new b("error",{error:v,message:v.message});P[c]=this,S(T,this,P)},"onError");else if(A==="open")F=o(function(){let v=new h("open");v[c]=this,S(T,this,v)},"onOpen");else return;F[n]=!!N[n],F[r]=T,N.once?this.once(A,F):this.on(A,F)},removeEventListener(A,T){for(let N of this.listeners(A))if(N[r]===T&&!N[n]){this.removeListener(A,N);break}}};e.exports={CloseEvent:g,ErrorEvent:b,Event:h,EventTarget:w,MessageEvent:y};function S(A,T,N){typeof A=="object"&&A.handleEvent?A.handleEvent.call(A,N):A.call(T,N)}o(S,"callListener")}}),mm=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/extension.js"(t,e){"use strict";var{tokenChars:n}=qs();function r(a,l,d){a[l]===void 0?a[l]=[d]:a[l].push(d)}o(r,"push");function i(a){let l=Object.create(null),d=Object.create(null),c=!1,u=!1,f=!1,h,g,b=-1,y=-1,w=-1,S=0;for(;S<a.length;S++)if(y=a.charCodeAt(S),h===void 0)if(w===-1&&n[y]===1)b===-1&&(b=S);else if(S!==0&&(y===32||y===9))w===-1&&b!==-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S);let T=a.slice(b,w);y===44?(r(l,T,d),d=Object.create(null)):h=T,b=w=-1}else throw new SyntaxError(`Unexpected character at index ${S}`);else if(g===void 0)if(w===-1&&n[y]===1)b===-1&&(b=S);else if(y===32||y===9)w===-1&&b!==-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S),r(d,a.slice(b,w),!0),y===44&&(r(l,h,d),d=Object.create(null),h=void 0),b=w=-1}else if(y===61&&b!==-1&&w===-1)g=a.slice(b,S),b=w=-1;else throw new SyntaxError(`Unexpected character at index ${S}`);else if(u){if(n[y]!==1)throw new SyntaxError(`Unexpected character at index ${S}`);b===-1?b=S:c||(c=!0),u=!1}else if(f)if(n[y]===1)b===-1&&(b=S);else if(y===34&&b!==-1)f=!1,w=S;else if(y===92)u=!0;else throw new SyntaxError(`Unexpected character at index ${S}`);else if(y===34&&a.charCodeAt(S-1)===61)f=!0;else if(w===-1&&n[y]===1)b===-1&&(b=S);else if(b!==-1&&(y===32||y===9))w===-1&&(w=S);else if(y===59||y===44){if(b===-1)throw new SyntaxError(`Unexpected character at index ${S}`);w===-1&&(w=S);let T=a.slice(b,w);c&&(T=T.replace(/\\/g,""),c=!1),r(d,g,T),y===44&&(r(l,h,d),d=Object.create(null),h=void 0),g=void 0,b=w=-1}else throw new SyntaxError(`Unexpected character at index ${S}`);if(b===-1||f||y===32||y===9)throw new SyntaxError("Unexpected end of input");w===-1&&(w=S);let A=a.slice(b,w);return h===void 0?r(l,A,d):(g===void 0?r(d,A,!0):c?r(d,g,A.replace(/\\/g,"")):r(d,g,A),r(l,h,d)),l}o(i,"parse");function s(a){return Object.keys(a).map(l=>{let d=a[l];return Array.isArray(d)||(d=[d]),d.map(c=>[l].concat(Object.keys(c).map(u=>{let f=c[u];return Array.isArray(f)||(f=[f]),f.map(h=>h===!0?u:`${u}=${h}`).join("; ")})).join("; ")).join(", ")}).join(", ")}o(s,"format"),e.exports={format:s,parse:i}}}),hm=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket.js"(t,e){"use strict";var n=Ye("events"),r=Ye("https"),i=Ye("http"),s=Ye("net"),a=Ye("tls"),{randomBytes:l,createHash:d}=Ye("crypto"),{Duplex:c,Readable:u}=Ye("stream"),{URL:f}=Ye("url"),h=Ms(),g=Vx(),b=Kx(),{isBlob:y}=qs(),{BINARY_TYPES:w,CLOSE_TIMEOUT:S,EMPTY_BUFFER:A,GUID:T,kForOnEventAttribute:N,kListener:F,kStatusCode:x,kWebSocket:v,NOOP:P}=Qr(),{EventTarget:{addEventListener:E,removeEventListener:M}}=HL(),{format:q,parse:te}=mm(),{toBuffer:B}=Ac(),H=Symbol("kAborted"),$=[8,13],_=["CONNECTING","OPEN","CLOSING","CLOSED"],j=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,C=class st extends n{static{o(this,"_WebSocket")}constructor(L,X,oe){super(),this._binaryType=w[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=A,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=st.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,L!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,X===void 0?X=[]:Array.isArray(X)||(typeof X=="object"&&X!==null?(oe=X,X=[]):X=[X]),ne(this,L,X,oe)):(this._autoPong=oe.autoPong,this._closeTimeout=oe.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(L){w.includes(L)&&(this._binaryType=L,this._receiver&&(this._receiver._binaryType=L))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(L,X,oe){let Q=new g({allowSynchronousEvents:oe.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:oe.maxBufferedChunks,maxFragments:oe.maxFragments,maxPayload:oe.maxPayload,skipUTF8Validation:oe.skipUTF8Validation}),me=new b(L,this._extensions,oe.generateMask);this._receiver=Q,this._sender=me,this._socket=L,Q[v]=this,me[v]=this,L[v]=this,Q.on("conclude",Ze),Q.on("drain",ut),Q.on("error",ue),Q.on("message",tt),Q.on("ping",Pe),Q.on("pong",Be),me.onerror=Lr,L.setTimeout&&L.setTimeout(0),L.setNoDelay&&L.setNoDelay(),X.length>0&&L.unshift(X),L.on("close",Gn),L.on("data",rn),L.on("end",on),L.on("error",Wn),this._readyState=st.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=st.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[h.extensionName]&&this._extensions[h.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=st.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(L,X){if(this.readyState!==st.CLOSED){if(this.readyState===st.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===st.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=st.CLOSING,this._sender.close(L,X,!this._isServer,oe=>{oe||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pn(this)}}pause(){this.readyState===st.CONNECTING||this.readyState===st.CLOSED||(this._paused=!0,this._socket.pause())}ping(L,X,oe){if(this.readyState===st.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof L=="function"?(oe=L,L=X=void 0):typeof X=="function"&&(oe=X,X=void 0),typeof L=="number"&&(L=L.toString()),this.readyState!==st.OPEN){et(this,L,oe);return}X===void 0&&(X=!this._isServer),this._sender.ping(L||A,X,oe)}pong(L,X,oe){if(this.readyState===st.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof L=="function"?(oe=L,L=X=void 0):typeof X=="function"&&(oe=X,X=void 0),typeof L=="number"&&(L=L.toString()),this.readyState!==st.OPEN){et(this,L,oe);return}X===void 0&&(X=!this._isServer),this._sender.pong(L||A,X,oe)}resume(){this.readyState===st.CONNECTING||this.readyState===st.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(L,X,oe){if(this.readyState===st.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof X=="function"&&(oe=X,X={}),typeof L=="number"&&(L=L.toString()),this.readyState!==st.OPEN){et(this,L,oe);return}let Q={binary:typeof L!="string",mask:!this._isServer,compress:!0,fin:!0,...X};this._extensions[h.extensionName]||(Q.compress=!1),this._sender.send(L||A,Q,oe)}terminate(){if(this.readyState!==st.CLOSED){if(this.readyState===st.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=st.CLOSING,this._socket.destroy())}}};Object.defineProperty(C,"CONNECTING",{enumerable:!0,value:_.indexOf("CONNECTING")}),Object.defineProperty(C.prototype,"CONNECTING",{enumerable:!0,value:_.indexOf("CONNECTING")}),Object.defineProperty(C,"OPEN",{enumerable:!0,value:_.indexOf("OPEN")}),Object.defineProperty(C.prototype,"OPEN",{enumerable:!0,value:_.indexOf("OPEN")}),Object.defineProperty(C,"CLOSING",{enumerable:!0,value:_.indexOf("CLOSING")}),Object.defineProperty(C.prototype,"CLOSING",{enumerable:!0,value:_.indexOf("CLOSING")}),Object.defineProperty(C,"CLOSED",{enumerable:!0,value:_.indexOf("CLOSED")}),Object.defineProperty(C.prototype,"CLOSED",{enumerable:!0,value:_.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(O=>{Object.defineProperty(C.prototype,O,{enumerable:!0})}),["open","error","close","message"].forEach(O=>{Object.defineProperty(C.prototype,`on${O}`,{enumerable:!0,get(){for(let L of this.listeners(O))if(L[N])return L[F];return null},set(L){for(let X of this.listeners(O))if(X[N]){this.removeListener(O,X);break}typeof L=="function"&&this.addEventListener(O,L,{[N]:!0})}})}),C.prototype.addEventListener=E,C.prototype.removeEventListener=M,e.exports=C;function ne(O,L,X,oe){let Q={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:S,protocolVersion:$[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...oe,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(O._autoPong=Q.autoPong,O._closeTimeout=Q.closeTimeout,!$.includes(Q.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Q.protocolVersion} (supported versions: ${$.join(", ")})`);let me;if(L instanceof f)me=L;else try{me=new f(L)}catch{throw new SyntaxError(`Invalid URL: ${L}`)}me.protocol==="http:"?me.protocol="ws:":me.protocol==="https:"&&(me.protocol="wss:"),O._url=me.href;let $t=me.protocol==="wss:",yt=me.protocol==="ws+unix:",Yt;if(me.protocol!=="ws:"&&!$t&&!yt?Yt=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:yt&&!me.pathname?Yt="The URL's pathname is empty":me.hash&&(Yt="The URL contains a fragment identifier"),Yt){let k=new SyntaxError(Yt);if(O._redirects===0)throw k;le(O,k);return}let yr=$t?443:80,m=l(16).toString("base64"),U=$t?r.request:i.request,J=new Set,Z;if(Q.createConnection=Q.createConnection||($t?$e:de),Q.defaultPort=Q.defaultPort||yr,Q.port=me.port||yr,Q.host=me.hostname.startsWith("[")?me.hostname.slice(1,-1):me.hostname,Q.headers={...Q.headers,"Sec-WebSocket-Version":Q.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},Q.path=me.pathname+me.search,Q.timeout=Q.handshakeTimeout,Q.perMessageDeflate&&(Z=new h({...Q.perMessageDeflate,isServer:!1,maxPayload:Q.maxPayload}),Q.headers["Sec-WebSocket-Extensions"]=q({[h.extensionName]:Z.offer()})),X.length){for(let k of X){if(typeof k!="string"||!j.test(k)||J.has(k))throw new SyntaxError("An invalid or duplicated subprotocol was specified");J.add(k)}Q.headers["Sec-WebSocket-Protocol"]=X.join(",")}if(Q.origin&&(Q.protocolVersion<13?Q.headers["Sec-WebSocket-Origin"]=Q.origin:Q.headers.Origin=Q.origin),(me.username||me.password)&&(Q.auth=`${me.username}:${me.password}`),yt){let k=Q.path.split(":");Q.socketPath=k[0],Q.path=k[1]}let G;if(Q.followRedirects){if(O._redirects===0){O._originalIpc=yt,O._originalSecure=$t,O._originalHostOrSocketPath=yt?Q.socketPath:me.host;let k=oe&&oe.headers;if(oe={...oe,headers:{}},k)for(let[K,z]of Object.entries(k))oe.headers[K.toLowerCase()]=z}else if(O.listenerCount("redirect")===0){let k=yt?O._originalIpc?Q.socketPath===O._originalHostOrSocketPath:!1:O._originalIpc?!1:me.host===O._originalHostOrSocketPath;(!k||O._originalSecure&&!$t)&&(delete Q.headers.authorization,delete Q.headers.cookie,k||delete Q.headers.host,Q.auth=void 0)}Q.auth&&!oe.headers.authorization&&(oe.headers.authorization="Basic "+Buffer.from(Q.auth).toString("base64")),G=O._req=U(Q),O._redirects&&O.emit("redirect",O.url,G)}else G=O._req=U(Q);Q.timeout&&G.on("timeout",()=>{xe(O,G,"Opening handshake has timed out")}),G.on("error",k=>{G===null||G[H]||(G=O._req=null,le(O,k))}),G.on("response",k=>{let K=k.headers.location,z=k.statusCode;if(K&&Q.followRedirects&&z>=300&&z<400){if(++O._redirects>Q.maxRedirects){xe(O,G,"Maximum redirects exceeded");return}G.abort();let ee;try{ee=new f(K,L)}catch{let re=new SyntaxError(`Invalid URL: ${K}`);le(O,re);return}ne(O,ee,X,oe)}else O.emit("unexpected-response",G,k)||xe(O,G,`Unexpected server response: ${k.statusCode}`)}),G.on("upgrade",(k,K,z)=>{if(O.emit("upgrade",k),O.readyState!==C.CONNECTING)return;G=O._req=null;let ee=k.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){xe(O,K,"Invalid Upgrade header");return}let ie=d("sha1").update(m+T).digest("base64");if(k.headers["sec-websocket-accept"]!==ie){xe(O,K,"Invalid Sec-WebSocket-Accept header");return}let re=k.headers["sec-websocket-protocol"],Y;if(re!==void 0?J.size?J.has(re)||(Y="Server sent an invalid subprotocol"):Y="Server sent a subprotocol but none was requested":J.size&&(Y="Server sent no subprotocol"),Y){xe(O,K,Y);return}re&&(O._protocol=re);let ae=k.headers["sec-websocket-extensions"];if(ae!==void 0){if(!Z){xe(O,K,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let pe;try{pe=te(ae)}catch{xe(O,K,"Invalid Sec-WebSocket-Extensions header");return}let be=Object.keys(pe);if(be.length!==1||be[0]!==h.extensionName){xe(O,K,"Server indicated an extension that was not requested");return}try{Z.accept(pe[h.extensionName])}catch{xe(O,K,"Invalid Sec-WebSocket-Extensions header");return}O._extensions[h.extensionName]=Z}O.setSocket(K,z,{allowSynchronousEvents:Q.allowSynchronousEvents,generateMask:Q.generateMask,maxBufferedChunks:Q.maxBufferedChunks,maxFragments:Q.maxFragments,maxPayload:Q.maxPayload,skipUTF8Validation:Q.skipUTF8Validation})}),Q.finishRequest?Q.finishRequest(G,O):G.end()}o(ne,"initAsClient");function le(O,L){O._readyState=C.CLOSING,O._errorEmitted=!0,O.emit("error",L),O.emitClose()}o(le,"emitErrorAndClose");function de(O){return O.path=O.socketPath,s.connect(O)}o(de,"netConnect");function $e(O){return O.path=void 0,!O.servername&&O.servername!==""&&(O.servername=s.isIP(O.host)?"":O.host),a.connect(O)}o($e,"tlsConnect");function xe(O,L,X){O._readyState=C.CLOSING;let oe=new Error(X);Error.captureStackTrace(oe,xe),L.setHeader?(L[H]=!0,L.abort(),L.socket&&!L.socket.destroyed&&L.socket.destroy(),process.nextTick(le,O,oe)):(L.destroy(oe),L.once("error",O.emit.bind(O,"error")),L.once("close",O.emitClose.bind(O)))}o(xe,"abortHandshake");function et(O,L,X){if(L){let oe=y(L)?L.size:B(L).length;O._socket?O._sender._bufferedBytes+=oe:O._bufferedAmount+=oe}if(X){let oe=new Error(`WebSocket is not open: readyState ${O.readyState} (${_[O.readyState]})`);process.nextTick(X,oe)}}o(et,"sendAfterClose");function Ze(O,L){let X=this[v];X._closeFrameReceived=!0,X._closeMessage=L,X._closeCode=O,X._socket[v]!==void 0&&(X._socket.removeListener("data",rn),process.nextTick(Ut,X._socket),O===1005?X.close():X.close(O,L))}o(Ze,"receiverOnConclude");function ut(){let O=this[v];O.isPaused||O._socket.resume()}o(ut,"receiverOnDrain");function ue(O){let L=this[v];L._socket[v]!==void 0&&(L._socket.removeListener("data",rn),process.nextTick(Ut,L._socket),L.close(O[x])),L._errorEmitted||(L._errorEmitted=!0,L.emit("error",O))}o(ue,"receiverOnError");function ft(){this[v].emitClose()}o(ft,"receiverOnFinish");function tt(O,L){this[v].emit("message",O,L)}o(tt,"receiverOnMessage");function Pe(O){let L=this[v];L._autoPong&&L.pong(O,!this._isServer,P),L.emit("ping",O)}o(Pe,"receiverOnPing");function Be(O){this[v].emit("pong",O)}o(Be,"receiverOnPong");function Ut(O){O.resume()}o(Ut,"resume");function Lr(O){let L=this[v];L.readyState!==C.CLOSED&&(L.readyState===C.OPEN&&(L._readyState=C.CLOSING,Pn(L)),this._socket.end(),L._errorEmitted||(L._errorEmitted=!0,L.emit("error",O)))}o(Lr,"senderOnError");function Pn(O){O._closeTimer=setTimeout(O._socket.destroy.bind(O._socket),O._closeTimeout)}o(Pn,"setCloseTimer");function Gn(){let O=this[v];if(this.removeListener("close",Gn),this.removeListener("data",rn),this.removeListener("end",on),O._readyState=C.CLOSING,!this._readableState.endEmitted&&!O._closeFrameReceived&&!O._receiver._writableState.errorEmitted&&this._readableState.length!==0){let L=this.read(this._readableState.length);O._receiver.write(L)}O._receiver.end(),this[v]=void 0,clearTimeout(O._closeTimer),O._receiver._writableState.finished||O._receiver._writableState.errorEmitted?O.emitClose():(O._receiver.on("error",ft),O._receiver.on("finish",ft))}o(Gn,"socketOnClose");function rn(O){this[v]._receiver.write(O)||this.pause()}o(rn,"socketOnData");function on(){let O=this[v];O._readyState=C.CLOSING,O._receiver.end(),this.end()}o(on,"socketOnEnd");function Wn(){let O=this[v];this.removeListener("error",Wn),this.on("error",P),O&&(O._readyState=C.CLOSING,this.destroy())}o(Wn,"socketOnError")}}),QL=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/stream.js"(t,e){"use strict";var n=hm(),{Duplex:r}=Ye("stream");function i(d){d.emit("close")}o(i,"emitClose");function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}o(s,"duplexOnEnd");function a(d){this.removeListener("error",a),this.destroy(),this.listenerCount("error")===0&&this.emit("error",d)}o(a,"duplexOnError");function l(d,c){let u=!0,f=new r({...c,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return d.on("message",o(function(g,b){let y=!b&&f._readableState.objectMode?g.toString():g;f.push(y)||d.pause()},"message")),d.once("error",o(function(g){f.destroyed||(u=!1,f.destroy(g))},"error")),d.once("close",o(function(){f.destroyed||f.push(null)},"close")),f._destroy=function(h,g){if(d.readyState===d.CLOSED){g(h),process.nextTick(i,f);return}let b=!1;d.once("error",o(function(w){b=!0,g(w)},"error")),d.once("close",o(function(){b||g(h),process.nextTick(i,f)},"close")),u&&d.terminate()},f._final=function(h){if(d.readyState===d.CONNECTING){d.once("open",o(function(){f._final(h)},"open"));return}d._socket!==null&&(d._socket._writableState.finished?(h(),f._readableState.endEmitted&&f.destroy()):(d._socket.once("finish",o(function(){h()},"finish")),d.close()))},f._read=function(){d.isPaused&&d.resume()},f._write=function(h,g,b){if(d.readyState===d.CONNECTING){d.once("open",o(function(){f._write(h,g,b)},"open"));return}d.send(h,b)},f.on("end",s),f.on("error",a),f}o(l,"createWebSocketStream2"),e.exports=l}}),Ux=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/subprotocol.js"(t,e){"use strict";var{tokenChars:n}=qs();function r(i){let s=new Set,a=-1,l=-1,d=0;for(d;d<i.length;d++){let u=i.charCodeAt(d);if(l===-1&&n[u]===1)a===-1&&(a=d);else if(d!==0&&(u===32||u===9))l===-1&&a!==-1&&(l=d);else if(u===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let f=i.slice(a,l);if(s.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);s.add(f),a=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`)}if(a===-1||l!==-1)throw new SyntaxError("Unexpected end of input");let c=i.slice(a,d);if(s.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return s.add(c),s}o(r,"parse"),e.exports={parse:r}}}),YL=Pt({"../node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket-server.js"(t,e){"use strict";var n=Ye("events"),r=Ye("http"),{Duplex:i}=Ye("stream"),{createHash:s}=Ye("crypto"),a=mm(),l=Ms(),d=Ux(),c=hm(),{CLOSE_TIMEOUT:u,GUID:f,kWebSocket:h}=Qr(),g=/^[+/0-9A-Za-z]{22}==$/,b=0,y=1,w=2,S=class extends n{static{o(this,"WebSocketServer2")}constructor(v,P){if(super(),v={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:c,...v},v.port==null&&!v.server&&!v.noServer||v.port!=null&&(v.server||v.noServer)||v.server&&v.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(v.port!=null?(this._server=r.createServer((E,M)=>{let q=r.STATUS_CODES[426];M.writeHead(426,{"Content-Length":q.length,"Content-Type":"text/plain"}),M.end(q)}),this._server.listen(v.port,v.host,v.backlog,P)):v.server&&(this._server=v.server),this._server){let E=this.emit.bind(this,"connection");this._removeListeners=A(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:o((M,q,te)=>{this.handleUpgrade(M,q,te,E)},"upgrade")})}v.perMessageDeflate===!0&&(v.perMessageDeflate={}),v.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=v,this._state=b}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(v){if(this._state===w){v&&this.once("close",()=>{v(new Error("The server is not running"))}),process.nextTick(T,this);return}if(v&&this.once("close",v),this._state!==y)if(this._state=y,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(T,this):process.nextTick(T,this);else{let P=this._server;this._removeListeners(),this._removeListeners=this._server=null,P.close(()=>{T(this)})}}shouldHandle(v){if(this.options.path){let P=v.url.indexOf("?");if((P!==-1?v.url.slice(0,P):v.url)!==this.options.path)return!1}return!0}handleUpgrade(v,P,E,M){P.on("error",N);let q=v.headers["sec-websocket-key"],te=v.headers.upgrade,B=+v.headers["sec-websocket-version"];if(v.method!=="GET"){x(this,v,P,405,"Invalid HTTP method");return}if(te===void 0||te.toLowerCase()!=="websocket"){x(this,v,P,400,"Invalid Upgrade header");return}if(q===void 0||!g.test(q)){x(this,v,P,400,"Missing or invalid Sec-WebSocket-Key header");return}if(B!==13&&B!==8){x(this,v,P,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(v)){F(P,400);return}let H=v.headers["sec-websocket-protocol"],$=new Set;if(H!==void 0)try{$=d.parse(H)}catch{x(this,v,P,400,"Invalid Sec-WebSocket-Protocol header");return}let _=v.headers["sec-websocket-extensions"],j={};if(this.options.perMessageDeflate&&_!==void 0){let C=new l({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let ne=a.parse(_);ne[l.extensionName]&&(C.accept(ne[l.extensionName]),j[l.extensionName]=C)}catch{x(this,v,P,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:v.headers[`${B===8?"sec-websocket-origin":"origin"}`],secure:!!(v.socket.authorized||v.socket.encrypted),req:v};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(ne,le,de,$e)=>{if(!ne)return F(P,le||401,de,$e);this.completeUpgrade(j,q,$,v,P,E,M)});return}if(!this.options.verifyClient(C))return F(P,401)}this.completeUpgrade(j,q,$,v,P,E,M)}completeUpgrade(v,P,E,M,q,te,B){if(!q.readable||!q.writable)return q.destroy();if(q[h])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>b)return F(q,503);let $=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(P+f).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(E.size){let j=this.options.handleProtocols?this.options.handleProtocols(E,M):E.values().next().value;j&&($.push(`Sec-WebSocket-Protocol: ${j}`),_._protocol=j)}if(v[l.extensionName]){let j=v[l.extensionName].params,C=a.format({[l.extensionName]:[j]});$.push(`Sec-WebSocket-Extensions: ${C}`),_._extensions=v}this.emit("headers",$,M),q.write($.concat(`\r
|
|
115
|
+
`).join(`\r
|
|
116
|
+
`)),q.removeListener("error",N),_.setSocket(q,te,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(_),_.on("close",()=>{this.clients.delete(_),this._shouldEmitClose&&!this.clients.size&&process.nextTick(T,this)})),B(_,M)}};e.exports=S;function A(v,P){for(let E of Object.keys(P))v.on(E,P[E]);return o(function(){for(let M of Object.keys(P))v.removeListener(M,P[M])},"removeListeners")}o(A,"addListeners");function T(v){v._state=w,v.emit("close")}o(T,"emitClose");function N(){this.destroy()}o(N,"socketOnError");function F(v,P,E,M){E=E||r.STATUS_CODES[P],M={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(E),...M},v.once("finish",v.destroy),v.end(`HTTP/1.1 ${P} ${r.STATUS_CODES[P]}\r
|
|
117
|
+
`+Object.keys(M).map(q=>`${q}: ${M[q]}`).join(`\r
|
|
118
|
+
`)+`\r
|
|
119
|
+
\r
|
|
120
|
+
`+E)}o(F,"abortHandshake");function x(v,P,E,M,q,te){if(v.listenerCount("wsClientError")){let B=new Error(q);Error.captureStackTrace(B,x),v.emit("wsClientError",B,E,P)}else F(E,M,q,te)}o(x,"abortHandshakeOrEmitwsClientError")}}),Q7=Hr(QL(),1),Y7=Hr(mm(),1),J7=Hr(Ms(),1),Z7=Hr(Vx(),1),X7=Hr(Kx(),1),eee=Hr(Ux(),1),JL=Hr(hm(),1),tee=Hr(YL(),1),ZL=JL.default,XL=ZL;Mx(XL);var eM=Object.defineProperty,tM=o((t,e,n)=>e in t?eM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,"__defNormalProp"),er=o((t,e,n)=>tM(t,typeof e!="symbol"?e+"":e,n),"__publicField");var Ec=560,Bs;var Vs=class{static{o(this,"ConvexHttpClient")}constructor(e,n){if(er(this,"address"),er(this,"auth"),er(this,"adminAuth"),er(this,"encodedTsPromise"),er(this,"debug"),er(this,"fetchOptions"),er(this,"fetch"),er(this,"logger"),er(this,"mutationQueue",[]),er(this,"isProcessingQueue",!1),typeof n=="boolean")throw new Error("skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.");(n??{}).skipConvexDeploymentUrlCheck!==!0&&nc(e),this.logger=n?.logger===!1?um({verbose:!1}):n?.logger!==!0&&n?.logger?n.logger:cm({verbose:!1}),this.address=e,this.debug=!0,this.auth=void 0,this.adminAuth=void 0,this.fetch=n?.fetch,n?.auth&&this.setAuth(n.auth)}backendUrl(){return`${this.address}/api`}get url(){return this.address}setAuth(e){this.clearAuth(),this.auth=e}setAdminAuth(e,n){if(this.clearAuth(),n!==void 0){let r=new TextEncoder().encode(JSON.stringify(n)),i=btoa(String.fromCodePoint(...r));this.adminAuth=`${e}:${i}`}else this.adminAuth=e}clearAuth(){this.auth=void 0,this.adminAuth=void 0}setDebug(e){this.debug=e}setFetchOptions(e){this.fetchOptions=e}async consistentQuery(e,...n){let r=An(n[0]),i=this.getTimestamp();return await this.queryInner(e,r,{timestampPromise:i})}async getTimestamp(){return this.encodedTsPromise?this.encodedTsPromise:this.encodedTsPromise=this.getTimestampInner()}async getTimestampInner(){let e=this.fetch||Bs||fetch,n={"Content-Type":"application/json","Convex-Client":`npm-${Xt}`},r=await e(`${this.address}/api/query_ts`,{...this.fetchOptions,method:"POST",headers:n});if(!r.ok)throw new Error(await r.text());let{ts:i}=await r.json();return i}async query(e,...n){let r=An(n[0]);return await this.queryInner(e,r,{})}async queryInner(e,n,r){let i=vr(e),s=[Wt(n)],a={"Content-Type":"application/json","Convex-Client":`npm-${Xt}`};this.adminAuth?a.Authorization=`Convex ${this.adminAuth}`:this.auth&&(a.Authorization=`Bearer ${this.auth}`);let l=this.fetch||Bs||fetch,d=r.timestampPromise?await r.timestampPromise:void 0,c=JSON.stringify({path:i,format:"convex_encoded_json",args:s,...d?{ts:d}:{}}),u=d?`${this.address}/api/query_at_ts`:`${this.address}/api/query`,f=await l(u,{...this.fetchOptions,body:c,method:"POST",headers:a});if(!f.ok&&f.status!==Ec)throw new Error(await f.text());let h=await f.json();if(this.debug)for(let g of h.logLines??[])Oi(this.logger,"info","query",i,g);switch(h.status){case"success":return Ot(h.value);case"error":throw h.errorData!==void 0?Rc(h.errorData,new En(h.errorMessage)):new Error(h.errorMessage);default:throw new Error(`Invalid response: ${JSON.stringify(h)}`)}}async mutationInner(e,n){let r=vr(e),i=JSON.stringify({path:r,format:"convex_encoded_json",args:[Wt(n)]}),s={"Content-Type":"application/json","Convex-Client":`npm-${Xt}`};this.adminAuth?s.Authorization=`Convex ${this.adminAuth}`:this.auth&&(s.Authorization=`Bearer ${this.auth}`);let l=await(this.fetch||Bs||fetch)(`${this.address}/api/mutation`,{...this.fetchOptions,body:i,method:"POST",headers:s});if(!l.ok&&l.status!==Ec)throw new Error(await l.text());let d=await l.json();if(this.debug)for(let c of d.logLines??[])Oi(this.logger,"info","mutation",r,c);switch(d.status){case"success":return Ot(d.value);case"error":throw d.errorData!==void 0?Rc(d.errorData,new En(d.errorMessage)):new Error(d.errorMessage);default:throw new Error(`Invalid response: ${JSON.stringify(d)}`)}}async processMutationQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.mutationQueue.length>0;){let{mutation:e,args:n,resolve:r,reject:i}=this.mutationQueue.shift();try{let s=await this.mutationInner(e,n);r(s)}catch(s){i(s)}}this.isProcessingQueue=!1}}enqueueMutation(e,n){return new Promise((r,i)=>{this.mutationQueue.push({mutation:e,args:n,resolve:r,reject:i}),this.processMutationQueue()})}async mutation(e,...n){let[r,i]=n,s=An(r);return i?.skipQueue?await this.mutationInner(e,s):await this.enqueueMutation(e,s)}async action(e,...n){let r=An(n[0]),i=vr(e),s=JSON.stringify({path:i,format:"convex_encoded_json",args:[Wt(r)]}),a={"Content-Type":"application/json","Convex-Client":`npm-${Xt}`};this.adminAuth?a.Authorization=`Convex ${this.adminAuth}`:this.auth&&(a.Authorization=`Bearer ${this.auth}`);let d=await(this.fetch||Bs||fetch)(`${this.address}/api/action`,{...this.fetchOptions,body:s,method:"POST",headers:a});if(!d.ok&&d.status!==Ec)throw new Error(await d.text());let c=await d.json();if(this.debug)for(let u of c.logLines??[])Oi(this.logger,"info","action",i,u);switch(c.status){case"success":return Ot(c.value);case"error":throw c.errorData!==void 0?Rc(c.errorData,new En(c.errorMessage)):new Error(c.errorMessage);default:throw new Error(`Invalid response: ${JSON.stringify(c)}`)}}async function(e,n,...r){let i=An(r[0]),s=typeof e=="string"?e:vr(e),a=JSON.stringify({componentPath:n,path:s,format:"convex_encoded_json",args:Wt(i)}),l={"Content-Type":"application/json","Convex-Client":`npm-${Xt}`};this.adminAuth?l.Authorization=`Convex ${this.adminAuth}`:this.auth&&(l.Authorization=`Bearer ${this.auth}`);let c=await(this.fetch||Bs||fetch)(`${this.address}/api/function`,{...this.fetchOptions,body:a,method:"POST",headers:l});if(!c.ok&&c.status!==Ec)throw new Error(await c.text());let u=await c.json();if(this.debug)for(let f of u.logLines??[])Oi(this.logger,"info","any",s,f);switch(u.status){case"success":return Ot(u.value);case"error":throw u.errorData!==void 0?Rc(u.errorData,new En(u.errorMessage)):new Error(u.errorMessage);default:throw new Error(`Invalid response: ${JSON.stringify(u)}`)}}};function Rc(t,e){return e.data=Ot(t),e}o(Rc,"forwardErrorData");var nM=900*1e3;async function Gx(t,e){let n=`${t.replace(/\/$/,"")}/cli/token`,r=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(r.status===401){let s=await jx(r);throw new Error(`API token rejected (401) at /cli/token: ${s} \u2014 mint a fresh token in the app under Settings \u2192 API-Token and update your config.`)}if(r.status===403){let s=await jx(r);throw new Error(`API token refused (403) at /cli/token: ${s}`)}if(!r.ok)throw new Error(`/cli/token exchange failed (${r.status} ${r.statusText}).`);let i=await r.json();if(!i.token)throw new Error("/cli/token returned no token.");return{jwt:i.token,expiresAt:i.expiresAt??Date.now()+nM}}o(Gx,"exchangeToken");async function jx(t){let e=await t.json().catch(()=>null);return e===null||typeof e.error!="string"?`no reason in the response (${t.status} ${t.statusText})`:e.error}o(jx,"exchangeRefusalReason");function Wx(t){if(t instanceof En){let n=t.data;return typeof n=="object"&&n!==null&&n.code==="UNAUTHENTICATED"}let e=t instanceof Error?t.message:String(t);return/\b(401|403|unauthenticated|unauthorized)\b/i.test(e)}o(Wx,"isAuthError");import{chmodSync as rM,existsSync as iM,mkdirSync as oM,readFileSync as sM,writeFileSync as aM}from"node:fs";import lM from"node:os";import zx from"node:path";var dM=6e4;function Hx(t){return zx.join(lM.homedir(),".config","agent-tools",`${t}.json`)}o(Hx,"cacheFile");function Qx(t){try{let e=Hx(t);if(!iM(e))return null;let n=JSON.parse(sM(e,"utf8"));return typeof n.jwt!="string"||typeof n.expiresAt!="number"?null:n.expiresAt-dM>Date.now()?n.jwt:null}catch{return null}}o(Qx,"loadJwt");function Yx(t,e,n){let r=Hx(t);oM(zx.dirname(r),{recursive:!0}),aM(r,JSON.stringify({jwt:e,expiresAt:n}),"utf8"),rM(r,384)}o(Yx,"storeJwt");async function Tc(t){let e=new Vs(t.convexUrl,{logger:!1}),n;if(t.auth.kind==="admin")e.setAdminAuth(t.auth.adminKey),n="admin";else{let{siteUrl:s,token:a,cacheKey:l}=t.auth,c=(l===void 0?null:Qx(l))??await Jx(s,a,l);e.setAuth(c),n="token"}async function r(s){try{return await s()}catch(a){if(n!=="token"||t.auth.kind!=="jwt"||!Wx(a))throw a;let l=await Jx(t.auth.siteUrl,t.auth.token,t.auth.cacheKey);return e.setAuth(l),s()}}return o(r,"withRetry"),{tenant:t.tenant,convexUrl:t.convexUrl,query:o((s,...a)=>r(()=>e.query(s,...a)),"query"),mutation:o((s,...a)=>r(()=>e.mutation(s,...a)),"mutation"),action:o((s,...a)=>r(()=>e.action(s,...a)),"action"),async paginate(s,a,l={}){let d=l.pageSize??100,c=[],u=null;for(;;){let f={...a,paginationOpts:{numItems:d,cursor:u}},h=await r(()=>e.query(s,f));if(c.push(...h.page),h.isDone||l.max!==void 0&&c.length>=l.max)break;u=h.continueCursor}return l.max!==void 0?c.slice(0,l.max):c},async upload(s,a,l="application/octet-stream"){let d=await fetch(s,{method:"POST",body:new Blob([new Uint8Array(a)],{type:l})});if(!d.ok)throw new Error(`upload failed (${d.status} ${d.statusText}).`);let c=await d.json();if(!c.storageId)throw new Error("upload returned no storageId.");return c.storageId}}}o(Tc,"makeCaller");async function Jx(t,e,n){let{jwt:r,expiresAt:i}=await Gx(t,e);return n!==void 0&&Yx(n,r,i),r}o(Jx,"mintAndCache");var Ni={name:"plexus",configFile:"plexus.yml",yamlKey:"plexus",envPrefix:"PLEXUS",jwtCachePrefix:"plexus-jwt",defaultEnv:"local"};var Us=Di.resolve(import.meta.dirname,"..","..",".."),uM="admin@plexus.swop.schule",fM="plexus-cli (local dev)",Zx="plx_configcli_local_0001";function Xx(t,e){return gm(t)?cM(t,"utf8").match(new RegExp(`^${e}=(.+)$`,"m"))?.[1]?.trim():void 0}o(Xx,"readEnvValue");function ym(){let t=process.cwd();for(let e=0;e<12;e+=1){for(let r of[t,Di.join(t,"app")])if(gm(Di.join(r,".env.local"))&&gm(Di.join(r,"convex")))return r;let n=Di.dirname(t);if(n===t)break;t=n}return Us}o(ym,"resolveLocalAppRoot");function eA(t){if(t.siteUrl)return t.siteUrl;if(process.env.CONVEX_SITE_URL)return process.env.CONVEX_SITE_URL;throw new Error(`plexus: env "${t.env}" has no site_url (needed for /cli/token). Set it in plexus.yml (site_url) or $CONVEX_SITE_URL.`)}o(eA,"resolveRemoteSiteUrl");function tA(t){if(process.env.CONVEX_SITE_URL)return process.env.CONVEX_SITE_URL;for(let e of[".env.local",".env.development.local"]){let n=Xx(Di.join(t,e),"VITE_CONVEX_SITE_URL");if(n)return n}throw new Error("plexus: could not resolve the local Convex SITE url (for /cli/token). Start local dev with `pnpm dev` (rdu) in this worktree, then retry.")}o(tA,"resolveLocalSiteUrl");function Ks(t){return t.env==="local"?process.env.PLEXUS_CONVEX_URL??Fp({cwd:ym()}):t.convexUrl??Fp({cwd:Us})}o(Ks,"resolveTargetConvexUrl");function nA(t){let e=Sc(Ni,t);return{env:e.env,convexUrl:Ks(e)}}o(nA,"resolveWriteTarget");async function js(t={}){let e=Sc(Ni,t);if(e.env==="local")return pM(e);if(!e.token)throw new Error(`plexus: env "${e.env}" needs an API token. Mint one in the app under Settings \u2192 API-Token and set it in plexus.yml (token) or $PLEXUS_TOKEN.`);let n={kind:"jwt",siteUrl:eA(e),token:e.token,cacheKey:`${Ni.jwtCachePrefix}-${e.env}`};return Tc({convexUrl:Ks(e),auth:n,tenant:e.tenant})}o(js,"resolveCaller");async function pM(t){let e=ym(),n=Ks(t);await dm(n);let r=tA(e);await dm(r);{let i=FS({cwd:e}),s=await Tc({convexUrl:n,auth:{kind:"admin",adminKey:i}}),a=Os("apiTokens:devSeedToken"),l={email:uM,name:fM,plaintext:Zx};await s.mutation(a,l)}return Tc({convexUrl:n,auth:mM(r),tenant:t.tenant})}o(pM,"resolveLocalCaller");function mM(t){return{kind:"jwt",siteUrl:t,token:Zx}}o(mM,"localJwtAuth");function rA(t={}){let e=Sc(Ni,t),n=o(r=>{try{return r()}catch{return"(unavailable \u2014 run `pnpm dev` in this worktree)"}},"safe");if(e.env==="local"){let r=ym();return{env:e.env,source:e.source,convexUrl:n(()=>Ks(e)),siteUrl:n(()=>tA(r)),tenant:e.tenant,authMode:"local-bootstrap",deployment:Xx(Di.join(r,".env.local"),"CONVEX_DEPLOYMENT")?.replace(/^anonymous:/,"")}}return{env:e.env,source:e.source,convexUrl:n(()=>Ks(e)),siteUrl:n(()=>eA(e)),tenant:e.tenant,authMode:"token"}}o(rA,"describeConnection");var bm={"applications discard-test":"write","applications start-test":"write","audit access":"write","branding clear-font":"write","branding clear-logo":"write","branding set-font":"write","branding set-logo":"write","branding set-theme":"write","catalog apply":"write","contract grant add":"write","contract grant add-aggregate":"write","contract grant end":"write","contract grant replace":"write","feedback assign":"write","feedback create":"write","feedback deadline":"write","feedback link":"write","feedback reassign":"write","feedback reply":"write","feedback set-status":"write","feedback sync":"write","feedback tag":"write","feedback tags create":"write","feedback tags delete":"write","feedback tags recolor":"write","feedback tags rename":"write","feedback tags visibility":"write","feedback to-issue":"write","feedback unlink":"write","feedback untag":"write","files put":"write","files remove":"write","files rm":"write","imports trigger":"write","imports trigger-all":"write","jobs cancel":"write","notifications chrome set":"write","notifications letters reset":"write","notifications letters set":"write","notifications retry":"write","notifications self-test":"write","offer apply":"write","offer capacity set":"write","offer create":"write","offer delete":"write","offer hard-delete":"write","offer level add":"write","offer level move":"write","offer level remove":"write","offer level rename":"write","offer level restore":"write","offer restore":"write","offer run add":"write","offer run archive":"write","offer run restore":"write","offer run set":"write","offer set":"write","offer unit create":"write","offer unit delete":"write","offer unit ensure-pedagogy":"write","generator apply":"write","generator archive":"write","generator assign":"write","generator clone":"write","generator combined create":"write","generator combined save":"write","generator create":"write","generator delete-draft":"write","generator restore":"write","generator seal":"write","generator setup apply":"write","generator template upload":"write","generator update":"write","generator source save":"write","generator scenarios approve":"write","signing connection activate":"write","signing connection remove":"write","signing connection reseal":"write","signing connection set":"write","signing connection test":"write","signing reconcile":"write","signing resend":"write","signing start":"write","signing void":"write","stripe allow":"write","stripe refresh":"write","test-actions run":"write","tokens create":"write","tokens revoke":"write","users add":"write","users create":"write","users delete":"write","users grant-all":"write","users provision":"write","users provision-platform-admin":"write","users provision-platform-user":"write","users relink-auth":"write","users remove":"write","users set-group":"write","users set-password":"write","users set-platform-admin":"write","users set-platform-permission":"write","users unset-group":"write","work-items assign":"write","work-items complete":"write","work-items create":"write","workers reap":"write","config apply":"confirm","config prune-offers":"confirm","config set":"confirm","config wipe":"confirm","imports cleanup-orphaned":"confirm","retention apply":"confirm","retention parties apply":"confirm","users groups delete":"confirm","users set-email":"confirm",call:"callKind","accounts email-changes":"read","admission laeufe":"read","applications counts":"read","applications list":"read","applications show":"read","applications store":"read","branding show":"read","catalog export":"read","catalog plan":"read","config export":"read","config targets":"read","feedback admins":"read","feedback comments":"read","feedback links":"read","feedback list":"read","feedback screenshot":"read","feedback tags list":"read","files list":"read","imports status":"read","interessenten list":"read","jobs list":"read","jobs logs":"read","jobs show":"read","migrations status":"read","notifications chrome show":"read","notifications letters list":"read","notifications letters show":"read","notifications list":"read","notifications show":"read","notifications sweeper-status":"read","offer diff":"read","offer export":"read","offer list":"read","offer plan":"read","offer show":"read","offer status":"read","platform tenants":"read","platform users":"read","platform workers":"read","generator combined export":"read","generator combined plan":"read","generator export":"read","generator implementations":"read","generator list":"read","generator runs":"read","generator scaffold":"read","generator setup plan":"read","generator show":"read","generator source export":"read","generator scenarios test":"read","generator template list":"read","generator test":"read","generator usages":"read","retention plan":"read","retention parties plan":"read","signing connection show":"read","signing status":"read","signing list":"read","signing show":"read","stammdaten persons":"read","stammdaten persons purge":"confirm","stripe status":"read",tenants:"read","test-actions list":"read","tokens list":"read",units:"read","users doctor":"read","users groups":"read","users list":"read","users login-trail":"read","users show":"read",whoami:"read","work-items list":"read","work-items show":"read","workers logs":"read","workers reaper-status":"read"},iA={"config targets":"lists the config targets through an action"};function oA(t,e){let n=o(r=>()=>{throw new Error(`plexus: "${e}" is listed as a read in plexus/writeVerbs.ts but called a ${r} \u2014 classify it as write (or name the read in ACTION_READS).`)},"refuse");return new Proxy(t,{get(r,i,s){return i==="mutation"?n("mutation"):i==="action"?n("action"):Reflect.get(r,i,s)}})}o(oA,"readOnlyCaller");var So=class extends Re{static{o(this,"OfflineMutationCommand")}warn(e){for(let n of e)this.context.stderr.write(`warning: [${n.area}] ${n.message}
|
|
121
|
+
`)}},V=class extends Re{static{o(this,"ClientCommand")}env=p.String("--env",{description:"Target environment (local|staging|prod)"});tenant=p.String("--tenant",{description:"Tenant slug (overrides config default)"});allowProd=p.Boolean("--allow-prod",!1,{description:"Required for a writing run against production"});writesNow(e){let n=bm[e];if(n===void 0)throw new Error(`plexus: "${e}" is not classified in plexus/writeVerbs.ts \u2014 add it as read|write|confirm|callKind.`);switch(n){case"read":return!1;case"write":return!0;case"confirm":return this.confirm===!0;case"callKind":{let r=this.effectiveKind;if(r===void 0)throw new Error(`plexus: "${e}" resolved no call kind before connecting.`);return r!=="query"}}}async caller(){let e=this.path.join(" "),n={env:this.env,tenant:this.tenant};if(this.writesNow(e))return Ox(this.env,e),Cx(this.resolvedTarget(),this.prodUrls(),this.allowProd,e),js(n);this.allowProd&&this.context.stderr.write(`note: ${e} reads here \u2014 --allow-prod has no effect.
|
|
122
|
+
`);let r=await js(n);return bm[e]==="read"&&!(e in iA)?oA(r,e):r}resolvedTarget(){return nA({env:this.env,tenant:this.tenant})}prodUrls(){return $x(Ni)}requireTenant(e){if(!e.tenant)throw new Error("plexus: no tenant \u2014 pass --tenant <slug> or set default_tenant in plexus.yml / PLEXUS_TENANT.");return e.tenant}};var sA={required:!0,description:"catalog.json (revenueAccounts, billingItems with their programs, grantTemplates, documentTemplates)"},aA=["step","target","action","detail"],wm=class extends V{static{o(this,"CatalogPlanCommand")}file=p.String("--file",sA);static paths=[["catalog","plan"]];static usage=I.Usage({category:"Contracts",description:"Read-only: what `catalog apply` would write (revenue accounts, articles, price versions, program assignments, packages, tiers, Word templates)."});async execute(){let e=await this.caller(),n=await wp(e,this.requireTenant(e),bp(this.file));return this.print(n.rows,r=>r,aA),0}},km=class extends V{static{o(this,"CatalogApplyCommand")}file=p.String("--file",sA);static paths=[["catalog","apply"]];static usage=I.Usage({category:"Contracts",description:"Bring a catalog file onto the environment by stable key; a Word file is uploaded only when its SHA-256 differs. Idempotent."});async execute(){let e=await this.caller();return this.print(await rS(e,this.requireTenant(e),bp(this.file)),n=>n,aA),0}},vm=class extends V{static{o(this,"CatalogExportCommand")}out=p.String("--out",{required:!0,description:"catalog.json to write (refuses an existing file)"});static paths=[["catalog","export"]];static usage=I.Usage({category:"Contracts",description:"Read-only: write the tenant's catalog (revenue accounts, articles with price, floor and programs, packages, grant templates) as catalog.json \u2014 `catalog plan` on it reports `same` everywhere. Word templates are not exported."});async execute(){if(hM(this.out))throw new Error(`${this.out} gibt es schon \u2014 einen neuen Pfad w\xE4hlen.`);let e=await this.caller(),{file:n,unkeyed:r}=await iS(e,this.requireTenant(e));gM(this.out,`${JSON.stringify(n,null,2)}
|
|
123
|
+
`);let i=Object.entries(r).filter(([,s])=>s>0).map(([s,a])=>`${a} ${s}`);return this.context.stdout.write(`${this.out}: ${n.billingItems.length} Artikel, ${n.grantTemplates.length} Rabattvorlagen`+(i.length===0?`
|
|
124
|
+
`:` \u2014 ohne Schl\xFCssel nicht exportiert: ${i.join(", ")}
|
|
125
|
+
`)),0}},lA=[wm,km,vm];var Sm=["sibling","stipend","promo","needsBased","singleParent"],Ic=class extends V{static{o(this,"GrantSourceCommand")}template=p.String("--template",{description:"Grant template configKey (its terms are copied)"});name=p.String("--name",{description:"One-off grant: display name (German)"});reason=p.String("--reason",{description:`One-off grant: ${Sm.join("|")}`});percent=p.String("--percent",{description:"One-off grant: percent off"});amount=p.String("--amount",{description:"One-off grant: euro off (a line, never a package)"});evidence=p.String("--evidence",{required:!0,description:'Why the family gets it, as a JSON object \u2014 e.g. {"rank":2,"proof":"Bescheid Stadt 03.11."}'});parsedEvidence(){let e;try{e=JSON.parse(this.evidence)}catch{throw new Error("--evidence must be a JSON object.")}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("--evidence must be a JSON object.");return e}source(){if(this.template!==void 0){if(this.name!==void 0||this.percent!==void 0||this.amount!==void 0)throw new Error("Either --template or --name/--reason/--percent|--amount, not both.");return{kind:"template",configKey:this.template}}if(this.name===void 0||this.reason===void 0||this.percent===void 0==(this.amount===void 0))throw new Error("A one-off grant needs --name, --reason and exactly one of --percent / --amount.");if(!Sm.includes(this.reason))throw new Error(`--reason must be one of ${Sm.join("|")}.`);let e=Number(this.percent??this.amount);if(!Number.isFinite(e))throw new Error("--percent/--amount must be a number.");return{kind:"terms",name:this.name,reason:this.reason,grantKind:this.percent!==void 0?"percent":"absolute",value:e}}},xm=class extends Ic{static{o(this,"ContractGrantAddCommand")}static paths=[["contract","grant","add"]];static usage=I.Usage({category:"Contracts",description:"Add a grant to one contract line (--line) from the 1st of a month.",examples:[["City rank 2 from November",`$0 contract grant add --env staging --tenant test --line <lineId> --template city-sibling-2 --from 2026-11-01 --evidence '{"rank":2}'`]]});line=p.String("--line",{description:"contract_lines id"});from=p.String("--from",{required:!0,description:"First day (YYYY-MM-01)"});to=p.String("--to",{description:"Last day (last day of a month)"});async execute(){if(!this.line)throw new Error("Name --line. Aggregate grants target explicit contract lines through contractGrants:addAggregate.");let e={kind:"line",contractLineId:this.line},n=await this.caller();return this.print(await n.mutation(R.contractGrants.add,{client:this.requireTenant(n),target:e,source:this.source(),eligibilityEvidence:this.parsedEvidence(),activeFrom:this.from,...this.to===void 0?{}:{activeTo:this.to}})),0}},Am=class extends V{static{o(this,"ContractGrantEndCommand")}static paths=[["contract","grant","end"]];static usage=I.Usage({category:"Contracts",description:"End an applied grant on the last day of a month."});grant=p.String({required:!0,name:"appliedGrantId"});to=p.String("--to",{required:!0,description:"Last day (last day of a month)"});async execute(){let e=await this.caller();return this.print(await e.mutation(R.contractGrants.end,{client:this.requireTenant(e),appliedGrantId:this.grant,activeTo:this.to})),0}},Em=class extends Ic{static{o(this,"ContractGrantReplaceCommand")}static paths=[["contract","grant","replace"]];static usage=I.Usage({category:"Contracts",description:"Replace an applied grant from the 1st of a month: the old one ends the day before, the new one takes its place."});grant=p.String({required:!0,name:"appliedGrantId"});from=p.String("--from",{required:!0,description:"First day of the new grant (YYYY-MM-01)"});async execute(){let e=await this.caller();return this.print(await e.mutation(R.contractGrants.replace,{client:this.requireTenant(e),appliedGrantId:this.grant,from:this.from,source:this.source(),eligibilityEvidence:this.parsedEvidence()})),0}},Rm=class extends V{static{o(this,"ContractGrantAddAggregateCommand")}static paths=[["contract","grant","add-aggregate"]];static usage=I.Usage({category:"Contracts",description:"Apply a contract grant template to its eligible contract lines, with an optional agreed euro amount and floor."});contract=p.String("--contract",{required:!0,description:"contracts id"});template=p.String("--template",{required:!0,description:"Aggregate grant template configKey"});amount=p.String("--amount",{description:"Agreed euro deduction for the stated period"});floor=p.String("--floor",{description:"Agreed euro floor for the stated period"});period=p.String("--period",{description:"month|year|once|unit; changing period requires an explicit floor"});from=p.String("--from",{required:!0,description:"First day (YYYY-MM-01)"});to=p.String("--to",{description:"Last day (last day of a month)"});evidence=p.String("--evidence",{required:!0,description:"Finance decision and supporting evidence as a JSON object"});async execute(){let e=o(l=>{if(!/^(0|[1-9]\d*)(\.\d{1,2})?$/.test(l))throw new Error("Amounts must be nonnegative euros with at most two decimal places.");let d=Math.round(Number(l)*100);if(!Number.isSafeInteger(d))throw new Error("Amount is too large.");return d},"money");if(this.period!==void 0&&!cp.includes(this.period))throw new Error("--period must be month|year|once|unit.");let n;try{n=JSON.parse(this.evidence)}catch{throw new Error("--evidence must be a JSON object.")}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("--evidence must be a JSON object.");let r=await this.caller(),i=this.requireTenant(r),a=(await r.query(R.contractConfig.model,{client:i})).grantTemplates.find(l=>l.configKey===this.template);if(!a||a.scope!=="aggregate")throw new Error("Name an existing aggregate grant template.");return this.print(await r.mutation(R.contractGrants.addAggregate,{client:i,contractId:this.contract,templateId:a.id,...this.amount===void 0?{}:{requestedAmountMinor:e(this.amount)},...this.floor===void 0?{}:{agreedFloorTotal:e(this.floor)},...this.period===void 0?{}:{pricePeriod:this.period},activeFrom:this.from,...this.to===void 0?{}:{activeTo:this.to},eligibilityEvidence:n})),0}},dA=[xm,Rm,Am,Em];import{mkdirSync as _A,readFileSync as CM,writeFileSync as OA}from"node:fs";import Jr from"node:path";var cA=["stammdaten","bewerbungsmanagement","finanzen_vertraege","administration","aufgaben","notifications"],yM={stammdaten:{_self:["access","read","write","configure"],parties:["read","write","delete"],customFields:["read","configure","editAutomatic"]},bewerbungsmanagement:{_self:["access"],branding:["manage"],applications:["read","manage","submitOwn","viewExternal","assignResponsibility"],forms:["configure"],workflow:["approval"],testActions:["run"]},finanzen_vertraege:{_self:["access"],contracts:["manage"],payments:["connect"]},administration:{_self:["access"],roles:["manage"],permissions:["manage"],users:["manage"],masterData:["manage"],feedback:["viewAll"],organizationStructure:["manage"],apiTokens:["manage"],config:["read","manage"]},aufgaben:{_self:["access"],items:["read","write","assign","decide"]},notifications:{_self:["access"],mail:["configure"],deliveries:["read"]}},Tm=Object.entries(yM).flatMap(([t,e])=>Object.entries(e).flatMap(([n,r])=>r.map(i=>`${t}.${n}.${i}`)));var bM={tenants:["accessAll"],workers:["monitor"],notifications:["monitor"],users:["manage"],feedback:["read","manage","tags","assign"],config:["read","manage"],schema:["read"],audit:["read","readActor"],apiTokens:["manage"]};var Im=Object.entries(bM).flatMap(([t,e])=>e.map(n=>`_platform.${t}.${n}`)),wM=Im,kM=["_platform.feedback.assign","_platform.audit.readActor","_platform.apiTokens.manage"],kte=wM.filter(t=>!kM.includes(t));var uA=["bewerbungsmanagement.applications.submitOwn"];var $m="applicant";var fA="interessent";var vM={Abholberechtigt:"Authorized pickup",Abholzeitfenster:"Pickup window","Abmeldung vom Religionsunterricht seit":"Withdrawn from religion class since","5a, 7b, Vorkurs":"5a, 7b, prep course",Adresszusatz:"Address supplement",Aktiv:"Active","Allergien & Besonderheiten":"Allergies & special notes","Alle Einrichtungen":"All units",Anrede:"Salutation",Ansprechpartner:"Contact person",Arbeitsverh\u00E4ltnis:"Employment",Arbeitszeit:"Working time",Art:"Type","Art der rechtlichen Vertretung":"Legal representation type",Aufenthalt:"Residence","Aufnahme am":"Admission date",Auskunftsberechtigt:"Authorized for information","Ausweis erforderlich":"ID required",Bewerbung:"Application",Bereiche:"Areas","Bedarf an sonderp\xE4dagogischer Unterst\xFCtzung":"Special educational support needed",befreit:"Exempt","Betreuung bis":"Care until",Beziehungen:"Relationships",Daten:"Data",Deutsch:"German",Deutschland:"Germany",divers:"Diverse",Divers:"Diverse","Dokumente & Nachweise":"Documents & evidence",Eintrittsdatum:"Start date","Einwilligung f\xFCr Videoaufnahmen":"Video recording consent",Einschulung:"School enrollment","Endg\xFCltige Zuweisung liegt vor":"Final assignment confirmed","elterliche Sorge":"Parental custody","Entlassung am":"Release date",Entscheidungsbefugt:"Authorized to decide",Erg\u00E4nzungspflegschaft:"Supplementary guardianship",Erstsprache:"First language",Evangelisch:"Protestant",evangelisch:"Protestant",Ehemalig:"Alumni","E-Mail":"Email","Empfehlung Bedarf sonderpad. Unterst.":"Recommendation: special educational support","Empfehlung F\xF6rderort":"Recommendation: support location","Empfehlung F\xF6rderschwerpunkt":"Recommendation: support focus","Extern/Bewerber":"External/applicant",F\u00F6rderbedarf:"Support needs",F\u00F6rderschule:"Special school",F\u00F6rderstunden:"Support hours","F\xF6rderstunden/Woche":"Support hours/week","F\xF6rderschwerpunkte (Mehrfachauswahl)":"Support focuses (multiple selection)",Fotoerlaubnis:"Photo consent",F\u00F6rderung:"Support",Frau:"Ms.",Ganztag:"Full-day care","Ganztag aktiv":"Full-day active",Gasth\u00F6rer:"Guest student",Geburtsdatum:"Date of birth",Geburtsland:"Country of birth",Geburtsort:"Place of birth","Gemeinsames Lernen":"Inclusive learning",Geschlecht:"Gender",Gesundheit:"Health","Gesundheit & Nachweise":"Health & evidence","Getrennt lebend":"Living separately","Gutachten an Schulamt/BezReg":"Report sent to school authority/district government","Gutachten erstellt von":"Report prepared by","Gutachten-Beauftragung bis":"Report commissioned until",Herr:"Mr.",Hinweis:"Note",Hinweise:"Notes","in Kl\xE4rung":"Clarifying","In Pr\xFCfung":"Under review","in Pr\xFCfung":"Under review",Islamisch:"Islamic",islamisch:"Islamic",Ja:"Yes","Ja \u2014 \xA74 Abs. 1 S. 1":"Yes \u2014 Section 4 (1) sentence 1",Katholisch:"Catholic",katholisch:"Catholic",Keine:"None","Keine Auskunft an Dritte":"No information to third parties","keine Teilnahme":"No participation","kein Bedarf":"No need",Klasse:"Class","Klassenlehrer/in":"Class teacher",Konfession:"Denomination",Kontaktarten:"Contact types",Korrespondenz:"Correspondence","K\xF6rperliche und motorische Entwicklung":"Physical and motor development",Land:"Country",Lernen:"Learning","LRS / Rechenschw\xE4che":"Dyslexia / dyscalculia",m\u00E4nnlich:"male",Masernimpfnachweis:"Measles vaccination proof","Mit Einschr\xE4nkungen":"With restrictions","Mitarbeiter/in":"Staff member",Mutter:"Mother",Nachname:"Last name","Name der Organisation":"Organization name",Nein:"No","Nicht gruppiert":"Ungrouped",Notfallkontakt:"Emergency contact","Nr.":"No.","Ohne Angabe":"Not specified","ohne Angabe":"not specified","Operative Kontaktart":"Operational contact type","Operativer Kontakt":"Operational contact",Organisation:"Organization",Organisationen:"Organizations",Ort:"City",Ortsteil:"District",Person:"Person",PLZ:"Postal code",Polen:"Poland",Position:"Position",Prim\u00E4rkontakt:"Primary contact",Priorit\u00E4t:"Priority","Probeweise Zuweisung liegt vor bis":"Trial assignment confirmed until",Regelschule:"Mainstream school","Rechtliche Vertretung":"Legal representation",Religionsunterricht:"Religion class",Rolle:"Role",Schule:"School",Schulinformationen:"School information","Sch\xFCler/in":"Student","Sch\xFClerinteressent/in":"Prospective student",Sch\u00FClernummer:"Student number",Sch\u00FClerstatus:"Student status","Sch\xFClerverzeichnis Nr.":"Student directory no.",Schwimmunterricht:"Swimming class","Scope der rechtlichen Vertretung":"Legal representation scope",Sprache:"Language",Staatsangeh\u00F6rigkeit:"Nationality",Stammdaten:"Master data",Standort:"Location","Standort/Schule":"Location/school",Status:"Status",Stra\u00DFe:"Street",Syrien:"Syria",Telefon:"Phone",Teilnahme:"Participation",T\u00FCrkei:"Turkey",T\u00FCrkisch:"Turkish",Ukraine:"Ukraine",Umfang:"Extent","Umfang der rechtlichen Vertretung":"Legal representation extent",Verwaltung:"Administration",Verwandtschaft:"Kinship",Verwandtschaftsart:"Kinship type",Verwandtschaftsgrad:"Degree of kinship",Vater:"Father",Vietnamesisch:"Vietnamese",Vollst\u00E4ndig:"Complete",voll:"full",Vorname:"First name","Vormundschaft Amt":"Public guardianship","Vormundschaft Einzelner":"Individual guardianship","Vormundschaft Verein":"Association guardianship",weiblich:"female",Wohnadresse:"Residential address",Wohnort:"City of residence","Aktives Programm \xFCber Einschreibung, Lerngruppe und Programm.":"Active program across enrollment, learning group, and program.",Arabisch:"Arabic","Auskunft gesperrt":"Information blocked","Campus Lindenfeld":"Campus Lindenfeld","Campus Sonnhalde":"Campus Sonnhalde","Emotionale Entwicklung":"Emotional development","Emotionale und soziale Entwicklung":"Emotional and social development","Foto eingeschr\xE4nkt":"Photo restricted","Geistige Entwicklung":"Cognitive development",Gro\u00DFeltern:"Grandparents","Grundschule Sonnenberg":"Sonnenberg Elementary School","Interessent/in":"Prospect","Keine Einwilligung f\xFCr Videoaufnahmen":"No video recording consent","Keine Fotos":"No photos","K\xF6rper/Motorik":"Physical/motor",Lehrer:"Teacher",Mitarbeitende:"Staff","Moers, Krefeld":"Moers, Krefeld","Namen der verkn\xFCpften rechtlichen Vertretungen.":"Names of the linked legal representatives.",Pflegeperson:"Caregiver",Programm:"Program","Rechtliche Vertretungen":"Legal representatives",Schulleitung:"School leadership",Schulverwaltung:"School administration",Stiefeltern:"Stepparents",Verm\u00F6gen:"Assets",teilweise:"partial"};function _m(t,e=vM[t]){return(e===void 0||e.trim()==="")&&W(`label("${t}"): no English text \u2014 pass it, or add it to ENGLISH_LABELS`),{de:t.trim(),en:e.trim()}}o(_m,"label");var pA={mode:"deviating",defaultCountryCode:"de"};function mA(t,e){return{slug:t,name:e,enabledModules:[...cA],permissions:[...Tm],defaultApplicantGroupKey:$m,defaultInteressentRoleKey:fA,defaultStartInProxy:!1,mailLevel:"all",magicLinkLogin:!0,nationalityFlag:{...pA}}}o(mA,"fullTenant");function hA(t){return{legalEntities:t.legalEntities,units:t.units,permissionGroups:[{key:"tenant_admin",label:_m("Mandantenadmin","Tenant Admin"),permissions:[...Tm],sortOrder:10,grantAllCustomFields:!0},{key:$m,label:_m("Extern/Bewerber","External/applicant"),permissions:[...uA],sortOrder:1e3}],users:t.users}}o(hA,"foundationWithTenantAdmin");function gA(t){let{slug:e,name:n}=t,r=`${e}_operator`,i=`${e}_schule`,s=hA({legalEntities:[{key:r,name:`${n} (Tr\xE4ger)`,type:"school_operator"}],units:[{key:i,name:{de:n,en:n},legalEntityKey:r,pedagogyUnit:!0,kind:"school"}],users:[]});return{key:e,tenant:mA(e,n),foundation:s,displayGroups:[{key:"stammdaten",label:{de:"Allgemein",en:"General"},color:"#475569",icon:"UserRound",sortOrder:10,defaultExpanded:!0}],lists:[],roles:[],fields:[],roleFields:[],deferredColumns:[],files:[],ignoredColumns:[]}}o(gA,"buildSkeletonTenantConfig");import{appendFileSync as yA,existsSync as xM,readFileSync as AM}from"node:fs";function Om(t,e,n="password"){e.length!==0&&(Cm(t,n)||yA(t,`email,${n}
|
|
126
|
+
`),yA(t,e.map(r=>`${r.email},${r.password}
|
|
127
|
+
`).join("")))}o(Om,"writeCredentialRows");function Cm(t,e){let n=`email,${e}`,r=xM(t)?AM(t,"utf8"):"";if(r.trim().length===0)return!1;let i=r.split(`
|
|
128
|
+
`,1)[0];if(i!==n)throw new Error(`plexus: ${t} is not an "${n}" file (header: "${i}") \u2014 pick another --output.`);return!0}o(Cm,"assertCredentialFile");function Yr(t,e,n,r="password"){Om(t,[{email:e,password:n}],r)}o(Yr,"writeCredentialRow");import{createHash as RM}from"node:crypto";import{mkdirSync as TM,readFileSync as IM,writeFileSync as $M}from"node:fs";import Sr from"node:path";var EM=/^[a-z0-9][a-z0-9-]*$/;function $c(t){return EM.test(t)}o($c,"isFileKey");function bA(t){return t.trim()===""?"is empty":t==="."||t===".."?"is not a file name":/[/\\]/.test(t)?"must not contain a path separator":/[\u0000-\u001f]/.test(t)?"must not contain control characters":null}o(bA,"fileNameDefect");var vA={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword",".odt":"application/vnd.oasis.opendocument.text",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png"},_c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff2":"font/woff2"};function Pm(t){return RM("sha256").update(t).digest("hex")}o(Pm,"sha256Hex");function Nm(t,e=vA){let n=Sr.resolve(t),r;try{r=IM(n)}catch{throw new Error(`File not found: ${t}`)}let i=e[Sr.extname(n).toLowerCase()];if(i===void 0)throw new Error(`${t}: unsupported file type \u2014 allowed: ${Object.keys(e).join(", ")}.`);return{bytes:r,filename:Sr.basename(n),mimeType:i,sha256:Pm(r),sizeBytes:r.length}}o(Nm,"readLocalFile");var _M={tenantFile:R.tenantFiles.platformGenerateUploadUrl,brandingAsset:R.branding.platformGenerateBrandingAssetUploadUrl};async function Dm(t,e,n,r,i){let{uploadUrl:s,uploadTicket:a}=await t.mutation(_M[i],{client:e}),l=await t.upload(s,n,r);return await t.mutation(R.uploads.registerUpload,{uploadTicket:a,storageId:l}),l}o(Dm,"uploadStaged");async function SA(t,e,n,r){return await Dm(t,e,n,r,"tenantFile")}o(SA,"uploadTenantFile");function Fm(t){let e=[...t].filter(([,n])=>"fileName"in n||"size"in n).map(([n])=>n);if(e.length!==0)throw new Error(`[cli/serverPredatesFileRef] ${e.join(", ")}: the target deployment still answers fileName / size \u2014 it runs a release from before file references. Use a plexus-cli built from that release, or wait for the next release.`)}o(Fm,"requireFileRefNames");async function Gs(t,e){let n=await t.query(R.tenantFiles.platformList,{client:e});return Fm(n.map(r=>[`files["${r.key}"]`,r])),n}o(Gs,"listLibrary");function wA(t,e,n,r,i){let s=Nm(Sr.resolve(t,e),i);if(s.mimeType!==n)throw new Error(`${r}: ${e} is ${s.mimeType}, the entry declares ${n}.`);return s}o(wA,"readSnapshotEntry");function xA(t,e){let n=new Map,r=(t.files??[]).map(l=>{if(l.path===void 0)return l;let{path:d,...c}=l,u=wA(e,d,c.mimeType,`files["${c.key}"]`,vA);return n.set(c.key,u),{...c,sha256:u.sha256,sizeBytes:u.sizeBytes}}),i=new Map,s=t.tenant.brandingAssets,a;if(s!==void 0){a={};for(let[l,d]of Object.entries(s)){if(d.path===void 0){a[l]=d;continue}let{path:c,...u}=d,f=`tenant.brandingAssets.${l}`,h=wA(e,c,u.mimeType,f,_c);i.set(l,h),a[l]={...u,sha256:h.sha256,sizeBytes:h.sizeBytes}}}return{config:{...t,tenant:{...t.tenant,...a!==void 0?{brandingAssets:a}:{}},files:r},bytes:n,brandingBytes:i}}o(xA,"resolveSnapshotFiles");async function AA(t,e,n,r,i){let s={},a={contents:s,changed:[],unavailable:[]};for(let l of t){if(e.get(l.key)===l.sha256)continue;a.changed.push(l.key);let d=await n(l.key);if(d===void 0){a.unavailable.push(l.key);continue}if(Pm(d)!==l.sha256)throw new Error(`${l.at}: the supplied bytes do not match sha256 ${l.sha256}.`);i||(s[l.key]=await r(d,l.mimeType))}return a}o(AA,"stageChanged");async function EA(t,e,n,r,i){let s=new Map(Object.entries(await t.query(R.tenantFiles.platformFileHashes,{client:e})??{})),a=new Map(n.map(l=>[l.key,l]));return await AA(n.map(l=>({key:l.key,sha256:l.sha256,mimeType:l.mimeType,at:`files["${l.key}"]`})),s,l=>r(a.get(l)),(l,d)=>Dm(t,e,l,d,"tenantFile"),i)}o(EA,"stageFileContents");async function Oc(t,e){let n=await t.query(R.branding.platformBrandingAssets,{client:e});return Fm(Object.entries(n??{}).map(([r,i])=>[`tenant.brandingAssets.${r}`,i])),n}o(Oc,"listBrandingAssets");async function RA(t,e,n,r,i){let s=new Map(Object.entries(await Oc(t,e)??{}).map(([a,l])=>[a,l.sha256]));return await AA(Object.entries(n??{}).map(([a,l])=>({key:a,sha256:l.sha256,mimeType:l.mimeType,at:`tenant.brandingAssets.${a}`})),s,r,(a,l)=>Dm(t,e,a,l,"brandingAsset"),i)}o(RA,"stageBrandingAssets");async function TA(t,e,n,r){if(t===null)throw new Error(`${n}: its stored object is gone \u2014 ${r}`);let i=await fetch(t);if(!i.ok)throw new Error(`download of ${n} failed (${i.status}).`);let s=new Uint8Array(await i.arrayBuffer());if(Pm(s)!==e)throw new Error(`download of ${n} does not match its sha256 ${e}.`);return s}o(TA,"downloadVerified");async function Lm(t){return await TA(t.url,t.sha256,`"${t.key}"`,"replace it with `files put` first.")}o(Lm,"downloadLibraryFile");async function Mm(t,e){return await TA(e.url,e.sha256,`branding/${t}`,"upload it again with `branding set-logo` / `branding set-font` first.")}o(Mm,"downloadBrandingAsset");function OM(t,e){let n=Object.keys(_c).find(r=>_c[r]===e);if(n===void 0)throw new Error(`export: branding/${t} is ${e}, which a snapshot cannot name (${Object.keys(_c).join(", ")}).`);return Sr.join("branding",`${t}${n}`)}o(OM,"brandingAssetPath");function kA(t,e,n){let r=Sr.join(t,e);TM(Sr.dirname(r),{recursive:!0}),$M(r,n)}o(kA,"writeBeside");async function IA(t,e,n,r){Fm([...n.files.map(c=>[`files["${c.key}"]`,c]),...Object.entries(n.tenant.brandingAssets??{}).map(([c,u])=>[`tenant.brandingAssets.${c}`,u])]);let i=new Map((await Gs(t,e)).map(c=>[c.key,c])),s=Sr.dirname(r),a=[];for(let c of n.files){let u=i.get(c.key);if(u===void 0)throw new Error(`export: "${c.key}" vanished from the library between two reads \u2014 rerun.`);let f=bA(c.filename);if(f!==null||!$c(c.key))throw new Error(`export: "${c.key}" / "${c.filename}" is not a safe path (${f??"bad key"}).`);let h=Sr.join("files",c.key,c.filename);kA(s,h,await Lm(u)),a.push({...c,path:h})}let l=n.tenant.brandingAssets,d;if(l!==void 0){let c=await Oc(t,e)??{};d={};for(let[u,f]of Object.entries(l)){let h=c[u];if(h===void 0||h.sha256!==f.sha256)throw new Error(`export: branding/${u} changed between two reads \u2014 rerun.`);let g=OM(u,f.mimeType);kA(s,g,await Mm(u,h)),d[u]={...f,path:g}}}return{...n,tenant:{...n.tenant,...d!==void 0?{brandingAssets:d}:{}},files:a}}o(IA,"writeSnapshotFiles");var Rn={create:"+",update:"~",destroy:"-"};function CA(t,e=!1){let n=[{kind:`${Rn.create} create`,target:"(all)",detail:String(t.counts.created)},{kind:`${Rn.update} update`,target:"(all)",detail:String(t.counts.updated)}];if(t.deletions!==void 0&&n.push({kind:`${Rn.destroy} delete`,target:"(all)",detail:String(t.counts.deleted??t.deletions.length)}),n.push({kind:"\xB7 unchanged",target:"(all)",detail:String(t.counts.unchanged)}),t.updates!==void 0)for(let r of t.updates)n.push({kind:`${Rn.update} update`,target:r.target,detail:r.key});else t.counts.updated>0&&n.push({kind:`${Rn.update} update`,target:"(unnamed)",detail:"this deployment predates per-row updates \u2014 deploy it to see which rows"});for(let r of t.deletions??[])n.push({kind:`${Rn.destroy} delete`,target:r.target,detail:r.key});for(let r of t.slugChanges??[])n.push({kind:`${Rn.update} slug`,target:`units/${r.unitKey}`,detail:`${r.from} \u2192 ${r.to} (old URL /e/units/${r.from} no longer reaches this unit)`});for(let r of t.orphans)n.push({kind:`${Rn.destroy} orphan`,target:`${r.target}/${r.table}`,detail:`${r.key} (${t.destroyed!==void 0?"destroyed":"would destroy"})`});for(let r of t.accounts?.minted??[])n.push({kind:`${Rn.create} account`,target:r.email,detail:e?"password: (not echoed)":`password: ${r.password}`});for(let r of t.accounts?.pending??[])n.push({kind:"! no account",target:r,detail:"would get a generated password on --confirm"});return n}o(CA,"planRows");function $A(t,e,n,r,i){return(t?.changed??[]).map(s=>({kind:`${Rn.update} ${e}`,target:`${n}/${s}`,detail:t?.unavailable.includes(s)?`content differs \u2014 NO bytes in this source; a commit needs them bundled or fails ${r}`:i?"content differs \u2014 would upload":"content uploaded"}))}o($A,"contentRows");async function PM(t,e){if(t==="blueprint")return{source:"blueprint"};if(t.startsWith("env:")){let n=t.slice(4);if(!n)throw new Error("config: --from env:<srcEnv> needs a source environment.");let r=await js({env:n,tenant:e});return{source:"inline",config:await r.query(R.config.api.exportTenant,{tenant:e}),bytesFor:o(async s=>{let a=(await Gs(r,e)).find(l=>l.key===s.key);return a===void 0?void 0:await Lm(a)},"bytesFor"),brandingBytesFor:o(async s=>{let a=(await Oc(r,e))?.[s];return a===void 0?void 0:await Mm(s,a)},"brandingBytesFor")}}if(t.startsWith("snapshot:")){let n=Jr.resolve(t.slice(9)),r=JSON.parse(CM(n,"utf8")),{config:i,bytes:s,brandingBytes:a}=xA(r,Jr.dirname(n));return{source:"inline",config:i,bytesFor:o(async l=>s.get(l.key)?.bytes,"bytesFor"),brandingBytesFor:o(async l=>a.get(l)?.bytes,"brandingBytesFor")}}throw new Error(`config: unknown --from "${t}". Use blueprint | env:<srcEnv> | snapshot:<path>. / Unbekannte Quelle "${t}".`)}o(PM,"resolveSource");function NM(t){try{return JSON.parse(t)}catch{return t}}o(NM,"parseValue");var qm=class extends Re{static{o(this,"ConfigShowCommand")}static paths=[["config","show"]];static usage=I.Usage({category:"Config",description:"Show the resolved connection config (no network) / Verbindung anzeigen"});env=p.String("--env",{description:"Target environment (local|staging|prod)"});tenant=p.String("--tenant",{description:"Tenant slug"});async execute(){let e=rA({env:this.env,tenant:this.tenant});return this.print({env:e.env,source:e.source,convexUrl:e.convexUrl,siteUrl:e.siteUrl,deployment:e.deployment??"(n/a)",tenant:e.tenant??"(none)",authMode:e.authMode},n=>[{key:"env",value:n.env},{key:"source",value:n.source},{key:"convexUrl",value:n.convexUrl},{key:"siteUrl",value:n.siteUrl},{key:"deployment",value:n.deployment},{key:"tenant",value:n.tenant},{key:"authMode",value:n.authMode}],["key","value"]),0}},Bm=class extends Re{static{o(this,"ConfigInitCommand")}static paths=[["config","init"]];static usage=I.Usage({category:"Config",description:"Scaffold a minimal, valid tenant config JSON on disk / Mandanten-Konfiguration anlegen"});tenant=p.String("--tenant",{required:!0,description:"New tenant slug"});name=p.String("--name",{required:!0,description:"Tenant display name"});out=p.String("--out",{description:"Output file (default: config/.dev/<tenant>/config.json)"});async execute(){let e=gA({slug:this.tenant,name:this.name}),n=this.out?Jr.resolve(this.out):Jr.join(Us,"config",".dev",this.tenant,"config.json");return _A(Jr.dirname(n),{recursive:!0}),OA(n,`${JSON.stringify(e,null,2)}
|
|
129
|
+
`,"utf8"),this.print({created:this.tenant,out:n},r=>[{key:"created",value:r.created},{key:"out",value:r.out},{key:"next",value:`plexus config apply --tenant ${r.created} --from snapshot:${r.out} (dry-run; add --confirm to commit)`}]),0}},Vm=class extends V{static{o(this,"ConfigTargetsCommand")}static paths=[["config","targets"]];static usage=I.Usage({category:"Config",description:"List the config/data target registry + live row counts / Ziel-Register"});async execute(){let e=await this.caller(),n=e.tenant,r=await e.action(R.config.api.targets,{...n!==void 0?{tenant:n}:{}});return this.print(r,i=>i.targets.map(s=>({id:s.id,kind:s.kind,scope:s.scope,rows:String(s.totalRows),label:`${s.label.de} / ${s.label.en}`,dependsOn:(s.dependsOn??[]).join(",")||"-"})),["id","kind","scope","rows","label","dependsOn"]),0}},Km=class extends V{static{o(this,"ConfigApplyCommand")}static paths=[["config","apply"]];static usage=I.Usage({category:"Config",description:"Reconcile a tenant/platform config (dry-run unless --confirm) / Konfiguration anwenden",details:"A committing apply on a tenant whose config carries `foundation.users` MINTS a login password for every one of them that has no account yet, and prints it once \u2014 so this command can return secrets. Use --output <file> (and --quiet) to keep them out of a shared terminal."});scope=p.String("--scope",{description:"Apply scope: tenant (default) | platform"});from=p.String("--from","blueprint",{description:"Source: blueprint | env:<srcEnv> | snapshot:<path>"});confirm=p.Boolean("--confirm",!1,{description:"Commit (else dry-run)"});allowDestructive=p.Boolean("--allow-destructive",!1,{description:"Permit destroying orphaned rows"});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let e=await this.caller();if(this.scope==="platform"){let h=await e.action(R.config.api.applyPlatform,{confirm:this.confirm});return this.print(h,g=>[{kind:`${Rn.create} create`,target:"(platform)",detail:String(g.counts.created)},{kind:`${Rn.update} update`,target:"(platform)",detail:String(g.counts.updated)},{kind:"\xB7 unchanged",target:"(platform)",detail:String(g.counts.unchanged)},{kind:"mode",target:g.dryRun?"DRY-RUN":"COMMITTED",detail:g.note}]),0}let n=this.requireTenant(e),{source:r,config:i,bytesFor:s,brandingBytesFor:a}=await PM(this.from,n),l=i!==void 0&&s!==void 0?await EA(e,n,i.files??[],s,!this.confirm):void 0,d=i!==void 0&&a!==void 0?await RA(e,n,i.tenant.brandingAssets,a,!this.confirm):void 0,c=await e.action(R.config.api.apply,{tenant:n,...r!==void 0?{source:r}:{},...i!==void 0?{config:i}:{},...l!==void 0&&Object.keys(l.contents).length>0?{fileContents:l.contents}:{},...d!==void 0&&Object.keys(d.contents).length>0?{brandingContents:d.contents}:{},confirm:this.confirm,allowDestructive:this.allowDestructive}),u=c.accounts?.minted??[],f=this.output!==void 0&&u.length>0;return this.output!==void 0&&Om(this.output,u),this.print(c,h=>[...CA(h,this.quiet),...$A(l,"file","files","[file/contentMissing]",h.dryRun),...$A(d,"brand","branding","[branding/contentMissing]",h.dryRun),{kind:"mode",target:h.dryRun?"DRY-RUN":"COMMITTED",detail:`from=${this.from}${f?` \u2192 ${this.output}`:""}`}]),0}},Um=class extends V{static{o(this,"ConfigExportCommand")}static paths=[["config","export"]];static usage=I.Usage({category:"Config",description:"Snapshot a tenant's live config to config/.dev/<tenant>/config.json / Konfiguration exportieren"});out=p.String("--out",{description:"Output file path (overrides default)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.config.api.exportTenant,{tenant:n}),i=this.out?Jr.resolve(this.out):Jr.join(Us,"config",".dev",n,"config.json");_A(Jr.dirname(i),{recursive:!0});let s=await IA(e,n,r,i);return OA(i,`${JSON.stringify(s,null,2)}
|
|
130
|
+
`,"utf8"),this.print({exported:n,out:i},a=>[{key:"exported",value:a.exported},{key:"out",value:a.out}]),0}},jm=class extends V{static{o(this,"ConfigSetCommand")}static paths=[["config","set"]];static usage=I.Usage({category:"Config",description:"Patch ONE field of ONE config row (dry-run unless --confirm) / Einzelnes Feld setzen"});target=p.String("--target",{required:!0,description:"setField target (tenant|display-groups|fields|lists|roles|units|\u2026)"});key=p.String("--key",{required:!0,description:"Row key"});field=p.String("--field",{required:!0,description:"Dot-path field (e.g. label.de)"});value=p.String("--value",{required:!0,description:"New value (JSON or string)"});confirm=p.Boolean("--confirm",!1,{description:"Commit (else dry-run)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.action(R.config.api.setField,{tenant:n,target:this.target,key:this.key,field:this.field,value:NM(this.value),confirm:this.confirm});return this.print(r,i=>[{kind:"edit",target:`${this.target}/${this.key}`,detail:`${this.field}=${this.value}`},...CA(i),{kind:"mode",target:i.dryRun?"DRY-RUN":"COMMITTED",detail:""}]),0}},Gm=class extends V{static{o(this,"ConfigWipeCommand")}static paths=[["config","wipe"]];static usage=I.Usage({category:"Config",description:"Clear a target's tables (--confirm + --allow-destructive) / Ziel leeren",details:"Only `--target all` deletes the tenant identity row (full teardown). `--target foundation` clears foundation child tables (+ dependent DATA with --cascade) but leaves the `tenants` row and sibling config targets. Without --confirm it is a dry run: it prints, per table, the rows the wipe would clear (and any block it would hit) and deletes nothing."});target=p.String("--target",{required:!0,description:"Target id (or 'all' for full tenant teardown)"});cascade=p.Boolean("--cascade",!1,{description:"Also clear dependent targets"});confirm=p.Boolean("--confirm",!1,{description:"Required: actually wipe"});allowDestructive=p.Boolean("--allow-destructive",!1,{description:"Required for destructive wipes"});async execute(){let e=await this.caller(),n=this.requireTenant(e);if(this.target!=="all"&&this.context.stderr.write(`note: '--target ${this.target}' leaves the tenant identity row and sibling config targets intact; use '--target all' for a full tenant teardown.
|
|
131
|
+
`),!this.confirm){let i=await e.action(R.config.api.wipePreview,{tenant:n,target:this.target,cascade:this.cascade});return this.print({dryRun:!0,tenant:n,...i},s=>[...s.perTable.map(a=>({table:`${a.target}.${a.table}`,deleted:`would clear ${a.rows}`})),...this.target==="all"?[{table:"tenants",deleted:`would delete the tenant "${n}" itself`}]:[],...s.blocked!==void 0?[{table:"BLOCKED",deleted:s.blocked}]:[],{table:"(dry run)",deleted:"add --confirm (+ --allow-destructive for heavy targets) to wipe"}]),0}let r=await e.action(R.config.api.wipe,{tenant:n,target:this.target,cascade:this.cascade,confirm:this.confirm,allowDestructive:this.allowDestructive});return this.print(r,i=>i.blocked?[{table:"BLOCKED",deleted:i.blocked}]:[{table:"(targets)",deleted:i.clearedTargets.join(",")||"-"},...i.perTable.map(s=>({table:s.table,deleted:String(s.deleted)}))]),0}},Wm=class extends V{static{o(this,"ConfigPruneOffersCommand")}static paths=[["config","prune-offers"]];static usage=I.Usage({category:"Config",description:"Drop offer generations that are only edit history / Tote Angebots-Generationen entfernen",details:"A generation is prunable only when ALL of these hold: its status is `archived`, NO application is pinned to it, and it is not the last generation of its key. A `wip` draft and a published head are never touched, however few applications sit on them. Dry-run unless --confirm."});confirm=p.Boolean("--confirm",!1,{description:"Required: actually delete the listed generations"});async execute(){let e=await this.caller(),n=this.requireTenant(e),i=await e.action(R.config.api.pruneOffers,{tenant:n,commit:this.confirm});return this.print(i,()=>[...i.prunable.map(s=>({verdict:i.committed?"deleted":"would delete",offer:`${s.key} r${s.revision}`,label:s.label})),...i.keptWithApplications.map(s=>({verdict:"kept (applications)",offer:`${s.key} r${s.revision}`,label:s.label})),{verdict:i.committed?`deleted ${i.deleted}`:`dry run (${i.prunable.length})`,offer:`${i.scanned} generations scanned`,label:""}]),0}},PA=[qm,Bm,Vm,Km,Um,jm,Gm,Wm];import{existsSync as qA}from"node:fs";import Hm from"node:path";import{existsSync as DM,readFileSync as FM}from"node:fs";function Pc(t){if(!DM(t))throw new Error(`function-spec snapshot not found at ${t}. Regenerate with the package's \`spec\` script.`);return JSON.parse(FM(t,"utf8"))}o(Pc,"loadSpec");function Tn(t){return t.replace(/\.(js|ts):/,":")}o(Tn,"normalize");function zm(t){return t.functionType.toLowerCase()}o(zm,"kindOf");function LM(t){let e=t.args;return e?.value?Object.keys(e.value):[]}o(LM,"argNames");function NA(t,e={}){return t.functions.map(n=>({function:Tn(n.identifier),kind:zm(n),args:LM(n)})).filter(n=>e.kind?n.kind===e.kind.toLowerCase():!0).filter(n=>e.grep?n.function.toLowerCase().includes(e.grep.toLowerCase()):!0).sort((n,r)=>n.function.localeCompare(r.function))}o(NA,"listFunctions");function DA(t,e){let n=Tn(e),r=t.functions.find(a=>Tn(a.identifier)===n);if(r)return r;let i=t.functions.map(a=>Tn(a.identifier)).filter(a=>a.includes(n.split(":")[0]??n)||a.includes(n.split(":")[1]??"")).slice(0,8),s=i.length?` Did you mean: ${i.join(", ")}?`:"";throw new Error(`Unknown function "${e}".${s}`)}o(DA,"describeFunction");function FA(t,e,n){if(n!==void 0){if(n!=="query"&&n!=="mutation"&&n!=="action")throw new Error(`Unknown --kind '${n}' (expected query|mutation|action).`);let a=t.functions.find(d=>Tn(d.identifier)===Tn(e)),l=a===void 0?void 0:zm(a);if(l!==void 0&&l!==n)throw new Error(`"${e}" is a ${l} in the offline spec \u2014 --kind ${n} contradicts it.`);return n}let r=Tn(e),i=t.functions.find(a=>Tn(a.identifier)===r),s=i===void 0?void 0:zm(i);if(s!=="query"&&s!=="mutation"&&s!=="action")throw new Error(`"${e}" is not in the offline spec (a newer function, or a typo \u2014 see \`plexus-cli functions --grep\`); pass --kind query|mutation|action.`);if(s!=="query")throw new Error(`"${e}" is a ${s} \u2014 it writes; pass --kind ${s} (and check --env).`);return s}o(FA,"callKindFor");function Fi(t){let e=t;if(!e||typeof e.type!="string")return"unknown";switch(e.type){case"array":return`${Fi(e.value)}[]`;case"union":return(Array.isArray(e.value)?e.value.map(Fi):[]).join(" | ")||"union";case"literal":return JSON.stringify(e.value);case"id":return`id<${e.tableName??"?"}>`;case"object":return"object";default:return e.type}}o(Fi,"typeStr");function Cc(t,e){let n=e;switch(n?.type){case"string":case"id":return typeof t=="string";case"number":case"float64":return typeof t=="number";case"int64":case"bigint":return typeof t=="number"&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;case"literal":return t===n.value;case"union":return Array.isArray(n.value)&&n.value.some(r=>Cc(t,r));case"array":return Array.isArray(t)&&t.every(r=>Cc(r,n.value));case"object":{if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=n.value??{},i=t;return Object.keys(i).every(s=>s in r)&&Object.entries(r).every(([s,a])=>i[s]===void 0?a.optional===!0:Cc(i[s],a.fieldType))}case"record":return typeof t=="object"&&t!==null&&!Array.isArray(t);default:return!0}}o(Cc,"fits");function LA(t,e,n={}){let r=t.args?.value??{},i={...e},s=[];for(let[a,l]of Object.entries(r)){if(i[a]===void 0){l.optional!==!0&&s.push(`missing ${a} (${Fi(l.fieldType)})`);continue}let d=l.fieldType?.type;(d==="string"||d==="id")&&typeof i[a]!="string"&&n[a]!==void 0&&(i[a]=n[a]),Cc(i[a],l.fieldType)||s.push(`${a}: expected ${Fi(l.fieldType)}, got ${JSON.stringify(i[a])}`)}for(let a of Object.keys(i))a in r||s.push(`unknown ${a} (takes: ${Object.keys(r).join(", ")||"nothing"})`);return{args:i,problems:s}}o(LA,"checkCallArgs");var Nc=[Hm.resolve(import.meta.dirname,"spec.snapshot.json"),Hm.resolve(import.meta.dirname,"..","..","spec.snapshot.json")].find(t=>qA(t))??Hm.resolve(import.meta.dirname,"..","..","spec.snapshot.json");function MA(t){let e=t;return!e||e.type!=="object"||!e.value?null:Object.entries(e.value).map(([n,r])=>{let i=r;return{name:n,type:Fi(i.fieldType),optional:!!i.optional}})}o(MA,"objectFields");function MM(t){let e=t.functionType.toLowerCase();return e==="query"||e==="mutation"||e==="action"?e:t.functionType}o(MM,"kindLabel");var Qm=class extends Re{static{o(this,"FunctionsCommand")}static paths=[["functions"]];static usage=I.Usage({category:"Introspection",description:"List callable public functions (offline; for `call`)."});kind=p.String("--kind",{description:"Filter by RPC kind (query|mutation|action)."});grep=p.String("--grep",{description:"Case-insensitive substring filter on the path."});async execute(){let e=Pc(Nc),n=NA(e,{kind:this.kind,grep:this.grep});return this.print(n,r=>r.map(i=>({function:i.function,kind:i.kind,args:i.args.join(",")})),["function","kind","args"]),0}},Ym=class extends Re{static{o(this,"DescribeCommand")}static paths=[["describe"]];static usage=I.Usage({category:"Introspection",description:"Show one public function's args + return type (offline)."});fn=p.String({required:!0});async execute(){let e=Pc(Nc),n=DA(e,this.fn);if(this.json)return this.print(n),0;let r=Tn(n.identifier??this.fn),i=this.context.stdout;i.write(`${r} [${MM(n)}]
|
|
132
|
+
|
|
133
|
+
`);let s=MA(n.args)??[];i.write(`args:${s.length?"":" (none)"}
|
|
134
|
+
`);for(let l of s)i.write(` ${l.name}: ${l.type}${l.optional?" (optional)":""}
|
|
135
|
+
`);let a=MA(n.returns);if(a!==null){i.write(`
|
|
136
|
+
returns: object
|
|
137
|
+
`);for(let l of a)i.write(` ${l.name}: ${l.type}${l.optional?" (optional)":""}
|
|
138
|
+
`)}else i.write(`
|
|
139
|
+
returns: ${Fi(n.returns)}
|
|
140
|
+
`);return 0}};function qM(t){let e={},n={};for(let r of t){let i=r.indexOf("=");if(i<0)throw new Error(`Expected key=value, got '${r}'.`);let s=r.slice(0,i),a=r.slice(i+1);n[s]=a;try{e[s]=JSON.parse(a)}catch{e[s]=a}}return{values:e,raw:n}}o(qM,"parseKv");var Jm=class extends V{static{o(this,"CallCommand")}static paths=[["call"]];static usage=I.Usage({category:"Introspection",description:"Call any public Convex function by name (escape hatch)."});fn=p.String({required:!0});kind=p.String("--kind",{description:"Function kind: query|mutation|action. Without it only a query runs (checked against the offline spec); a write needs --kind."});args=p.Rest();effectiveKind=void 0;async execute(){let e=this.kind===void 0||qA(Nc)?Pc(Nc):{functions:[]},n=FA(e,this.fn,this.kind),{values:r,raw:i}=qM(this.args),s=e.functions.find(u=>Tn(u.identifier)===Tn(this.fn)),a=r;if(s===void 0)this.context.stderr.write(`note: "${this.fn}" is not in the offline spec \u2014 arguments are not checked before the call
|
|
141
|
+
`);else{let u=LA(s,r,i);if(u.problems.length>0)throw new Error(`call ${this.fn}: ${u.problems.join("; ")} \u2014 see \`plexus-cli describe ${this.fn}\``);a=u.args}this.effectiveKind=n;let l=await this.caller(),d=Os(this.fn),c;if(n==="query"){let u=d;c=await l.query(u,a)}else if(n==="mutation"){let u=d;c=await l.mutation(u,a)}else{let u=d;c=await l.action(u,a)}return this.context.stdout.write(`${JSON.stringify(c,(u,f)=>typeof f=="bigint"?f.toString():f,2)}
|
|
142
|
+
`),0}},BA=[Qm,Ym,Jm];async function Dc(t){let e;try{e=await t.query(R.platformAdmin.listAllTenants,{})}catch{e=(await t.query(R.permissions.currentUserAccess,{})).users.map(r=>r.tenant).filter(r=>r!==null)}return e.filter(n=>n.slug.length>0)}o(Dc,"accessibleTenants");function Je(t,e,n,r="--label"){if(t===void 0||t.trim()==="")throw new Error(`${n}: ${r} cannot be empty \u2014 the German text is required`);if(e===void 0||e.trim()==="")throw new Error(`${n}: ${r} needs ${r}-en too \u2014 the English text is required; every config text carries German AND English ([i18n/missingTranslation])`);return{de:t,en:e}}o(Je,"newLocalizedText");function BM(t){return t===void 0||t.en===void 0||t.en.trim()===""||t.en===t.de}o(BM,"isUntranslated");var VM={de:"the German text",en:"the English text"};function Zm(t,e,n,r=VM){let{en:i}=e;if(e.de==="")throw new Error(`${n}: ${r.de} cannot be empty`);if(i==="")throw new Error(`${n}: ${r.en} cannot be empty \u2014 every config text needs both languages`);let s=e.de===t?.de?void 0:e.de;if(i===void 0){if(s===void 0)return;if(!BM(t))throw new Error(`${n}: carries an English text ("${t.en}") for the old German ("${t.de}") \u2014 pass ${r.en} for the new German too`);return{de:s,en:""}}let a=s??t?.de;if(a===void 0||a==="")throw new Error(`${n}: an English text needs the German one first \u2014 pass ${r.de}`);if(!(a===t?.de&&i===t?.en))return{de:a,en:i}}o(Zm,"editedLocalizedText");function at(t,e,n,r){let{de:i,en:s}=n;if(i===""&&n.clearable){if(s!==void 0&&s!=="")throw new Error(`${r}: an English text needs the German one`);delete t[e];return}let a=Zm(t[e],{de:i,en:s},r);a!==void 0&&(t[e]=a)}o(at,"setLocalizedText");function VA(t){let e=t.indexOf(":");if(e<0)return{id:t.trim(),de:"",en:void 0};let n=t.slice(0,e).trim(),r=t.slice(e+1),i=r.indexOf(":");return i<0?{id:n,de:r.trim(),en:void 0}:{id:n,de:r.slice(0,i).trim(),en:r.slice(i+1).trim()}}o(VA,"splitIdDeEn");function tn(t,e,n){let r=t.de?.trim()??"",i=t.en?.trim()??"";if(r==="")throw new Error(`${e}: ${n.de} is required`);if(i==="")throw new Error(`${e}: ${n.en} is required \u2014 every name a reader sees needs German and English`);return{de:r,en:i}}o(tn,"newName");function tr(t,e,n,r){let i=Zm(t,{de:e.de?.trim(),en:e.en?.trim()},n,r);if(i!==void 0&&i.en.trim()==="")throw new Error(`${n}: there is no English name for "${i.de}" \u2014 pass ${r.en}; every name a reader sees needs German and English`);return i}o(tr,"editedName");function Fe(t){return t.en===""||t.en===t.de?t.de:`${t.de} / ${t.en}`}o(Fe,"showName");var Xm=class extends V{static{o(this,"WhoamiCommand")}static paths=[["whoami"]];static usage=I.Usage({category:"Identity",description:"Show the authenticated identity + permissions."});async execute(){let e=await this.caller(),n=await e.query(R.permissions.currentUserAccess,e.tenant?{client:e.tenant}:{});return this.print(n),0}},eh=class extends V{static{o(this,"TenantsCommand")}static paths=[["tenants"]];static usage=I.Usage({category:"Identity",description:"List tenants you can access."});async execute(){let e=await this.caller(),n=await Dc(e);return this.print(n,r=>r.map(i=>({slug:i.slug,name:i.name,id:i.id})),["slug","name","id"]),0}},th=class extends V{static{o(this,"UnitsCommand")}static paths=[["units"]];static usage=I.Usage({category:"Identity",description:"List the active tenant's organisation tree."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.organization.getOrgTree,{client:n});return this.print(r,i=>i.units.map(s=>({id:s.id,key:s.configKey??"\u2014",name:Fe(s.name),kind:s.kind,code:s.code,pedagogic:s.isPedagogic?"\u2713":""}))),0}},KA=[Xm,eh,th];var nh=class extends V{static{o(this,"TokensListCommand")}static paths=[["tokens","list"]];static usage=I.Usage({category:"Identity",description:"List your API tokens."});async execute(){let n=await(await this.caller()).query(R.apiTokens.listMine,{});return this.print(n,r=>r.map(i=>({id:i.id,name:i.name,prefix:i.prefix,active:i.active?"\u2713":"\u2717"})),["id","name","prefix","active"]),0}},rh=class extends V{static{o(this,"TokensCreateCommand")}static paths=[["tokens","create"]];static usage=I.Usage({category:"Identity",description:"Create a new API token (shown once) \u2014 for yourself, or with --for for a tenant administrator to hand over (platform right `_platform.users.manage`).",examples:[["Your own token","plexus-cli --env staging tokens create laptop"],["A token for a tenant administrator, kept out of the terminal","plexus-cli --env staging tokens create cli --for admin@schule.example --output /tmp/token.csv --quiet"]]});name=p.String({required:!0,name:"name"});forEmail=p.String("--for",{description:"Create the token FOR this account instead of yourself (platform right `_platform.users.manage`). The account must hold `administration.apiTokens.manage` in at least one tenant."});output=p.String("--output",{description:"Append the `email,token` row to this CSV file (created with a header). Needs --for."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the token to stdout (use with --output)."});async execute(){let e={name:this.name,forEmail:this.forEmail,output:this.output,quiet:this.quiet};KM(e);let n=await UM(await this.caller(),e);return this.json?(this.print(this.quiet?{id:n.id,prefix:n.prefix}:n),0):(this.context.stdout.write(jM(e,n)),0)}};function KM(t){if(t.forEmail===void 0&&(t.output!==void 0||t.quiet))throw new Error("plexus: --output/--quiet go with --for \u2014 your own token is printed for you to copy.");if(t.quiet&&t.output===void 0)throw new Error("plexus: --quiet without --output would lose the token \u2014 it is shown only once.");t.output!==void 0&&Cm(t.output,"token")}o(KM,"assertCreateFlags");async function UM(t,e){let n=e.forEmail===void 0?await t.mutation(R.apiTokens.createToken,{name:e.name}):await t.mutation(R.apiTokens.createTokenFor,{email:e.forEmail,name:e.name});return e.forEmail!==void 0&&e.output!==void 0&&Yr(e.output,e.forEmail.trim().toLowerCase(),n.plaintextKey,"token"),n}o(UM,"createTokenRun");function jM(t,e){let n=t.forEmail===void 0?"":` for ${t.forEmail}`,r=t.output!==void 0?` \u2192 ${t.output}`:"";return t.quiet?`Token created${n}${r} (prefix: ${e.prefix}).
|
|
143
|
+
`:`Token created${n}${r}. Copy it now \u2014 it is shown only once:
|
|
144
|
+
|
|
145
|
+
${e.plaintextKey}
|
|
146
|
+
|
|
147
|
+
prefix: ${e.prefix}
|
|
148
|
+
`}o(jM,"createdTokenText");var ih=class extends V{static{o(this,"TokensRevokeCommand")}static paths=[["tokens","revoke"]];static usage=I.Usage({category:"Identity",description:"Revoke an API token."});tokenId=p.String({required:!0,name:"tokenId"});async execute(){return await(await this.caller()).mutation(R.apiTokens.revokeToken,{tokenId:this.tokenId}),this.print({revoked:this.tokenId},n=>[{revoked:n.revoked}]),0}},UA=[nh,rh,ih];var GM=/^(\d+)([mhd])$/,WM={m:6e4,h:36e5,d:864e5};function Fc(t,e=Date.now()){let n=t.trim(),r=GM.exec(n);if(r!==null)return e-Number(r[1])*WM[r[2]];let i=/^\d{4}-\d{2}-\d{2}/.test(n)?Date.parse(n):Number.NaN;if(Number.isNaN(i))throw new Error(`--since "${t}": expected 90m, 24h, 2d or an ISO date like 2026-10-13T11:40Z`);return i}o(Fc,"parseSince");var xo="tenant_admin",Lc=Im;async function jA(t){return t.query(R.platformAdmin.listAllPlatformUsers,{})}o(jA,"listUsers");async function Ws(t,e){return t.query(R.permissions.model,{client:e})}o(Ws,"loadModel");async function Rh(t,e){let n=e.trim().toLowerCase(),i=(await jA(t)).find(s=>s.email.toLowerCase()===n);if(i===void 0)throw new Error(`No user with email "${e}".`);return i}o(Rh,"findUser");async function zs(t,e){return(await Rh(t,e)).userId}o(zs,"resolveUserId");async function zM(t,e,n){let i=(await Rh(t,e)).tenants.find(s=>s.slug===n);if(i===void 0)throw new Error(`${e} has no active access to tenant "${n}".`);return i.userTenantAccessId}o(zM,"resolveAccessId");function GA(t,e){let n=t.permissionGroups.find(r=>r.key===e);if(n===void 0){let r=t.permissionGroups.map(i=>i.key).join(", ");throw new Error(`No permission group "${e}". Available: ${r||"(none)"}.`)}return n.id}o(GA,"resolveGroupId");function HM(t,e,n){let r=t.memberships.find(i=>i.userId===e&&i.permissionGroupId===n);if(r===void 0)throw new Error("User is not a member of that group in this tenant.");return r.id}o(HM,"resolveMembershipId");function QM(t,e){let n=new Map(t.permissionGroups.map(i=>[i.id,i])),r=[];for(let i of t.memberships){if(i.userId!==e)continue;let s=n.get(i.permissionGroupId);s!==void 0&&r.push({key:s.key,label:s.label,active:i.active})}return r}o(QM,"userGroups");var Et=class extends V{static{o(this,"UsersBaseCommand")}report(e,n){this.json?this.print(e):this.context.stdout.write(`${n}
|
|
149
|
+
`)}},oh=class extends V{static{o(this,"UsersListCommand")}static paths=[["users","list"]];static usage=I.Usage({category:"Users",description:"List all platform users."});async execute(){let e=await this.caller(),n=await jA(e);return this.print(n,r=>r.map(i=>({email:i.email,name:i.name,platform:i.platformPermissions.length>0?"\u2713":"",tenants:i.tenants.map(s=>s.slug).join(",")})),["email","name","platform","tenants"]),0}},sh=class extends V{static{o(this,"UsersShowCommand")}static paths=[["users","show"]];static usage=I.Usage({category:"Users",description:"Show one user's tenants, groups + platform status."});email=p.String({required:!0});async execute(){let e=await this.caller(),n=await Rh(e,this.email),r=await Promise.all(n.tenants.map(async a=>{let l=await Ws(e,a.slug);return{slug:a.slug,name:a.name,groups:QM(l,n.userId)}})),i={userId:n.userId,email:n.email,name:n.name,platformPermissions:n.platformPermissions,tenants:r};if(this.json)return this.print(i),0;let s=[`${i.email} (${i.name})`];i.platformPermissions.length>0&&s.push(` platform: ${i.platformPermissions.join(", ")}`),i.tenants.length===0&&s.push(" tenants: (none)");for(let a of i.tenants){let l=a.groups.map(c=>c.active?c.key:`${c.key} (inactive)`),d=l.length>0?l.join(", "):"(no groups)";a.groups.length>0&&!a.groups.some(c=>c.active)&&(d+=" <-- NO ACTIVE GROUP"),s.push(` ${a.slug} (${a.name}): ${d}`)}return this.context.stdout.write(`${s.join(`
|
|
150
|
+
`)}
|
|
151
|
+
`),0}},ah=class extends V{static{o(this,"UsersGroupsCommand")}static paths=[["users","groups"]];static usage=I.Usage({category:"Users",description:"List a tenant's permission groups."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await Ws(e,n);return this.print(r.permissionGroups,i=>i.map(s=>({key:s.key,label:s.label})),["key","label"]),0}},lh=class extends Et{static{o(this,"UsersGroupsDeleteCommand")}static paths=[["users","groups","delete"]];static usage=I.Usage({category:"Users",description:"Delete a tenant permission group (hard; refuses while in use).",details:`
|
|
152
|
+
Removes the group outright \u2014 there is no soft delete. A hidden-but-present
|
|
153
|
+
group would need an \`active\` flag every reader honours, and one that
|
|
154
|
+
forgot it is exactly what left a removed user haunting the permissions
|
|
155
|
+
admin and breaking \`config export\`.
|
|
156
|
+
|
|
157
|
+
The backend refuses while anything still points at the group: members,
|
|
158
|
+
application team bindings, or a workflow graph naming its key. It also
|
|
159
|
+
refuses for \`tenant_admin\` and for the tenant's default applicant group.
|
|
160
|
+
The group's own custom-field grants are removed with it.
|
|
161
|
+
`});key=p.String({required:!0});confirm=p.Boolean("--confirm",!1,{description:"Required: actually delete (else dry-run)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await Ws(e,n),i=r.permissionGroups.find(l=>l.key===this.key);if(i===void 0)throw new Error(`Tenant "${n}" has no permission group "${this.key}". Known: ${r.permissionGroups.map(l=>l.key).join(", ")}`);let s=r.memberships.filter(l=>l.permissionGroupId===i.id).length;if(!this.confirm)return this.report({tenant:n,key:i.key,members:s,deleted:!1},`DRY RUN \u2014 would delete "${i.key}" from "${n}" (${s} member(s)). Re-run with --confirm.`),0;let a=await e.mutation(R.permissions.deletePermissionGroup,{client:n,key:i.key});return this.report({tenant:n,key:i.key,...a,deleted:!0},`Deleted permission group "${i.key}" from "${n}" (${a.deletedCustomFieldGrants} field grant(s) removed).`),0}},dh=class extends Et{static{o(this,"UsersAddCommand")}static paths=[["users","add"]];static usage=I.Usage({category:"Users",description:"Add a user to a tenant (creates the user if absent)."});email=p.String({required:!0});group=p.String("--group",xo,{description:`Permission group key (default: ${xo}).`});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.platformAdmin.grantTenantAccess,{email:this.email,tenantSlug:n,permissionGroupKey:this.group});return this.report(r,`Added ${this.email} to "${n}" (group: ${this.group}).`),0}},ch=class extends Et{static{o(this,"UsersGrantAllCommand")}static paths=[["users","grant-all"]];static usage=I.Usage({category:"Users",description:"Grant every current user of one tenant access to another (e.g. let all tenants dogfood the Test Tenant). One-time + idempotent; new users are not auto-enrolled."});from=p.String("--from",{required:!0,description:"Source tenant slug."});to=p.String("--to",{required:!0,description:"Target tenant slug."});group=p.String("--group",xo,{description:`Permission group key in the target (default: ${xo}).`});async execute(){let n=await(await this.caller()).mutation(R.platformAdmin.grantAllTenantUsersAccess,{fromTenantSlug:this.from,toTenantSlug:this.to,permissionGroupKey:this.group});if(this.json)return this.print(n),0;let r=[`Granted ${n.granted}/${n.totalUsers} users of "${n.fromTenantSlug}" access to "${n.toTenantSlug}" (group: ${this.group}).`];for(let i of n.skipped)r.push(` skipped ${i.email}: ${i.reason}`);return this.context.stdout.write(`${r.join(`
|
|
162
|
+
`)}
|
|
163
|
+
`),0}},uh=class extends Et{static{o(this,"UsersRemoveCommand")}static paths=[["users","remove"]];static usage=I.Usage({category:"Users",description:"Revoke a user's access to a tenant."});email=p.String({required:!0});replaceWith=p.String("--replace-with",{description:"configKey of the staff member who takes over their active applications \u2014 required while they are responsible for any. A rule naming them refuses regardless: change it first (workflow editor: \u201EPerson ersetzen\u201C, then publish)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await zM(e,this.email,n);return await e.mutation(R.platformAdmin.revokeTenantAccess,{userTenantAccessId:r,...this.replaceWith!==void 0?{replaceWith:this.replaceWith}:{}}),this.report({revoked:r},`Revoked ${this.email}'s access to "${n}".`),0}},fh=class extends Et{static{o(this,"UsersSetGroupCommand")}static paths=[["users","set-group"]];static usage=I.Usage({category:"Users",description:"Add a user to a permission group in a tenant."});email=p.String({required:!0});group=p.String("--group",{required:!0,description:"Permission group key."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await zs(e,this.email),i=await Ws(e,n),s=GA(i,this.group),a=await e.mutation(R.permissions.createMembership,{client:n,userId:r,permissionGroupId:s});return this.report(a,`Added ${this.email} to group "${this.group}" in "${n}".`),0}},ph=class extends Et{static{o(this,"UsersUnsetGroupCommand")}static paths=[["users","unset-group"]];static usage=I.Usage({category:"Users",description:"Remove a user from a permission group in a tenant."});email=p.String({required:!0});group=p.String("--group",{required:!0,description:"Permission group key."});replaceWith=p.String("--replace-with",{description:"configKey of the staff member who takes over their active applications \u2014 required while they are responsible for any. A rule naming them refuses regardless: change it first (workflow editor: \u201EPerson ersetzen\u201C, then publish)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await zs(e,this.email),i=await Ws(e,n),s=GA(i,this.group),a=HM(i,r,s);return await e.mutation(R.permissions.deleteMembership,{client:n,id:a,...this.replaceWith!==void 0?{replaceWith:this.replaceWith}:{}}),this.report({removed:a},`Removed ${this.email} from group "${this.group}" in "${n}".`),0}},mh=class extends Et{static{o(this,"UsersSetPlatformAdminCommand")}static paths=[["users","set-platform-admin"]];static usage=I.Usage({category:"Users",description:"Grant/revoke platform-admin status (--on | --off)."});email=p.String({required:!0});on=p.Boolean("--on",!1,{description:"Grant."});off=p.Boolean("--off",!1,{description:"Revoke."});async execute(){let e=WA(this.on,this.off),n=await this.caller(),r=await zs(n,this.email);await n.mutation(R.platformAdmin.setPlatformAdmin,{userId:r,isPlatformAdmin:e});let i=e?"is now a platform admin":"is no longer a platform admin";return this.report({userId:r,isPlatformAdmin:e},`${this.email} ${i}.`),0}},hh=class extends Et{static{o(this,"UsersSetPlatformPermissionCommand")}static paths=[["users","set-platform-permission"]];static usage=I.Usage({category:"Users",description:"Grant/revoke a single _platform.* permission (--on | --off)."});email=p.String({required:!0});permission=p.String("--permission",{required:!0,description:"The _platform.* permission."});on=p.Boolean("--on",!1,{description:"Grant."});off=p.Boolean("--off",!1,{description:"Revoke."});async execute(){let e=WA(this.on,this.off);if(!Lc.includes(this.permission))throw new Error(`Unknown _platform.* permission "${this.permission}". One of: ${Lc.join(", ")}.`);let n=await this.caller(),r=await zs(n,this.email);await n.mutation(R.platformAdmin.setPlatformPermission,{userId:r,permission:this.permission,enabled:e});let i=e?"granted":"revoked";return this.report({userId:r,permission:this.permission,enabled:e},`${i} ${this.permission} for ${this.email}.`),0}},gh=class extends Et{static{o(this,"UsersCreateCommand")}static paths=[["users","create"]];static usage=I.Usage({category:"Users",description:"Create a tenant-less user WITH a login account (optionally a platform admin).",details:"The generated password is printed once (use --output/--quiet to keep it out of the terminal). An existing user is left untouched \u2014 no password is rotated."});email=p.String({required:!0});platformAdmin=p.Boolean("--platform-admin",!1,{description:"Make the new user a platform admin (full _platform.* set)."});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let n=await(await this.caller()).mutation(R.platformAdmin.createUser,{email:this.email,platformAdmin:this.platformAdmin});if(n.password!==void 0&&this.output!==void 0&&Yr(this.output,this.email,n.password),this.json)return this.print({...n,email:this.email}),0;let r=n.created?`Created ${this.email}${this.platformAdmin?" as a platform admin":""}.`:`${this.email} already exists (no change).`;return this.context.stdout.write(`${r}
|
|
164
|
+
`),n.password!==void 0&&!this.quiet&&this.context.stdout.write(` password: ${n.password}
|
|
165
|
+
`),0}},yh=class extends Et{static{o(this,"UsersProvisionCommand")}static paths=[["users","provision"]];static usage=I.Usage({category:"Users",description:"Create a ready-to-log-in tenant user: grants access + a credential account with a generated password. Emits the email\u2192password mapping."});email=p.String({required:!0});name=p.String("--name",{required:!0,description:"Display name for the login."});group=p.String("--group",xo,{description:`Permission group key (default: ${xo}).`});password=p.String("--password",{description:"Use this password instead of letting the server generate one."});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.platformAdmin.provisionUser,{email:this.email,name:this.name,tenantSlug:n,permissionGroupKey:this.group,password:this.password});if(this.output!==void 0&&Yr(this.output,this.email,r.password),this.json)return this.print({...r,email:this.email}),0;let i=this.output!==void 0?` \u2192 ${this.output}`:"";return this.context.stdout.write(`Provisioned ${this.email} in "${n}" (group: ${this.group})${i}.
|
|
166
|
+
`),this.quiet||this.context.stdout.write(` password: ${r.password}
|
|
167
|
+
`),0}},bh=class extends Et{static{o(this,"UsersProvisionPlatformAdminCommand")}static paths=[["users","provision-platform-admin"]];static usage=I.Usage({category:"Users",description:"Create a ready-to-log-in, tenant-less platform admin: a credential account holding the full _platform.* set, with a generated (or given) password. Emits the email\u2192password mapping."});email=p.String({required:!0});name=p.String("--name",{required:!0,description:"Display name for the platform-admin identity."});password=p.String("--password",{description:"Use this password instead of letting the server generate one."});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let n=await(await this.caller()).mutation(R.platformAdmin.provisionPlatformAdmin,{email:this.email,name:this.name,password:this.password});if(this.output!==void 0&&Yr(this.output,this.email,n.password),this.json)return this.print({...n,email:this.email}),0;let r=this.output!==void 0?` \u2192 ${this.output}`:"";return this.context.stdout.write(`Provisioned platform admin ${this.email} (${this.name})${r}.
|
|
168
|
+
`),this.quiet||this.context.stdout.write(` password: ${n.password}
|
|
169
|
+
`),0}},wh=class extends Et{static{o(this,"UsersProvisionPlatformUserCommand")}static paths=[["users","provision-platform-user"]];static usage=I.Usage({category:"Users",description:"Create a ready-to-log-in, tenant-less platform user with an exact _platform.* permission subset. Emits the email\u2192password mapping.",examples:[["Provision a schema-read-only platform user","plexus-cli --env prod users provision-platform-user --allow-prod ada@example.com --name Ada --permission _platform.schema.read --output /tmp/credentials.csv --quiet"]]});email=p.String({required:!0});name=p.String("--name",{required:!0,description:"Display name for the platform-user identity."});permissions=p.Array("--permission",{description:"Exact _platform.* permission to grant (repeatable). At least one required."});password=p.String("--password",{description:"Use this password instead of letting the server generate one."});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let e=[...new Set(this.permissions??[])];if(e.length===0)throw new Error("Pass at least one --permission.");for(let s of e)if(!Lc.includes(s))throw new Error(`Unknown _platform.* permission "${s}". One of: ${Lc.join(", ")}.`);let r=await(await this.caller()).mutation(R.platformAdmin.provisionPlatformUser,{email:this.email,name:this.name,permissions:e,password:this.password});if(this.output!==void 0&&Yr(this.output,this.email,r.password),this.json)return this.print({...r,email:this.email}),0;let i=this.output!==void 0?` \u2192 ${this.output}`:"";return this.context.stdout.write(`Provisioned platform user ${this.email} (${this.name}) with ${e.join(", ")}${i}.
|
|
170
|
+
`),this.quiet||this.context.stdout.write(` password: ${r.password}
|
|
171
|
+
`),0}},kh=class extends Et{static{o(this,"UsersSetPasswordCommand")}static paths=[["users","set-password"]];static usage=I.Usage({category:"Users",description:"Set (rotate) an existing user's login password \u2014 tenant user or platform admin. Pass --password or let the server generate one. Emits the email\u2192password mapping. Creates nothing; fails loud on an unknown or orphaned identity (run `users relink-auth` first)."});email=p.String({required:!0});password=p.String("--password",{description:"Use this password instead of letting the server generate one."});output=p.String("--output",{description:"Append the `email,password` row to this CSV file (created with a header)."});quiet=p.Boolean("--quiet",!1,{description:"Do not echo the password to stdout (use with --output)."});async execute(){let n=await(await this.caller()).mutation(R.platformAdmin.setUserPassword,{email:this.email,password:this.password});if(this.output!==void 0&&Yr(this.output,this.email,n.password),this.json)return this.print({...n,email:this.email}),0;let r=this.output!==void 0?` \u2192 ${this.output}`:"";return this.context.stdout.write(`Set password for ${this.email}${r}.
|
|
172
|
+
`),this.quiet||this.context.stdout.write(` password: ${n.password}
|
|
173
|
+
`),0}};function YM(t){return new Date(t).toISOString().replace("T"," ").slice(0,19)+"Z"}o(YM,"stamp");function JM(t){let e=[],n=t.account;e.push(n===null?`${t.email}: kein anmeldef\xE4higes Konto (keine Identit\xE4t oder nie ein Anmeldekonto angelegt) \u2014 die Anmeldeseite sendet dorthin nichts und speichert keine Anfrage.`:`${t.email}: Konto ${n.userId}, Adresse ${n.emailVerified?"best\xE4tigt":"NICHT best\xE4tigt"}`);let r=[...t.refusals.map(i=>({at:i.at,text:`abgelehnt: ${i.reason}`})),...t.letters.map(i=>({at:i.createdAt,text:`Brief ${i.templateId}: ${i.status}${i.errorCode?` (${i.errorCode})`:""}${i.lastSmtpResponse?` \u2014 Relay: ${i.lastSmtpResponse}`:""}`})),...t.sessions.map(i=>({at:i.createdAt,text:`Sitzung von ${i.ipAddress??"?"} \u2014 ${i.userAgent??"?"}`})),...t.passwordSetAt===null?[]:[{at:t.passwordSetAt,text:"Passwort gesetzt (zuletzt)"}]].sort((i,s)=>i.at-s.at);r.length===0&&e.push(" (nichts im Zeitraum)");for(let i of r)e.push(` ${YM(i.at)} ${i.text}`);e.push("Nicht erfasst:");for(let i of t.notRecorded)e.push(` - ${i}`);return e.join(`
|
|
174
|
+
`)}o(JM,"loginTrailText");var vh=class extends V{static{o(this,"UsersLoginTrailCommand")}static paths=[["users","login-trail"]];static usage=I.Usage({category:"Users",description:"Everything the platform still knows about one address's sign-in: login-page refusals, letters with the relay's answer, sessions (when, network, browser), when a password was set (platform-admin).",examples:[["Why did she get no link today?","$0 --env prod users login-trail steffi@schule.example --since 24h"]]});email=p.String({required:!0});since=p.String("--since",{description:"From: 90m, 24h, 2d or an ISO date/time (default 7d)."});async execute(){let n=await(await this.caller()).query(R.loginTrail.forAddress,{email:this.email,since:Fc(this.since??"7d")});return this.json?this.print(n):this.context.stdout.write(`${JM(n)}
|
|
175
|
+
`),0}},Sh=class extends Et{static{o(this,"UsersSetEmailCommand")}static paths=[["users","set-email"]];static usage=I.Usage({category:"Users",description:"Change an existing user's login e-mail across all their tenants (plan unless --confirm). Fails loud when the new address is taken.",details:"The password stays. Mailbox proof is reset \u2014 except when the new address is a reserved test address (.test, .example, .invalid, .localhost, example.com/.net/.org), which has no mailbox to prove.",examples:[["Plan moving a test account off a real domain","plexus-cli --env prod users set-email old@example.com --to new@example.com"],["Apply it","plexus-cli --env prod users set-email old@example.com --to new@example.com --confirm --allow-prod"]]});email=p.String({required:!0});to=p.String("--to",{required:!0,description:"The new login e-mail address."});confirm=p.Boolean("--confirm",!1,{description:"Write the change (without it, only the plan is printed)."});async execute(){let n=await(await this.caller()).mutation(R.platformAdmin.setUserEmail,{email:this.email,newEmail:this.to,dryRun:!this.confirm});if(this.json)return this.print(n),0;let r=n.tenants.length>0?n.tenants.join(", "):"no tenant";if(!n.changed)return this.context.stdout.write(`${n.from} is already ${n.to} (no change).
|
|
176
|
+
`),0;let i=n.applied?"Changed":"Would change";return this.context.stdout.write(`${i} ${n.from} \u2192 ${n.to} (${r}); mailbox proof ${n.proof}.
|
|
177
|
+
`),n.applied||this.context.stdout.write(`Dry run \u2014 re-run with --confirm to write.
|
|
178
|
+
`),0}},xh=class extends Et{static{o(this,"UsersDeleteCommand")}static paths=[["users","delete"]];static usage=I.Usage({category:"Users",description:"Deactivate a user everywhere (revoke all access; keep history)."});email=p.String({required:!0});replaceWith=p.String("--replace-with",{description:"configKey of the staff member who takes over their active applications \u2014 required while they are responsible for any. A rule naming them refuses regardless: change it first (workflow editor: \u201EPerson ersetzen\u201C, then publish)"});async execute(){let e=await this.caller(),n=await zs(e,this.email);return await e.mutation(R.platformAdmin.deactivateUserEverywhere,{userId:n,...this.replaceWith!==void 0?{replaceWith:this.replaceWith}:{}}),this.report({userId:n,deactivated:!0},`Deactivated ${this.email} everywhere (access revoked; history kept).`),0}},Ah=class extends V{static{o(this,"UsersDoctorCommand")}static paths=[["users","doctor"]];static usage=I.Usage({category:"Users",description:"List identities that cannot log in, with the repair each one needs. Exits non-zero when any are found.",details:"dead-link = stored authId points at no live account \xB7 unlinked = no authId but a live account exists for the address \xB7 no-account = no login account at all. The first two are healed with `users relink-auth`, the third needs `users provision` (there is no first login without an account)."});async execute(){let n=await(await this.caller()).query(R.platformAdmin.listOrphanedUsers,{});if(this.print(n,r=>r.map(i=>({email:i.email,kind:i.kind,repair:i.repair,userId:i.userId,storedAuthId:i.storedAuthId??"\u2014"})),["email","kind","repair","userId","storedAuthId"]),!this.json)if(n.length>0){let r=n.filter(a=>a.repair==="relink-auth"),i=n.filter(a=>a.repair==="provision"),s=n.length===1?"identity":"identities";this.context.stdout.write(`
|
|
179
|
+
${n.length} unusable ${s}:
|
|
180
|
+
`),r.length>0&&this.context.stdout.write(` ${r.length} linkable \u2014 plexus-cli users relink-auth <email>
|
|
181
|
+
`),i.length>0&&this.context.stdout.write(` ${i.length} without any login account \u2014 plexus-cli users provision --tenant <slug> --email <email> --name <name>
|
|
182
|
+
`)}else this.context.stdout.write(`No unusable identities.
|
|
183
|
+
`);return n.length>0?1:0}},Eh=class extends Et{static{o(this,"UsersRelinkAuthCommand")}static paths=[["users","relink-auth"]];static usage=I.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 n=await(await this.caller()).mutation(R.platformAdmin.relinkAuthAccount,{email:this.email}),r=n.changed?`Relinked ${this.email} to live auth account ${n.authId}.`:`${this.email} already linked to the live auth account (no change).`;return this.report(n,r),0}};function WA(t,e){if(t===e)throw new Error("Pass exactly one of --on or --off.");return t}o(WA,"requireOnOff");var zA=[oh,sh,ah,lh,dh,ch,uh,fh,ph,mh,hh,gh,yh,bh,wh,kh,vh,Sh,xh,Ah,Eh];var Th=class extends V{static{o(this,"PlatformTenantsCommand")}static paths=[["platform","tenants"]];static usage=I.Usage({category:"Platform",description:"List ALL tenants (platform-admin)"});async execute(){let n=await(await this.caller()).query(R.platformAdmin.listAllTenants,{});return this.print(n,r=>r.map(i=>({slug:i.slug,name:i.name,id:i.id})),["slug","name","id"]),0}},Ih=class extends V{static{o(this,"PlatformUsersCommand")}static paths=[["platform","users"]];static usage=I.Usage({category:"Platform",description:"List all platform users (platform-admin)"});async execute(){let n=await(await this.caller()).query(R.platformAdmin.listAllPlatformUsers,{});return this.print(n,r=>r.map(i=>({email:i.email,name:i.name,platform:i.platformPermissions.length>0?"\u2713":"",tenants:i.tenants.map(s=>s.slug).join(",")})),["email","name","platform","tenants"]),0}},$h=class extends V{static{o(this,"PlatformWorkersCommand")}static paths=[["platform","workers"]];static usage=I.Usage({category:"Platform",description:"List live job workers (platform-admin)"});async execute(){let n=await(await this.caller()).query(R.workers.listFleet,{});return this.print(n,r=>r.map(i=>{let s=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:s}}),["workerId","lifecycle","status","kinds","host","job"]),0}},_h=class extends V{static{o(this,"AuditAccessCommand")}static paths=[["audit","access"]];static usage=I.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 e=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 e.mutation(R.audit.listActorAccess,{client:this.requireTenant(e),actorEmail:this.actor});return this.printAccessRows(i.rows,i.truncated,!0),0}let n=this.application;if(this.withActor){let i=await e.mutation(R.audit.listApplicationAccessWithActor,{applicationId:n});return this.printAccessRows(i.rows,i.truncated,!0),0}let r=await e.mutation(R.audit.listApplicationAccess,{applicationId:n});return this.printAccessRows(r.rows,r.truncated,!1),0}printAccessRows(e,n,r){this.print({rows:e,truncated:n},i=>i.rows.map(s=>({at:new Date(s.at).toISOString(),purpose:s.purpose,...r?{actor:s.actorEmail??""}:{}})),r?["at","actor","purpose"]:["at","purpose"]),n&&!this.json&&this.context.stderr.write(`warning: the report was truncated \u2014 older rows are not shown.
|
|
184
|
+
`)}},ZM=200,HA=2e3,Oh=class extends V{static{o(this,"AccountsEmailChangesCommand")}static paths=[["accounts","email-changes"]];static usage=I.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 e=await this.caller(),n=this.user!==void 0?await e.query(R.accountEmailChangeLog.listForAddress,{email:this.user}):await this.tenantRows(e);return this.print(n,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(e){let n=this.requireTenant(e),r=[],i=null;for(;;){let s=await e.query(R.accountEmailChangeLog.listForTenant,{client:n,paginationOpts:{numItems:ZM,cursor:i}});if(r.push(...s.page),s.isDone)return r;if(r.length>=HA)throw new Error(`plexus accounts email-changes: more than ${HA} rows \u2014 narrow it with --user <email>.`);i=s.continueCursor}}},QA=[Th,Ih,$h,_h,Oh];import{readFileSync as Mh}from"node:fs";import Hs from"node:path";var XM={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".avif":"image/avif"};function YA(t){return XM[Hs.extname(t).toLowerCase()]}o(YA,"guessImageContentType");async function eq(t,e){if(t===void 0==(e===void 0))throw new Error("Pass exactly one of --file <path> or --url <url>.");if(t!==void 0){let a=Hs.resolve(t),l;try{l=Mh(a)}catch{throw new Error(`File not found: ${t}`)}let d=YA(a);if(d===void 0)throw new Error(`Cannot infer an image content-type from "${Hs.basename(a)}" \u2014 use a .png/.jpg/.webp/.gif file.`);return{bytes:new Uint8Array(l),contentType:d}}let n=await fetch(e);if(!n.ok)throw new Error(`Fetch failed for ${e} (${n.status} ${n.statusText}).`);let r=new Uint8Array(await n.arrayBuffer()),i=n.headers.get("content-type")?.split(";")[0]?.trim(),s=i&&i.startsWith("image/")?i:YA(new URL(e).pathname);if(s===void 0)throw new Error(`Response for ${e} is not an image (content-type "${i??"unknown"}").`);return{bytes:r,contentType:s}}o(eq,"loadLogoBytes");async function tq(t,e,n,r){let i=await t.mutation(R.branding.platformGenerateBrandingLogoUploadUrl,{client:e});return t.upload(i,n,r)}o(tq,"uploadLogo");var Ch=class extends V{static{o(this,"BrandingSetLogoCommand")}static paths=[["branding","set-logo"]];static usage=I.Usage({category:"Branding",description:"Upload a tenant's portal logo (platform-admin)",details:"Sets the external-portal logo for --tenant from a local --file or a remote --url. A one-off upload without the tenant's Branding admin UI. To move the logo with the rest of the config (export \u2192 apply, env \u2192 env), use `config apply` \u2014 it carries the file by hash (`tenant.brandingAssets.logo`).",examples:[["Upload the test tenant's logo to staging from a file","$0 --env staging --tenant test branding set-logo --file logo.png"],["Upload from an S3 URL","$0 --env staging --tenant test branding set-logo --url https://s3.example/logo.png"]]});file=p.String("--file",{description:"Local image file to upload"});url=p.String("--url",{description:"Fetch the logo image from this URL"});async execute(){let e=await this.caller(),n=this.requireTenant(e),{bytes:r,contentType:i}=await eq(this.file,this.url),s=await tq(e,n,r,i);return await e.mutation(R.branding.platformSetBrandingLogo,{client:n,slot:"primary",storageId:s}),this.print({tenant:n,slot:"primary",contentType:i,bytes:r.length,storageId:s},a=>[{field:"tenant",value:a.tenant},{field:"slot",value:a.slot},{field:"contentType",value:a.contentType},{field:"bytes",value:String(a.bytes)},{field:"storageId",value:a.storageId}]),0}},Ph=class extends V{static{o(this,"BrandingClearLogoCommand")}static paths=[["branding","clear-logo"]];static usage=I.Usage({category:"Branding",description:"Remove a tenant's portal logo (platform-admin)"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.branding.platformClearBrandingLogo,{client:n,slot:"primary"}),this.print({tenant:n,slot:"primary",cleared:!0},r=>[{field:"tenant",value:r.tenant},{field:"slot",value:r.slot},{field:"cleared",value:String(r.cleared)}]),0}};function JA(t){if(t!=="heading"&&t!=="body")throw new Error(`branding: --slot must be heading or body (got "${t}")`);return t}o(JA,"parseFontSlot");var Nh=class extends V{static{o(this,"BrandingSetFontCommand")}static paths=[["branding","set-font"]];static usage=I.Usage({category:"Branding",description:"Upload a tenant's portal font file (WOFF2) for a slot (platform-admin)",details:"Uploads --file as the font of --slot (heading|body). The backend checks the WOFF2 signature and the 2 MB cap and applies the file under the slot's configured family (`fonts.<slot>.family` \u2014 set it first with `branding set-theme` or `config apply`). A replaced file is deleted. `config apply` carries font files by hash too (`tenant.brandingAssets.fontHeading|fontBody`).",examples:[["Upload the test tenant's heading font to staging","$0 --env staging --tenant test branding set-font --slot heading --file heading.woff2"]]});slot=p.String("--slot",{required:!0,description:"heading | body"});file=p.String("--file",{required:!0,description:"Local .woff2 file"});async execute(){let e=JA(this.slot),n=Hs.resolve(this.file),r;try{r=Mh(n)}catch{throw new Error(`File not found: ${this.file}`)}let i=await this.caller(),s=this.requireTenant(i),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),{storageId:l}=await i.action(R.brandingFonts.platformSetBrandingFont,{client:s,slot:e,bytes:a});return this.print({tenant:s,slot:e,bytes:r.length,storageId:l},d=>[{field:"tenant",value:d.tenant},{field:"slot",value:d.slot},{field:"bytes",value:String(d.bytes)},{field:"storageId",value:d.storageId}]),0}},Dh=class extends V{static{o(this,"BrandingClearFontCommand")}static paths=[["branding","clear-font"]];static usage=I.Usage({category:"Branding",description:"Remove a tenant's portal font file for a slot (platform-admin; the family stays)"});slot=p.String("--slot",{required:!0,description:"heading | body"});async execute(){let e=JA(this.slot),n=await this.caller(),r=this.requireTenant(n);return await n.mutation(R.branding.platformClearBrandingFont,{client:r,slot:e}),this.print({tenant:r,slot:e,cleared:!0},i=>[{field:"tenant",value:i.tenant},{field:"slot",value:i.slot},{field:"cleared",value:String(i.cleared)}]),0}},Fh=class extends V{static{o(this,"BrandingSetThemeCommand")}static paths=[["branding","set-theme"]];static usage=I.Usage({category:"Branding",description:"Set a tenant's portal theme tokens from a JSON file (platform-admin)",details:"Replaces the branding THEME (colors/radius/logoSize/bannerDensity/filledHeader/websiteUrl/font families) wholesale from --file. Does NOT touch the uploaded logo or font files (see `branding set-logo` / `branding set-font`). The same brand tokens `config apply` writes, but surgical \u2014 it touches only branding, not the rest of the tenant config.",examples:[["Apply the test tenant's theme to staging","$0 --env staging --tenant test branding set-theme --file theme.json"]]});file=p.String("--file",{required:!0,description:"Branding theme JSON"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=Hs.resolve(this.file),i;try{i=JSON.parse(Mh(r,"utf8"))}catch(s){throw new Error(`Cannot read branding JSON ${this.file}: ${Dn(s)}`,{cause:s})}return await e.mutation(R.branding.platformUpdateBranding,{client:n,branding:i}),this.print({tenant:n,applied:!0},s=>[{field:"tenant",value:s.tenant},{field:"applied",value:String(s.applied)}]),0}},Lh=class extends V{static{o(this,"BrandingShowCommand")}static paths=[["branding","show"]];static usage=I.Usage({category:"Branding",description:"Show a tenant's current branding + resolved logo and font-file URLs (platform-admin)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.branding.platformGetBranding,{client:n});return this.print(r),0}},ZA=[Lh,Fh,Ch,Ph,Nh,Dh];var qh=class extends V{static{o(this,"FilesListCommand")}static paths=[["files","list"]];static usage=I.Usage({category:"Files",description:"List a tenant's file library (Vorlagen) / Dateien auflisten"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.tenantFiles.platformList,{client:n});return this.print(r,i=>i.map(s=>({key:s.key,label:s.label.de,labelEn:s.label.en,file:s.filename,size:String(s.sizeBytes),sha256:s.sha256.slice(0,12),usedBy:s.references.map(a=>`${a.offerKey} r${a.offerRevision}/${a.fieldKey}`).join(", ")||"-"})),["key","label","labelEn","file","size","sha256","usedBy"]),0}},Bh=class extends V{static{o(this,"FilesPutCommand")}static paths=[["files","put"]];static usage=I.Usage({category:"Files",description:"Create or replace a library file by key / Datei anlegen oder ersetzen",details:"Replacing keeps the key, so every form that attaches it offers the new file at once. Identical bytes are not stored twice; a changed label alone is still written. A new key needs --label AND --label-en. On an existing key, --label-en alone translates the stored German; a German change over a real English is refused without --label-en.",examples:[["Put a reference form","$0 --env staging --tenant test files put referenzformular ./Referenzformular.pdf --label 'Vorlage: Referenzformular' --label-en 'Template: reference form'"]]});key=p.String({name:"key"});file=p.String({name:"path"});label=p.String("--label",{description:"German label (required for a new key)"});labelEn=p.String("--label-en",{description:"English label (required for a new key)"});fileName=p.String("--file-name",{description:"Download name (default: the local file name)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=Nm(this.file),i=(await Gs(e,n)).find(u=>u.key===this.key),s=this.fileName??r.filename,a=`files put "${this.key}"`,l;if(i===void 0)l=Je(this.label,this.labelEn,a);else if(this.label!==void 0||this.labelEn!==void 0){let u={label:{...i.label}};at(u,"label",{de:this.label,en:this.labelEn},a),l=u.label}if(i!==void 0&&i.sha256===r.sha256&&l===void 0&&i.filename===s)return this.print({key:this.key,outcome:"unchanged"},u=>[{key:"key",value:u.key},{key:"outcome",value:u.outcome}]),0;let d=await SA(e,n,r.bytes,r.mimeType),c=await e.mutation(R.tenantFiles.platformPutFile,{client:n,key:this.key,...l!==void 0?{label:l}:{},filename:s,storageId:d});return this.print({key:this.key,outcome:c,sha256:r.sha256,sizeBytes:r.sizeBytes},u=>[{key:"key",value:u.key},{key:"outcome",value:String(u.outcome)},{key:"sha256",value:u.sha256},{key:"size",value:String(u.sizeBytes)}]),0}},Vh=class extends V{static{o(this,"FilesRemoveCommand")}static paths=[["files","remove"],["files","rm"]];static usage=I.Usage({category:"Files",description:"Remove a library file (refused while a form uses it) / Datei entfernen"});key=p.String({name:"key"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.tenantFiles.platformRemoveFile,{client:n,key:this.key}),this.print({removed:this.key},r=>[{key:"removed",value:r.removed}]),0}},XA=[qh,Bh,Vh];var Kh=class extends V{static{o(this,"StammdatenPersonsCommand")}static paths=[["stammdaten","persons"]];static usage=I.Usage({category:"Stammdaten",description:"Search persons in the active tenant"});query=p.String("-q,--query","",{description:"Free-text search"});limit=p.String("--limit","25",{description:"Max rows (default 25)"});all=p.Boolean("--all",!1,{description:"Fetch every page (ignores --limit)"});deleted=p.Boolean("--deleted",!1,{description:"List the persons staff deleted (the app's \u201EGel\xF6schte\u201C view) instead"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=Number.parseInt(this.limit,10);if(!Number.isFinite(r)||r<=0)throw new Error(`stammdaten: --limit must be a positive integer, got "${this.limit}".`);let i=this.all?void 0:r,s=await e.paginate(R.parties.listForMainPage,this.deleted?{client:n,deleted:!0}:{client:n,q:this.query},{max:i});return this.print(s,a=>a.map(l=>({id:l.id,name:l.name,roles:l.roles.map(d=>d.key).join(",")})),["id","name","roles"]),0}},Uh=class extends V{static{o(this,"StammdatenPersonsPurgeCommand")}static paths=[["stammdaten","persons","purge"]];static usage=I.Usage({category:"Stammdaten",description:"Hard-delete a person staff already deleted, with everything that belongs to it (plan unless --confirm). Needs _platform.config.manage.",details:"Only a person in the app's \u201EGel\xF6schte\u201C view can be purged. The plan lists the rows per table, the person's stored files (taken unless something else still holds them) and every receipt (contract, invoice, signature, \u2026) that refuses the commit. A person a running application still holds, or one linked to a user account, is refused.",examples:[["Plan","plexus-cli --env staging --tenant test stammdaten persons purge <partyId>"],["Apply","plexus-cli --env prod --tenant <slug> stammdaten persons purge <partyId> --confirm --allow-prod"]]});partyId=p.String({required:!0});confirm=p.Boolean("--confirm",!1,{description:"Delete for good (without it, only the plan is printed)."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.parties.purgeDeletedParty,{tenantSlug:n,partyId:this.partyId,dryRun:!this.confirm});if(this.json)return this.print(r),0;let i=this.context.stdout;i.write(`${r.applied?"Deleted":"Would delete"} ${r.name??"(unbenannt)"} (${r.partyId}), `),i.write(`soft-deleted ${new Date(r.deletedAt).toISOString()}
|
|
185
|
+
`);for(let a of r.rows)i.write(` ${a.table}: ${a.count}
|
|
186
|
+
`);let s=r.files.filter(a=>a.heldBy===null);i.write(`Files: ${s.length} ${r.applied?"deleted":"to delete"}, ${r.files.length-s.length} kept
|
|
187
|
+
`);for(let a of r.files)a.heldBy!==null&&i.write(` kept ${a.storageId} \u2014 held by ${a.heldBy}
|
|
188
|
+
`);if(r.blockers.length>0){i.write(`Refused \u2014 still referenced:
|
|
189
|
+
`);for(let a of r.blockers)i.write(` ${a}
|
|
190
|
+
`);return 1}return r.applied||i.write(`Dry run \u2014 re-run with --confirm to delete.
|
|
191
|
+
`),0}},eE=[Kh,Uh];var jh=class extends V{static{o(this,"AdmissionLaeufeCommand")}static paths=[["admission","laeufe"]];static usage=I.Usage({category:"Admission",description:"List Bewerbungsl\xE4ufe for the active tenant"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.admission.listBewerbungslaeufe,{tenantSlug:n});return this.print(r),0}},tE=[jh];var Gh=[{key:"fixture_test",email:"test@example.com",firstName:"Test",lastName:"Bewerber"}],Ire=new Set(Gh.map(t=>t.key));function rE(t,e,n,r){let i=t.flatMap(l=>l.angebote).find(l=>l.offerKey===e);if(i===void 0){let l=t.flatMap(d=>d.angebote.map(c=>c.offerKey));throw new Error(`applications start-test: no offer "${e}" (offers: ${l.join(", ")||"none"})`)}let s=i.stages.find(l=>l.stageKey===r||l.stageId===r);if(s===void 0){let l=i.stages.map(d=>`${d.stageKey} (${d.stageId})`);throw new Error(`applications start-test: no level "${r}" in ${e} \u2014 name it by key or id: ${l.join(", ")}`)}let a=s.runs.find(l=>l.runKey===n||l.runId===n);if(a===void 0){let l=s.runs.map(d=>`${d.runKey} (${d.runId})`);throw new Error(`applications start-test: no school year "${n}" for level ${s.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 ${s.stageKey}`);return{programRunId:a.runId,programStageId:s.stageId}}o(rE,"resolveStartTarget");function nq(t){return t.kind==="named"?t.name:`(${t.standIn??t.fallback})`}o(nq,"applicantText");function iE(t){return t.map(e=>({id:e.application._id,status:e.deletedAt?`${e.application.status} (gel\xF6scht)`:e.application.status,state:e.currentProcessStateId??"",applicant:nq(e.applicantName),test:e.application.testMode===!0?"test":""}))}o(iE,"applicationRows");var nE=Gh.map(t=>t.email);function oE(t,e,n,r){if(n===void 0&&r===void 0)throw new Error("applications start-test: name the applicant \u2014 --party <partyId> or --applicant <email>");if(n!==void 0&&r!==void 0)throw new Error("applications start-test: --party or --applicant, not both");if(lm(t,e)&&(r===void 0||!nE.includes(r.trim().toLowerCase())))throw new Error(`applications start-test: on prod only for the test account ${nE.join(", ")} (--applicant) \u2014 never a real family's`)}o(oE,"assertStartApplicant");function sE(t){let e={};for(let{address:n,...r}of t.entries)e[n]=r;return{applicationId:t.applicationId,store:e}}o(sE,"processStoreJson");function rq(t){switch(t.kind){case"form":return`form ${t.formInstanceId} (${t.state})`;case"document":return t.file===null?`document ${t.slotKey} (leer)`:`document ${t.slotKey} \xB7 v${t.file.versionNumber} ${t.file.filename??t.file.artifactId}`;case"contract":return`contract ${t.contractId} \xB7 ${t.revision===null?"keine Fassung":`Fassung ${t.revision.revisionNumber}`} \xB7 ${t.contractStatus}`;case"contracts":return t.contracts.map(e=>`${e.partKey}: contract ${e.contractId} \xB7 ${e.revision===null?"keine Fassung":`Fassung ${e.revision.revisionNumber}`} \xB7 ${e.contractStatus}`).join("; ")}}o(rq,"refText");function iq(t){return t.state!=="present"?t.reason??"":t.ref!==void 0?rq(t.ref):JSON.stringify(t.value)}o(iq,"holds");function aE(t){return t.entries.map(e=>({address:e.address,state:e.state,holds:iq(e),producer:e.producer?.label??"",written:e.writtenAt===void 0?"":new Date(e.writtenAt).toISOString()}))}o(aE,"storeRows");var lE="started",Mc="submitted",dE="load-scenario:";var cE="(Bewerbung)";function uE(t){return{nodeId:cE,actions:t.map(e=>({id:e.id,label:{de:`${e.label??e.id}${e.count===void 0?"":` (${e.count})`}`,en:`${e.label??e.id}${e.count===void 0?"":` (${e.count})`}`},...e.disabledReason===void 0?{}:{disabledReason:e.disabledReason}}))}}o(uE,"sharedAsList");function fE(t){return t.disabledReason===void 0?"":t.disabledCount===void 0?t.disabledReason:`${t.disabledReason} (${t.disabledCount})`}o(fE,"disabledText");function pE(t){return t.flatMap(({nodeId:e,actions:n})=>n.map(r=>({node:e,action:r.id,label:r.label.de,disabled:fE(r)})))}o(pE,"actionRows");function mE(t,e,n=[]){let r=t.filter(({actions:d})=>d.some(c=>c.id===e));if(r.length===0){let d=[...new Set(t.flatMap(({actions:c})=>c.map(u=>u.id)))];throw new Error(`test-actions run: no current node offers "${e}" (offered: ${d.join(", ")||"nothing"})`)}if(r.length>1)throw new Error(`test-actions run: "${e}" is offered by ${r.map(d=>d.nodeId).join(", ")} \u2014 pass --node`);let{nodeId:i,actions:s}=r[0],a=s.find(d=>d.id===e);if(a.disabledReason!==void 0)throw new Error(`test-actions run: "${e}" on ${i} is disabled: ${fE(a)}`);if(i!==cE)return i;let l=n[0];if(l===void 0)throw new Error(`test-actions run: "${e}" needs a current node \u2014 the application has none`);return l}o(mE,"nodeOfferingAction");function hE(t,e){return t.startsWith(dE)?{autoSubmit:e}:void 0}o(hE,"runParams");async function oq(t,e){let n=await t.query(R.workflow.getInstance,{applicationId:e});if(n===null)throw new Error(`test-actions: application ${e} has no workflow instance`);return n.instance.currentNodeIds}o(oq,"currentNodeIds");async function qc(t,e,n){let r=await t.query(R.workflow.listSharedTestActions,{applicationId:e});if(!r.permitted)throw new Error(`test-actions: not permitted on ${e} \u2014 not a test application, or the caller lacks testActions.run`);let i=[];for(let s of n){let a=await t.query(R.workflow.listTestActions,{applicationId:e,nodeId:s});if(a===null)throw new Error(`test-actions: node "${s}" is not in this application's workflow (or it has no instance)`);i.push({nodeId:s,actions:a})}return[...i,uE(r.actions)]}o(qc,"actionsOf");async function gE(t,e,n){return n!==void 0?[n]:await oq(t,e)}o(gE,"nodesOf");var Wh=class extends V{static{o(this,"TestActionsListCommand")}static paths=[["test-actions","list"]];static usage=I.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 e=await this.caller(),n=await qc(e,this.application,await gE(e,this.application,this.node));return this.print(n,pE,["node","action","label","disabled"]),0}},zh=class extends V{static{o(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=I.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)"});async execute(){let e=await this.caller(),n=this.application,r=await gE(e,this.application,this.node),i=mE(await qc(e,n,r),this.action,r),s=hE(this.action,this.autoSubmit);return await e.mutation(R.workflow.runTestAction,{applicationId:n,nodeId:i,actionId:this.action,...s===void 0?{}:{params:s}}),this.print({ran:this.action,on:i},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}},yE=[Wh,zh];var nr=/^[a-z][A-Za-z0-9]*$/;function Hh(t){return typeof t=="string"&&nr.test(t)}o(Hh,"isNodeId");function Ao(t,e){Hh(t)||W(`[graph/nodeIdFormat] "${t}" cannot name a node: a node id is ${nr.source}.`);let n=new Set(e);if(!n.has(t))return t;let r=2;for(;n.has(`${t}${r}`);)r++;return`${t}${r}`}o(Ao,"makeNodeId");var Zr="$env";function fe(t){if(t.scope==="env")return`${Zr}.${t.key}`;let e=t.scope==="derived"?`$derived.${t.key}`:`$${t.scope}.${t.owner}.${t.key}`;return t.path===void 0?e:`${e}.${t.path}`}o(fe,"formatAddress");var rr=/^[a-z][a-zA-Z0-9_]*$/,sq=/^[A-Za-z_][A-Za-z0-9_]*$/;function Li(t){return typeof t=="string"&&t.split(".").every(e=>sq.test(e))}o(Li,"isPath");function xr(t){if(!t.startsWith("$"))return null;let e=t.slice(1).split("."),[n,...r]=e;switch(n){case"env":{let i=r.join(".");return r.length>0&&Li(i)?{scope:"env",key:i}:null}case"derived":{let[i,...s]=r;return i===void 0||!rr.test(i)?null:bE({scope:"derived",key:i},s)}case"node":case"task":{let[i,s,...a]=r;return i===void 0||s===void 0||!rr.test(s)||(n==="node"?!nr.test(i):!rr.test(i))?null:bE({scope:n,owner:i,key:s},a)}default:return null}}o(xr,"tryParseAddress");function bE(t,e){if(e.length===0)return t;let n=e.join(".");return Li(n)?{...t,path:n}:null}o(bE,"withPath");function Se(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t,n=e.scope==="env"?["scope","key"]:e.scope==="derived"?["scope","key","path"]:["scope","owner","key","path"];if(Object.keys(e).some(r=>!n.includes(r))||e.path!==void 0&&!Li(e.path))return!1;switch(e.scope){case"env":return Li(e.key);case"derived":return typeof e.key=="string"&&rr.test(e.key);case"node":return typeof e.owner=="string"&&nr.test(e.owner)&&typeof e.key=="string"&&rr.test(e.key);case"task":return typeof e.owner=="string"&&rr.test(e.owner)&&typeof e.key=="string"&&rr.test(e.key);default:return!1}}o(Se,"isAddress");var Ar={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"}},Qs=Object.keys(Ar);function Eo(t){return Object.hasOwn(Ar,t)}o(Eo,"isEnvKey");var aq=["self-service","staff"];function wE(t,e){return{kind:"fixed",values:t,labels:e}}o(wE,"fixedSet");var Bc={of:"applicant.language",withoutValue:"de"},Er={"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:Bc},"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:Bc},"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:Bc},"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:Bc},"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:wE(At,{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:wE(aq,{staff:{de:"intern",en:"in-house"},"self-service":{de:"online (Familie)",en:"online (family)"}}),nullable:!1,label:{de:"Eingangsweg",en:"Intake channel"}}},Vc={types:Ar,fields:Er},Kc=Qs.flatMap(t=>Object.keys(Ar[t]).map(e=>`${t}.${e}`));function Ln(t){return Object.hasOwn(Er,t)}o(Ln,"isEnvLeaf");function Uc(t){return`${Zr}.${t}`}o(Uc,"envIdentifier");function Mi(t){let e=Er[t],[n,r]=t.split("."),i=Ar[n][r];i===void 0&&W(`[env] leaf "${t}" has no type`);let s=e.valueSet;return{leaf:t,type:i,label:e.label,nullable:e.nullable,...e.absent===void 0?{}:{absent:e.absent},...e.nameLanguage===void 0?{}:{nameLanguage:e.nameLanguage},...e.cohortBound===void 0?{}:{cohortBound:e.cohortBound},...s.kind==="fixed"?{enumOptions:s.values.map(a=>{let l=s.labels[a];return l===void 0&&W(`[env] "${t}" names the value "${a}" without a label`),{value:a,label:l}})}:{}}}o(Mi,"envLeaf");var kE="staffInput";var lq=["boolean"],Ys=/^[a-z][A-Za-z0-9]*$/;function vE(t){return t.staffInputs??[]}o(vE,"staffInputsOf");function SE(t){return`${kE}.${t}`}o(SE,"staffInputLeaf");function xE(t){return`${Zr}.${SE(t)}`}o(xE,"staffInputIdentifier");function dq(t){let e=`${kE}.`;return t.startsWith(e)?t.slice(e.length):null}o(dq,"staffInputKeyOfLeaf");function Js(t,e){let n=dq(e);return n===null?void 0:vE(t).find(r=>r.key===n)}o(Js,"declaredStaffInput");function cq(t){return[...vE(t).map(e=>({leaf:SE(e.key),type:e.type,label:e.label,valueSet:{kind:"open"},nullable:!1,cohortBound:!1})),...Kc.map(e=>{let n=Mi(e);return{leaf:e,type:n.type,label:n.label,valueSet:Er[e].valueSet,nullable:n.nullable,cohortBound:n.cohortBound===!0}})]}o(cq,"envLeavesFor");function AE(t){return cq(t).filter(e=>!e.cohortBound)}o(AE,"conditionEnvLeaves");function EE(t){let e={},n={};for(let{leaf:r,type:i,valueSet:s,nullable:a}of AE(t)){let[l="",d=""]=r.split(".");e[l]={...e[l]??{},[d]:i},n[r]={valueSet:s,nullable:a}}return{types:e,fields:n}}o(EE,"envConditionSchemaFor");function RE(t){let e=t.staffInputs;if(e===void 0)return[];if(!Array.isArray(e))return[{path:"staffInputs",reason:"[staffInput/shape] graph.staffInputs muss eine Liste sein."}];let n=[],r=new Set;return e.forEach((i,s)=>{let a=`staffInputs[${s}]`,l=i;if(l===null||typeof l!="object"||typeof l.key!="string"){n.push({path:a,reason:"[staffInput/shape] Eine interne Angabe braucht key, type und label ({ de, en })."});return}let d=`Interne Angabe "${l.key}"`;Ys.test(l.key)||n.push({path:`${a}.key`,reason:`[staffInput/keyFormat] ${d}: Schl\xFCssel beginnt mit einem Kleinbuchstaben und enth\xE4lt nur Buchstaben und Ziffern.`}),r.has(l.key)&&n.push({path:`${a}.key`,reason:`[staffInput/duplicateKey] ${d}: Schl\xFCssel ist doppelt vergeben.`}),r.add(l.key),lq.includes(l.type)||n.push({path:`${a}.type`,reason:`[staffInput/unknownType] ${d}: Typ "${String(l.type)}" \u2014 erlaubt ist nur "boolean" (K\xE4stchen).`});let c=wt(l.label);c==="not-localized"?n.push({path:`${a}.label`,reason:`[staffInput/shape] ${d}: label muss { de, en } sein.`}):c.length>0&&n.push({path:`${a}.label`,reason:`[i18n/missingTranslation] ${d}: Beschriftung fehlt in ${c.join(", ")}.`})}),n}o(RE,"staffInputIssues");var tg={required:!0,description:"Offer slug (its offerKey)"},Qh=class extends V{static{o(this,"ApplicationsListCommand")}static paths=[["applications","list"]];static usage=I.Usage({category:"Admission",description:"List an offer's applications (id, status, board state, applicant, test)"});offer=p.String("--offer",tg);testOnly=p.Boolean("--test-only",!1,{description:"Only test applications"});async execute(){let e=await this.caller(),n=await e.query(R.admission.listForAngebot,{client:this.requireTenant(e),offerKey:this.offer}),r=iE(n).filter(i=>!this.testOnly||i.test==="test");return this.print(r,i=>i,["id","status","state","applicant","test"]),0}},Yh=class extends V{static{o(this,"ApplicationsCountsCommand")}static paths=[["applications","counts"]];static usage=I.Usage({category:"Admission",description:"Count an offer's applications per list"});offer=p.String("--offer",tg);async execute(){let e=await this.caller(),n=await e.query(R.admission.getCountsByListForAngebot,{client:this.requireTenant(e),offerKey:this.offer});return this.print(n,r=>[...Object.entries(r.counts).map(([i,s])=>({list:i,count:String(s)})),{list:"total",count:String(r.total)}],["list","count"]),0}},Jh=class extends V{static{o(this,"ApplicationsShowCommand")}static paths=[["applications","show"]];static usage=I.Usage({category:"Admission",description:"One application: status, test flag, offer, current workflow nodes"});application=p.String({required:!0});async execute(){let e=await this.caller(),n=this.application,r=await e.query(R.admission.get,{applicationId:n});if(r===null)throw new Error(`applications show: no application ${n} (or not visible to you)`);let i=await e.query(R.workflow.getInstance,{applicationId:n});return this.print({application:r,currentNodes:i?.instance.currentNodeIds??[]},s=>[{key:"id",value:n},{key:"status",value:s.application.status},{key:"test",value:s.application.testMode?"ja":"nein"},{key:"offer",value:s.application.offerKey},{key:"current nodes",value:s.currentNodes.join(", ")}]),0}},Zh=class extends V{static{o(this,"ApplicationsStoreCommand")}static paths=[["applications","store"]];static usage=I.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 n=await(await this.caller()).query(R.processStoreView.get,{applicationId:this.application});return this.print(sE(n),()=>aE(n),["address","state","holds","producer","written"]),0}},Xh=class extends V{static{o(this,"ApplicationsStartTestCommand")}static paths=[["applications","start-test"]];static usage=I.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",tg);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 e=await this.caller();oE(this.resolvedTarget(),this.prodUrls(),this.party,this.applicant);let n=this.requireTenant(e),r=rE(await e.query(R.admission.listAdmissionTree,{client:n}),this.offer,this.run,this.stage),i=this.party;if(this.applicant!==void 0){let d=await e.query(R.applicants.partyByEmail,{client:n,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 s=await e.mutation(R.admission.staffStartApplicationForParty,{client:n,offerKey:this.offer,partyId:i,programRunId:r.programRunId,programStageId:r.programStageId,...this.proxy===void 0?{}:{startInProxy:this.proxy},staffInputs:uq(this.staffInput??[]),testMode:!0,...this.version===void 0?{}:{offerVersionId:this.version}}),a,l;try{let d=await e.query(R.workflow.getInstance,{applicationId:s.applicationId});if(d===null)throw new Error("the started application has no workflow instance");a=d.instance.currentNodeIds,l=(await qc(e,s.applicationId,a)).flatMap(c=>c.actions.map(u=>u.id))}catch(d){throw new Error(`applications start-test: started ${s.applicationId}, but reading its state failed: ${d instanceof Error?d.message:String(d)}`,{cause:d})}return this.print({applicationId:s.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}},eg=class extends V{static{o(this,"ApplicationsDiscardTestCommand")}static paths=[["applications","discard-test"]];static usage=I.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(R.admission.discardTest,{applicationId:this.application}),this.print({discarded:this.application},n=>[{key:"discarded",value:n.discarded}]),0}},TE=[Qh,Yh,Jh,Zh,Xh,eg];function uq(t){return t.map(e=>{let[n="",r,...i]=e.split("=");if(!Ys.test(n)||r!=="true"&&r!=="false"||i.length>0)throw new Error(`--staff-input "${e}": expected key=true or key=false`);return{key:n,value:r==="true"}})}o(uq,"parseStaffInputs");import{readFileSync as zq}from"node:fs";import{existsSync as Gc,mkdirSync as IE,readFileSync as sg,writeFileSync as fq}from"node:fs";import ir from"node:path";var rg="bundle.yaml",$E="manifest.json",ig="smartforms",_E="workflow.json";function ng(t){return JSON.parse(sg(t,"utf8"))}o(ng,"readJson");function Ue(t){return JSON.stringify(og(t),null,2)+`
|
|
192
|
+
`}o(Ue,"canonicalJson");function og(t){return Array.isArray(t)?t.map(og):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,og(t[e])])):t}o(og,"sortKeys");function _e(t){let e=ir.resolve(t),n=ir.join(e,rg);if(!Gc(n))throw new Error(`offer: no ${rg} in ${e}`);let r=zr.load(sg(n,"utf8"));pq(r,n);let i=ir.join(e,_E),s,a=Object.keys(r.smartforms??{});if(a.length>0){s={};for(let l of a){let d=ir.join(e,ig,`${l}.json`);if(!Gc(d))throw new Error(`offer: bundle.yaml declares smartform "${l}" but ${ig}/${l}.json is missing`);s[l]=ng(d)}}return{dir:e,index:r,manifest:ng(ir.join(e,$E)),...s?{smartforms:s}:{},...Gc(i)?{workflow:ng(i)}:{}}}o(_e,"readBundle");function jc(t,e,n,r){Gc(t)&&Ue(r(sg(t,"utf8")))===Ue(e)||fq(t,n,"utf8")}o(jc,"writeIfChanged");function or(t){if(IE(t.dir,{recursive:!0}),jc(ir.join(t.dir,rg),t.index,zr.dump(t.index,{lineWidth:100,sortKeys:!1}),e=>zr.load(e)),jc(ir.join(t.dir,$E),t.manifest,Ue(t.manifest),JSON.parse),t.smartforms!==void 0){let e=ir.join(t.dir,ig);IE(e,{recursive:!0});for(let[n,r]of Object.entries(t.smartforms))jc(ir.join(e,`${n}.json`),r,Ue(r),JSON.parse)}t.workflow!==void 0&&jc(ir.join(t.dir,_E),t.workflow,Ue(t.workflow),JSON.parse)}o(or,"writeBundle");function pq(t,e){let n=[];if(t?.module||n.push("module"),t?.tenant||n.push("tenant"),t?.label||n.push("label"),t?.slugs?.manifest||n.push("slugs.manifest"),n.length>0)throw new Error(`offer: ${e} is missing required keys: ${n.join(", ")}`)}o(pq,"assertIndex");var mq=new Set(["if","else","in","true","false","null"]),hq=new Set(["==","!=","<=",">=","&&","||"]);function gq(t){return t>="0"&&t<="9"}o(gq,"isDigit");function yq(t){return/[a-zA-Z_$]/.test(t)}o(yq,"isIdentStart");function bq(t){return/[a-zA-Z0-9_.$]/.test(t)}o(bq,"isIdentCont");function wq(t){let e=[],n=0;for(;n<t.length;){let r=t.charAt(n);if(r===" "||r===" "||r===`
|
|
193
|
+
`||r==="\r"){n++;continue}if(r==="'"){let s=n+1,a="";for(;s<t.length&&t.charAt(s)!=="'";)t.charAt(s)==="\\"&&s+1<t.length?(a+=t.charAt(s+1),s+=2):(a+=t.charAt(s),s++);s>=t.length&&W(`Unterminated string at ${n}`),e.push({t:"str",v:a}),n=s+1;continue}if(gq(r)){let s=n;for(;s<t.length&&/[0-9.]/.test(t.charAt(s));)s++;e.push({t:"num",v:Number(t.slice(n,s))}),n=s;continue}if(yq(r)){let s=n;for(;s<t.length&&bq(t.charAt(s));)s++;let a=t.slice(n,s);mq.has(a)?e.push({t:"kw",v:a}):e.push({t:"ident",v:a}),n=s;continue}let i=t.slice(n,n+2);if(hq.has(i)){e.push({t:"op",v:i}),n+=2;continue}if("<>!".includes(r)){e.push({t:"op",v:r}),n++;continue}if("()[],".includes(r)){e.push({t:"punct",v:r}),n++;continue}W(`Unexpected char '${r}' at ${n}`)}return e}o(wq,"tokenise");var OE=1e4,CE=128;function Ro(t){t.depth++,t.depth>CE&&W(`Expression nesting too deep (> ${CE})`)}o(Ro,"enterDepth");function ME(t){return t.pos<t.tokens.length?t.tokens[t.pos]:null}o(ME,"peek");function Nt(t){let e=t.tokens[t.pos];return e||W(`Unexpected end at ${t.pos}`),t.pos++,e}o(Nt,"take");function Dt(t,e,n){let r=ME(t);return!(!r||r.t!==e||n!==void 0&&r.v!==n)}o(Dt,"match");function qi(t,e,n){return Dt(t,e,n)||W(`Expected ${e}${n?`:${n}`:""} at ${t.pos}`),Nt(t)}o(qi,"expect");function Tr(t){Ro(t);try{return Dt(t,"kw","if")?kq(t):vq(t)}finally{t.depth--}}o(Tr,"parseExpr");function kq(t){qi(t,"kw","if"),qi(t,"punct","(");let e=Tr(t);qi(t,"punct",")");let n=Tr(t);qi(t,"kw","else");let r=Tr(t);return{kind:"if",cond:e,then:n,else:r}}o(kq,"parseIf");function vq(t){let e=PE(t),n=0;try{for(;Dt(t,"op","||");){Nt(t),Ro(t),n++;let r=PE(t);e={kind:"binary",op:"||",left:e,right:r}}}finally{t.depth-=n}return e}o(vq,"parseLogicOr");function PE(t){let e=NE(t),n=0;try{for(;Dt(t,"op","&&");){Nt(t),Ro(t),n++;let r=NE(t);e={kind:"binary",op:"&&",left:e,right:r}}}finally{t.depth-=n}return e}o(PE,"parseLogicAnd");function NE(t){let e=DE(t),n=0;try{for(;Dt(t,"op","==")||Dt(t,"op","!=");){let r=Nt(t).v;Ro(t),n++;let i=DE(t);e={kind:"binary",op:r,left:e,right:i}}}finally{t.depth-=n}return e}o(NE,"parseEquality");function DE(t){let e=lg(t),n=0;try{for(;Dt(t,"op","<")||Dt(t,"op","<=")||Dt(t,"op",">")||Dt(t,"op",">=")||Dt(t,"kw","in");){let r=Nt(t),i=r.t==="kw"?"in":r.v;Ro(t),n++;let s=lg(t);e={kind:"binary",op:i,left:e,right:s}}}finally{t.depth-=n}return e}o(DE,"parseCompare");function lg(t){if(Dt(t,"op","!")){Nt(t),Ro(t);try{return{kind:"unary",op:"!",operand:lg(t)}}finally{t.depth--}}return Sq(t)}o(lg,"parseUnary");function Sq(t){let e=ME(t);if(e||W("Unexpected end"),e.t==="num")return Nt(t),{kind:"num",value:e.v};if(e.t==="str")return Nt(t),{kind:"str",value:e.v};if(e.t==="kw"&&e.v==="true")return Nt(t),{kind:"bool",value:!0};if(e.t==="kw"&&e.v==="false")return Nt(t),{kind:"bool",value:!1};if(e.t==="kw"&&e.v==="null")return Nt(t),{kind:"null"};if(e.t==="punct"&&e.v==="("){Nt(t);let n=Tr(t);return qi(t,"punct",")"),n}if(e.t==="punct"&&e.v==="["){Nt(t);let n=[];if(!Dt(t,"punct","]"))for(n.push(Tr(t));Dt(t,"punct",",");)Nt(t),n.push(Tr(t));return qi(t,"punct","]"),{kind:"arr",items:n}}if(e.t==="ident"){let n=e.v;if(Nt(t),Dt(t,"punct","(")){Nt(t);let r=[];if(!Dt(t,"punct",")"))for(r.push(Tr(t));Dt(t,"punct",",");)Nt(t),r.push(Tr(t));return qi(t,"punct",")"),{kind:"call",name:n,args:r}}return{kind:"ident",path:n}}W(`Unexpected token at ${t.pos}`)}o(Sq,"parsePrimary");function Ft(t){t.length>OE&&W(`Expression too long (${t.length} > ${OE})`);let e={tokens:wq(t),pos:0,depth:0},n=Tr(e);return e.pos<e.tokens.length&&W(`Unexpected trailing token at ${e.pos}`),n}o(Ft,"parseExpression");var xq=new Map([["today",()=>new Date().toISOString().slice(0,10)],["years_between",(t,e)=>{if(typeof t!="string"||typeof e!="string")return null;let n=new Date(t),r=new Date(e);if(isNaN(n.getTime())||isNaN(r.getTime()))return null;let i=r.getFullYear()-n.getFullYear(),s=r.getMonth()-n.getMonth();return(s<0||s===0&&r.getDate()<n.getDate())&&i--,i}],["length",t=>typeof t=="string"||Array.isArray(t)?t.length:0]]);function lt(t,e){switch(t.kind){case"num":return t.value;case"str":return t.value;case"bool":return t.value;case"null":return null;case"ident":{let n=Object.hasOwn(e.values,t.path)?e.values[t.path]:void 0;return n===void 0?null:n}case"arr":return t.items.map(n=>lt(n,e));case"unary":{let n=lt(t.operand,e);return!Xr(n)}case"call":{let n=e.functions!==void 0&&Object.hasOwn(e.functions,t.name)?e.functions[t.name]:xq.get(t.name);n||W(`Unknown function '${t.name}'`);let r=t.args.map(i=>lt(i,e));return n(...r)}case"binary":return Aq(t.op,t.left,t.right,e);case"if":return Xr(lt(t.cond,e))?lt(t.then,e):lt(t.else,e)}}o(lt,"evaluate");function Aq(t,e,n,r){if(t==="&&"){let a=lt(e,r);return Xr(a)?Xr(lt(n,r)):!1}if(t==="||"){let a=lt(e,r);return Xr(a)?!0:Xr(lt(n,r))}let i=lt(e,r),s=lt(n,r);switch(t){case"==":return ag(i,s);case"!=":return!ag(i,s);case"<":{let[a,l]=Wc(i,s);return a!==null&&l!==null&&a<l}case"<=":{let[a,l]=Wc(i,s);return a!==null&&l!==null&&a<=l}case">":{let[a,l]=Wc(i,s);return a!==null&&l!==null&&a>l}case">=":{let[a,l]=Wc(i,s);return a!==null&&l!==null&&a>=l}case"in":return Array.isArray(s)?s.some(a=>ag(a,i)):!1}}o(Aq,"evalBinary");function Wc(t,e){return[FE(t),FE(e)]}o(Wc,"orderedOperands");function FE(t){if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){if(t.trim()==="")return null;let e=Number(t);return Number.isFinite(e)?e:null}return null}o(FE,"numericOperand");function ag(t,e){return t===e?!0:t==null||e==null?!1:typeof t=="number"&&typeof e=="string"?t===Number(e):typeof t=="string"&&typeof e=="number"?Number(t)===e:!1}o(ag,"looseEq");function Xr(t){return!(t==null||t===!1||t===0||t===""||Array.isArray(t)&&t.length===0)}o(Xr,"truthy");function dt(t){let e=new Set;return Rr(t,e),[...e]}o(dt,"dependencies");function Rr(t,e){switch(t.kind){case"ident":e.add(t.path);return;case"call":t.args.forEach(n=>Rr(n,e));return;case"arr":t.items.forEach(n=>Rr(n,e));return;case"unary":Rr(t.operand,e);return;case"binary":Rr(t.left,e),Rr(t.right,e);return;case"if":Rr(t.cond,e),Rr(t.then,e),Rr(t.else,e);return;default:return}}o(Rr,"walk");var LE=new Map;function Mn(t){let e=LE.get(t);return e||(e=Ft(t),LE.set(t,e)),e}o(Mn,"parseCached");function Eq(t,e){return lt(Mn(t),e)}o(Eq,"evalExpression");function qE(t,e){return Xr(Eq(t,e))}o(qE,"evalBoolean");var BE=/^\d{4}-\d{2}-\d{2}$/;function Bi(t){if(typeof t!="object"||t===null)return"keine Reduktion";let e=t;if(e.kind==="none")return Object.keys(e).length===1?null:'\u201Ekeine Reduktion" tr\xE4gt keine weiteren Angaben';if(e.kind!=="amount")return`unbekannte Art ${JSON.stringify(e.kind)}`;let{amount:n,activeFrom:r,activeTo:i}=e;return typeof n!="number"||!Number.isFinite(n)||n<=0?"der Betrag muss gr\xF6\xDFer als 0 \u20AC sein":Number.isInteger(Number((n*100).toFixed(6)))?typeof r!="string"||!BE.test(r)?"der Beginn fehlt (JJJJ-MM-TT)":typeof i!="string"||!BE.test(i)?"das Ende fehlt (JJJJ-MM-TT)":i<r?"das Ende liegt vor dem Beginn":e.floorTotal!==void 0&&(typeof e.floorTotal!="number"||!Number.isSafeInteger(e.floorTotal)||e.floorTotal<0)?"die Untergrenze muss ein nichtnegativer Centbetrag sein":e.pricePeriod!==void 0&&!["month","year","once","unit"].includes(String(e.pricePeriod))?"ung\xFCltige Preisperiode":Object.keys(e).some(s=>!["kind","amount","activeFrom","activeTo","floorTotal","pricePeriod"].includes(s))?"unbekannte Angaben":null:"der Betrag hat mehr als zwei Nachkommastellen"}o(Bi,"reductionShapeIssue");function VE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.groupKey=="string"&&e.groupKey.length>0&&Array.isArray(e.grantKeys)&&e.grantKeys.every(n=>typeof n=="string"&&n.length>0)&&(e.reduction===void 0||Bi(e.reduction)===null&&e.reduction.kind==="amount")&&Object.keys(e).every(n=>n==="groupKey"||n==="grantKeys"||n==="reduction")}o(VE,"isPricedGroupValue");var dg={string:"text",email:"text",tel:"text",number:"number",date:"date",boolean:"boolean",enum:"option",address:"composite",docRef:"file",party:"edge",personRef:"edge",personList:"edge",roleKey:"edge",pricedItem:"pricedItem",pricedGroup:"pricedGroup",reduction:"reduction",article:"article",legalEntity:"legalEntity"},cg=Object.keys(dg);function To(t){return typeof t=="string"&&t in dg}o(To,"isValueType");function mn(t){return t===void 0?void 0:dg[t]}o(mn,"dataTypeOf");function zc(t,e){let n=mn(t),r=mn(e);return n!==void 0&&n===r}o(zc,"valueTypesCompatible");function KE(t,e){let n=mn(e.type),r=JSON.stringify(t),i=`slot type "${e.type}" takes a binding, not a literal`;if(n===void 0||n==="composite"||n==="file"||n==="edge")return i;if(t===null)return null;switch(n){case"text":return typeof t=="string"?null:`${r} is not a text (slot type "${e.type}")`;case"date":return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?null:`${r} is not a date YYYY-MM-DD`;case"number":return typeof t=="number"&&Number.isFinite(t)?null:`${r} is not a number`;case"boolean":return typeof t=="boolean"?null:`${r} is not true/false`;case"option":{if(typeof t!="string")return`${r} is not an option value`;let s=(e.enumOptions??[]).map(a=>a.value);return s.length===0||s.includes(t)?null:`${r} is not one of the options ${s.join(", ")}`}case"pricedItem":{let s=t;return typeof s=="object"&&typeof s.itemKey=="string"&&s.itemKey.length>0&&Array.isArray(s.grantKeys)&&s.grantKeys.every(a=>typeof a=="string")?null:`${r} is not a priced item {"itemKey":\u2026,"grantKeys":[\u2026]}`}case"pricedGroup":return VE(t)?null:`${r} is not a priced group {"groupKey":\u2026,"grantKeys":[\u2026]}`;case"article":return typeof t=="string"&&t.length>0?null:`${r} is not an article key`;case"legalEntity":return typeof t=="string"&&t.length>0?null:`${r} is not a legal entity key`;case"reduction":{let s=Bi(t);return s===null?null:`${r} is not a reduction \u2014 ${s}`}}}o(KE,"literalTypeIssue");var UE=Zr,Vi=`${UE}.`,Rq=new Set(["text","number","date","boolean","option","edge"]);function Hc(t,e){let n=t[e];return n===void 0&&W(`[env/unknownKey] no environment key '${e}'`),typeof n=="string"?null:Object.keys(n)}o(Hc,"contextFields");function jE(t,e){return Object.hasOwn(t,e)}o(jE,"isContextKey");function GE(t){let e=[];for(let n of Object.keys(t)){let r=Hc(t,n);if(r===null)e.push(n);else for(let i of r)e.push(`${n}.${i}`)}return e}o(GE,"leafPaths");function Zs(t,e){let[n="",r,...i]=e.split(".");if(!jE(t,n)||i.length>0)return;let s=t[n];if(typeof s=="string")return r===void 0?s:void 0;if(!(r===void 0||!Object.hasOwn(s,r)))return s[r]}o(Zs,"leafType");function WE(t){let e=new Set;for(let n of t){let r=Io(n);r!==null&&e.add(r.split(".")[0])}return[...e]}o(WE,"contextKeysOf");function Io(t){return t.startsWith(Vi)?t.slice(Vi.length):null}o(Io,"contextPathOf");function Xs(t){return t===UE||t.startsWith(Vi)}o(Xs,"isContextIdentifier");function Qc(t,e){let n=Io(e)??"",[r=""]=n.split("."),i=Object.keys(t);if(!jE(t,r))return{code:"env/unknownKey",message:`'${e}' names no environment key \u2014 known: ${i.join(", ")}.`};if(Zs(t,n)!==void 0)return null;let s=Hc(t,r);return{code:"env/unknownKey",message:s===null?`'${e}': environment key '${r}' is a single value \u2014 read it as '${Vi}${r}'.`:`'${e}': environment key '${r}' has the fields ${s.join(", ")}.`}}o(Qc,"identifierIssue");function Yc(t,e,n=Object.keys(t)){let r={};for(let i of n){let s=Hc(t,i),a=Object.hasOwn(e,i)?e[i]:void 0;if(a===void 0&&W(`[env/missing] context key '${i}' was not supplied`),s===null){r[`${Vi}${i}`]=a;continue}for(let l of s){let d=typeof a=="object"&&a!==null&&Object.hasOwn(a,l)?a[l]:void 0;d===void 0&&W(`[env/missing] context key '${i}' carries no '${l}'`),r[`${Vi}${i}.${l}`]=d}}return r}o(Yc,"flatten");function zE(t,e,n){if(n===void 0)return!1;let r=Hc(t,e);return r===null?!0:typeof n=="object"&&n!==null&&r.every(i=>n[i]!==void 0)}o(zE,"contextValueComplete");function Tq(t,e){switch(e){case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"date":return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}/.test(t);default:return typeof t=="string"}}o(Tq,"valueMatchesDataType");function HE(t,e,n=Object.keys(t.types)){let r=new Set(n);for(let i of GE(t.types)){if(!r.has(i.split(".")[0]))continue;let s=e[`${Vi}${i}`];s===void 0&&W(`[env/missing] context path '${i}' was not supplied`);let a=t.fields[i];if(s===null){a.nullable||W(`[env/null] context path '${i}' is not nullable but carries null`);continue}let l=mn(Zs(t.types,i));Tq(s,l)||W(`[env/type] context path '${i}' expects ${l}, got ${JSON.stringify(s)}`),a.valueSet.kind==="fixed"&&!a.valueSet.values.includes(s)&&W(`[env/value] context path '${i}' carries '${String(s)}', outside ${a.valueSet.values.join(" | ")}`)}}o(HE,"assertContextValues");function Iq(t){let e=[],n=GE(t.types);for(let r of n){let i=Zs(t.types,r),s=mn(i);if(!To(i)||s===void 0||!Rq.has(s)){e.push(`'${r}' has type '${String(i)}', not a scalar value type`);continue}let a=Object.hasOwn(t.fields,r)?t.fields[r]:void 0;if(a===void 0){e.push(`'${r}' has no field spec (value set + nullability)`);continue}a.valueSet.kind==="fixed"&&(a.valueSet.values.length===0&&e.push(`'${r}' has an empty fixed value set`),s!=="text"&&s!=="option"&&e.push(`'${r}' is ${s}; a fixed value set needs a text or option leaf`))}for(let r of Object.keys(t.fields))n.includes(r)||e.push(`field spec '${r}' names no leaf of the schema`);return e}o(Iq,"schemaIssues");function $o(t){let e=Iq(t);e.length>0&&W(`[env/schema] ${e.join("; ")}`)}o($o,"assertSchema");var ug={length:{params:["text"],returns:"number"},years_between:{params:["date","date"],returns:"number"}};function ei(t){return JSON.stringify(t)}o(ei,"canonical");function Oo(t){return t.kind==="binary"&&t.op==="&&"?[...Oo(t.left),...Oo(t.right)]:[t]}o(Oo,"conjuncts");function JE(t,e){let n;try{n=Ft(t)}catch{return!1}let r=ei(Ft(e));return Oo(n).some(i=>ei(i)===r)}o(JE,"hasConjunct");function ZE(t,e){try{return ei(Ft(t))===ei(Ft(e))}catch{return!1}}o(ZE,"sameCondition");function XE(t){let e=[];for(let n of t)e.push(...dt(Mn(n)));return WE(e)}o(XE,"contextKeysRead");function eR(t){try{return dt(Ft(t)).some(Xs)}catch{return!1}}o(eR,"readsContext");var $q=/^\d{4}-\d{2}-\d{2}$/,_q=new Set(["==","!=","<","<=",">",">=","in"]),Oq=new Set(["<","<=",">",">="]);function Zc(t,e,n=[]){$o(e);let r;try{r=Ft(t)}catch(a){return[Lt("condition/parse",`condition '${t}' does not parse: ${a.message}`)]}let i=[];for(let a of dt(r)){if(!Xs(a)){i.push(Lt("condition/foreignIdentifier",`'${a}' is not a context identifier \u2014 conditions read only '$env.*'`));continue}let l=Qc(e.types,a);l!==null&&i.push(Lt("condition/unknownIdentifier",l.message))}if(i.length>0)return i;let s=sr(r,e,i);ea(s)||i.push(Lt("condition/notBoolean",`condition '${t}' is not a yes/no expression`)),Dq(r,e,i);for(let{identifier:a,op:l}of mg(r,e))i.push(Lt("condition/unguardedNullable",`'${l}' over '${a}', which may be null, needs a guard '${a} != null &&' before it`));return i.push(...Cq(r,n)),i}o(Zc,"conditionIssues");function Cq(t,e){let n=Oo(t).map(ei);return e.flatMap(r=>{let i=Ft(r),s=Pq(i);return s===null||!n.includes(ei(s))?[]:[{severity:"info",code:"condition/guardForm",message:`[condition/guardForm] a mirrored guard does not count \u2014 write it exactly as '${r}'`}]})}o(Cq,"guardFormHints");function Pq(t){if(t.kind!=="binary"||t.op!=="=="&&t.op!=="!=")return null;let e={...t,left:t.right,right:t.left};return ei(e)===ei(t)?null:e}o(Pq,"mirror");function ea(t){return t.t==="unknown"||t.t==="data"&&t.dt==="boolean"}o(ea,"isBooleanish");function tR(t){let e=Io(t);return e===null&&W(`[condition/invariant] '${t}' reached a pass that only sees $env identifiers`),e}o(tR,"contextPath");function nR(t,e){let n=Io(e);return n!==null&&t.fields[n]?.nullable===!0}o(nR,"isNullableLeaf");function Nq(t,e){let n=mn(Zs(t.types,tR(e)));return n===void 0?{t:"unknown"}:{t:"data",dt:n}}o(Nq,"identType");function Jc(t,e){return t.t==="unknown"||e.t==="unknown"||t.t==="null"||e.t==="null"?!0:t.t==="array"||e.t==="array"?!1:t.t==="str"&&e.t==="str"?!0:t.t==="str"?QE(t.value,e.dt):e.t==="str"?QE(e.value,t.dt):t.dt===e.dt}o(Jc,"fits");function QE(t,e){return e==="text"||e==="option"||e==="edge"?!0:e==="date"?$q.test(t):!1}o(QE,"strFits");function YE(t){return t.t==="unknown"?"unknown":t.t==="data"&&t.dt==="number"?"number":null}o(YE,"orderedCategory");function sr(t,e,n){switch(t.kind){case"num":return{t:"data",dt:"number"};case"bool":return{t:"data",dt:"boolean"};case"str":return{t:"str",value:t.value};case"null":return{t:"null"};case"ident":return Nq(e,t.path);case"arr":for(let r of t.items)sr(r,e,n);return{t:"array"};case"unary":{let r=sr(t.operand,e,n);return ea(r)||n.push(Lt("condition/notBoolean","'!' needs a yes/no operand")),{t:"data",dt:"boolean"}}case"call":{let r=Object.hasOwn(ug,t.name)?ug[t.name]:void 0,i=t.args.map(l=>sr(l,e,n));return r===void 0?(n.push(Lt("condition/functionNotAllowed",`function '${t.name}' is not allowed \u2014 allowed: ${Object.keys(ug).join(", ")}`)),{t:"unknown"}):(i.length===r.params.length&&i.every((l,d)=>l.t!=="null"&&Jc(l,{t:"data",dt:r.params[d]}))||n.push(Lt("condition/typeMismatch",`'${t.name}' takes (${r.params.join(", ")})`)),{t:"data",dt:r.returns})}case"if":{let r=sr(t.cond,e,n);ea(r)||n.push(Lt("condition/notBoolean","'if' needs a yes/no condition"));let i=sr(t.then,e,n),s=sr(t.else,e,n);return Jc(i,s)||n.push(Lt("condition/typeMismatch","the two arms of 'if' differ in type")),i.t==="null"?s:i}case"binary":{let r=sr(t.left,e,n),i=sr(t.right,e,n);if(t.op==="&&"||t.op==="||")(!ea(r)||!ea(i))&&n.push(Lt("condition/notBoolean",`'${t.op}' needs yes/no operands`));else if(t.op==="in")t.right.kind!=="arr"?n.push(Lt("condition/inWithoutArray","'in' needs a list on its right, e.g. ['a', 'b']")):t.right.items.every(s=>Jc(r,sr(s,e,[])))||n.push(Lt("condition/typeMismatch","a list item of 'in' does not match the left operand's type"));else if(Oq.has(t.op)){let s=YE(r),a=YE(i);(s===null||a===null||s!=="unknown"&&a!=="unknown"&&s!==a)&&n.push(Lt("condition/orderedComparison",`'${t.op}' compares only numbers \u2014 for dates use years_between(\u2026)`))}else Jc(r,i)||n.push(Lt("condition/typeMismatch",`'${t.op}' compares values of different types`));return{t:"data",dt:"boolean"}}}}o(sr,"typeOf");function fg(t){return t.kind==="str"||t.kind==="num"||t.kind==="bool"}o(fg,"isLiteral");function rR(t){let e=[],n=o(r=>{if(r.kind==="binary"&&_q.has(r.op)){if(r.left.kind==="ident"){let i=r.op==="in"&&r.right.kind==="arr"?r.right.items.filter(fg):fg(r.right)?[r.right]:[];i.length>0&&e.push({ident:r.left.path,literals:i})}r.right.kind==="ident"&&fg(r.left)&&e.push({ident:r.right.path,literals:[r.left]})}iR(r,n)},"visit");return n(t),e}o(rR,"comparedLiterals");function Dq(t,e,n){for(let{ident:r,literals:i}of rR(t)){let s=Fq(r,i,e);s!==null&&n.push(s)}}o(Dq,"literalIssues");function pg(t,e){let n;try{n=Ft(t)}catch{return[]}let r=[];for(let{ident:i,literals:s}of rR(n)){let a=Io(i);if(!(a===null||e.fields[a]?.valueSet.kind!=="live"))for(let l of s)l.kind==="str"&&r.push({path:a,value:l.value})}return r}o(pg,"liveLiterals");function Fq(t,e,n){let r=n.fields[tR(t)]?.valueSet;if(r?.kind==="unstable")return Lt("condition/literalOnUnstable",`'${t}' is not stable across environments \u2014 compare it to no literal; branch on a stable attribute instead`);if(r?.kind!=="fixed")return null;let i=e.flatMap(s=>s.kind==="str"&&!r.values.includes(s.value)?[`'${s.value}'`]:[]);return i.length===0?null:Lt("condition/literalOutsideSet",`'${t}' takes only ${r.values.map(s=>`'${s}'`).join(", ")} \u2014 not ${i.join(", ")}`)}o(Fq,"valueSetIssue");function iR(t,e){switch(t.kind){case"binary":e(t.left),e(t.right);return;case"unary":e(t.operand);return;case"call":t.args.forEach(e);return;case"arr":t.items.forEach(e);return;case"if":e(t.cond),e(t.then),e(t.else);return;default:return}}o(iR,"forEachChild");function oR(t){return t.kind==="binary"&&(t.op==="=="||t.op==="!=")&&(t.left.kind==="ident"&&t.right.kind==="null"||t.left.kind==="null"&&t.right.kind==="ident")}o(oR,"isNullTest");function sR(t){return Oo(t).flatMap(e=>{let n=aR(e);return n===null?[]:[n]})}o(sR,"guardsOf");function ta(t,e,n){switch(t.kind){case"ident":return nR(e,t.path)&&!n.has(t.path)?t.path:null;case"call":for(let r of t.args){let i=ta(r,e,n);if(i!==null)return i}return null;case"if":return ta(t.then,e,new Set([...n,...sR(t.cond)]))??ta(t.else,e,n);default:return null}}o(ta,"unguardedNullSource");function aR(t){return!oR(t)||t.kind!=="binary"||t.op!=="!="?null:t.left.kind==="ident"?t.left.path:t.right.kind==="ident"?t.right.path:null}o(aR,"guardedIdent");function _o(t,e,n,r){if(t.kind==="binary"&&t.op==="&&"){let i=new Set(n);for(let s of Oo(t)){_o(s,e,i,r);let a=aR(s);a!==null&&i.add(a)}return}if(t.kind==="if"){_o(t.cond,e,n,r),_o(t.then,e,new Set([...n,...sR(t.cond)]),r),_o(t.else,e,n,r);return}if(t.kind==="binary"&&t.op==="!="&&t.left.kind!=="null"&&t.right.kind!=="null"){let i=ta(t.left,e,n)??ta(t.right,e,n);i!==null&&r(i,"!=")}if(t.kind==="unary"&&!oR(t.operand)){let i=dt(t.operand).filter(s=>nR(e,s)&&!n.has(s));i.length>0&&r(i[0],"!")}iR(t,i=>_o(i,e,n,r))}o(_o,"nullableReads");function mg(t,e){$o(e);let n=[];return _o(t,e,new Set,(r,i)=>{n.some(s=>s.identifier===r)||n.push({identifier:r,op:i})}),n}o(mg,"unguardedNullableReads");function Lt(t,e){return{severity:"error",code:t,message:`[${t}] ${e}`}}o(Lt,"error");function Lq(t){let e=t.assign;if(e==null||typeof e!="object")return{};let n={};for(let[r,i]of Object.entries(e))typeof i=="string"&&i.length>0&&(n[r]=i);return n}o(Lq,"readAssignMap");function Mq(t){let e=t.tasks;return Array.isArray(e)?e:[]}o(Mq,"readComposedTemplates");function na(t){let e=new Set,n=o(i=>{typeof i=="string"&&i.length>0&&e.add(i)},"add"),r=Array.isArray(t.nodes)?t.nodes:[];for(let i of r){for(let s of Object.values(Lq(i)))n(s);for(let s of Mq(i))n(s.assign?.group),n(s.params?.revisionGroup)}return e}o(na,"declaredGroupKeys");var Rt="responsible",hg="team:";function gg(t){return`${hg}${t}`}o(gg,"teamSlot");function yg(t){return t.startsWith(hg)?t.slice(hg.length):null}o(yg,"teamKeyOfSlot");var Co=Vc;var qq="unit.key",Bq="offer.key";function lR(t,e){return t===qq?e.unitKeys:t===Bq?e.offerKeys:null}o(lR,"liveKeyUniverse");function Xc(t){return[Rt,...[...na(t)].sort((e,n)=>e.localeCompare(n)).map(gg)]}o(Xc,"requiredSlots");var Ki=`${Uc("applicant.channel")} == 'staff'`;var bg=["strict","leastLoaded"];var dR=2;function cR(t){return t.some(e=>e.length===0)?"names an empty person key":new Set(t).size!==t.length?"names a person twice":t.length<dR?`needs at least ${dR} people`:null}o(cR,"rotationPoolProblem");function Vq(t,e){let n=e===null?-1:t.indexOf(e);return[...t.slice(n+1),...t.slice(0,n+1)]}o(Vq,"strictOrder");function uR(t){let e=Vq(t.pool,t.previous).filter(i=>t.eligible.has(i));if(e.length===0)return null;if(t.mode==="strict")return e[0];let n=t.openCounts;n===void 0&&W("[assignment/rotation] leastLoaded needs the open counts");let r=o(i=>{let s=n.get(i);return s===void 0&&W(`[assignment/rotation] no open count for '${i}'`),s},"load");return e.reduce((i,s)=>r(s)<r(i)?s:i)}o(uR,"pickFromPool");function pR(t,e){let n=t?.assignmentRules;n===void 0&&W(`[assignment/noRules] ${e}: the workflow has no assignment rule`);let r=yR(n);return r.length>0&&W(`${r.join("; ")} (${e})`),n}o(pR,"rulesOfGraph");function Kq(t){return t===Rt?{slot:t,rules:[{when:Ki,assign:{kind:"creator"}},{when:null,assign:{kind:"unassigned"}}]}:{slot:t,rules:[{when:null,assign:{kind:"queue"}}]}}o(Kq,"defaultSlotRules");function mR(t,e){let n=new Set(t.map(s=>s.slot)),r=e.filter(s=>!n.has(s)).map(Kq);return[...r.filter(s=>s.slot===Rt),...t,...r.filter(s=>s.slot!==Rt)]}o(mR,"withRequiredSlots");function kt(t,e){return e===void 0?`slot '${t}'`:`slot '${t}' row #${e+1}`}o(kt,"where");function ln(t,e,n={},r="error"){return{severity:r,code:t,message:`[${t}] ${e}`,...n}}o(ln,"issue");function fR(t){if(t===Rt)return!0;let e=yg(t);return e!==null&&e.length>0}o(fR,"isKnownSlot");function Uq(t,e){$o(Co);let n=[],r=new Set;t.forEach((s,a)=>{let{slot:l}=s;fR(l)||n.push(ln("assignment/unknownSlot",`'${l}' is no slot \u2014 'responsible' or 'team:<teamKey>'`,{slot:l})),r.has(l)&&n.push(ln("assignment/duplicateSlot",`${kt(l)} is listed twice`,{slot:l})),r.add(l),l===Rt&&a!==0&&n.push(ln("assignment/responsibleFirst",`'${Rt}' must be the first slot \u2014 team rows copy it`,{slot:l})),n.push(...jq(s))});for(let s of e)r.has(s)||n.push(ln("assignment/slotMissing",`${kt(s)} has no rule list \u2014 the workflow needs it`,{slot:s}));let i=new Set(e);for(let{slot:s}of t)s!==Rt&&!i.has(s)&&fR(s)&&n.push(ln("assignment/unusedSlot",`${kt(s)} is not needed here \u2014 allowed, and not evaluated`,{slot:s},"info"));return n}o(Uq,"validateRules");function jq({slot:t,rules:e}){let n=[];return(e.length===0||e[e.length-1].when!==null)&&n.push(ln("assignment/defaultRowMissing",`${kt(t)} must end with a row without condition (\u201Esonst\u201C)`,{slot:t})),e.forEach((r,i)=>{let s={slot:t,row:i},{when:a,assign:l}=r;if(a===null&&i<e.length-1&&n.push(ln("assignment/ruleAfterDefault",`${kt(t,i)} has no condition, but rows follow it \u2014 they can never match`,s)),a!==null){let d=Zc(a,Co,[Ki]);for(let c of d)n.push({...c,message:`${c.message} (${kt(t,i)})`,...s});if(d.every(c=>c.severity!=="error")){eR(a)||n.push(ln("assignment/shadowedRule",`${kt(t,i)} reads nothing of the application \u2014 it holds for every application or for none`,s));let c=e.slice(0,i).findIndex(u=>u.when!==null&&ZE(u.when,a));c!==-1&&n.push(ln("assignment/shadowedRule",`${kt(t,i)} repeats the condition of row #${c+1} \u2014 it can never match`,s))}}if(t===Rt&&l.kind==="slot"&&n.push(ln("assignment/slotForwardRef",`${kt(t,i)} copies '${l.slot}' \u2014 only a team slot after '${Rt}' may`,s)),t===Rt&&l.kind==="queue"&&n.push(ln("assignment/queueOnProcessSlot",`${kt(t,i)} assigns the queue \u2014 the responsible slot is always a person`,s)),l.kind==="unassigned"&&n.push(ln("assignment/targetMissing",`${kt(t,i)} names no one yet \u2014 choose a person`,s)),l.kind==="rotation"){let d=cR(l.configKeys);d!==null&&n.push(ln("assignment/rotationPool",`${kt(t,i)} rotates over a pool that ${d}`,s))}l.kind==="creator"&&(a===null||!JE(a,Ki))&&n.push(ln("assignment/unguardedTarget",`${kt(t,i)} assigns the creator, which exists only when the row's condition is (or has the conjunct) '${Ki}'`,s))}),n}o(jq,"rowIssues");function hR(t,e){for(let r of e)t.some(i=>i.slot===r)||W(`[assignment/slotMissing] ${kt(r)} has no rule list`);let n=new Set(e);return t.filter(r=>n.has(r.slot))}o(hR,"selectSlots");function Gq(t,e){return XE(hR(t,e).flatMap(n=>n.rules.flatMap(r=>r.when===null?[]:[r.when])))}o(Gq,"contextKeysOfRules");function gR(t,e,n,r){$o(Co);let i=hR(t,n),s=Gq(t,n),a=Yc(Co.types,e,s);HE(Co,a,s);let l=[];for(let{slot:d,rules:c}of i){let u=c.findIndex((h,g)=>{if(h.when===null)return!0;for(let b of dt(Mn(h.when)))Object.hasOwn(a,b)||W(`[condition/unknownIdentifier] ${kt(d,g)} reads '${b}', which the context does not carry`);return qE(h.when,{values:a})});u===-1&&W(`[assignment/defaultRowMissing] ${kt(d)}: no row matched and there is no default row`);let f=c[u].assign;l.push({slot:d,ruleIndex:u,assign:f,value:Wq(d,u,f,l,r)})}return l}o(gR,"evaluateRules");function Wq(t,e,n,r,i){switch(n.kind){case"person":return{kind:"value",value:i.person(n.configKey)};case"creator":return{kind:"value",value:i.creator()};case"rotation":return{kind:"value",value:i.rotation(n,{slot:t,row:e})};case"unassigned":return W(`[assignment/targetMissing] ${kt(t,e)} names no one`);case"queue":return t===Rt&&W(`[assignment/queueOnProcessSlot] ${kt(t,e)} assigns the queue`),{kind:"queue"};case"slot":{let s=t===Rt?void 0:r.find(a=>a.slot===n.slot);return s===void 0&&W(`[assignment/slotForwardRef] ${kt(t,e)} copies '${n.slot}', which is not decided before it`),s.value}}}o(Wq,"resolveTarget");var wg={person:["kind","configKey"],creator:["kind"],slot:["kind","slot"],queue:["kind"],rotation:["kind","configKeys","mode"],unassigned:["kind"]};function yR(t){let e=[],n=o((r,i)=>e.push(`[assignment/shape] ${r}: ${i}`),"bad");return Array.isArray(t)?(t.forEach((r,i)=>{let s=`slots[${i}]`;if(typeof r!="object"||r===null)return n(s,"must be { slot, rules }");let{slot:a,rules:l,...d}=r;if(Object.keys(d).length>0&&n(s,`unknown field(s) ${Object.keys(d).join(", ")}`),typeof a!="string"&&n(s,"slot must be a string"),!Array.isArray(l))return n(s,"rules must be a list");l.forEach((c,u)=>{let f=`${s}.rules[${u}]`;if(typeof c!="object"||c===null)return n(f,"must be { when, assign }");let{when:h,assign:g,...b}=c;Object.keys(b).length>0&&n(f,`unknown field(s) ${Object.keys(b).join(", ")}`),h!==null&&typeof h!="string"&&n(f,"when must be a condition string or null (\u201Esonst\u201C)");let y=g?.kind;if(typeof g!="object"||g===null||typeof y!="string"||!Object.hasOwn(wg,y))return n(f,`assign must be one of ${Object.keys(wg).map(T=>`{kind:'${T}'}`).join(", ")}`);let w=wg[y],S=Object.keys(g);(S.some(T=>!w.includes(T))||w.some(T=>!S.includes(T)))&&n(f,`a '${y}' target has exactly the field(s) ${w.join(", ")}`);let A=g;if(y==="person"&&(typeof A.configKey!="string"||A.configKey.length===0)&&n(f,"a 'person' target needs a non-empty configKey"),y==="rotation"){let T=A.configKeys;(!Array.isArray(T)||T.some(N=>typeof N!="string"))&&n(f,"a 'rotation' target needs configKeys, a list of person keys"),bg.includes(A.mode)||n(f,`a 'rotation' target's mode is one of ${bg.map(N=>`'${N}'`).join(", ")}`)}y==="slot"&&A.slot!==Rt&&n(f,`a 'slot' target copies '${Rt}' and nothing else`)})}),e):(n("slots","must be a list of { slot, rules }"),e)}o(yR,"ruleShapeIssues");function bR(t){let e=t??{},n=[];if(e.teamOwnerBindings!==void 0&&n.push("[assignment/legacyBindings] the workflow still carries teamOwnerBindings \u2014 the assignment rule replaces them; remove the field"),e.assignmentRules===void 0)return n.push("[assignment/noRules] the workflow has no assignment rule (graph.assignmentRules) \u2014 every workflow must say who becomes responsible"),n;let r=yR(e.assignmentRules);if(r.length>0)return[...n,...r];let i=Xc({nodes:Array.isArray(e.nodes)?e.nodes:[]});for(let s of Uq(e.assignmentRules,i))s.severity==="error"&&n.push(s.message);return n}o(bR,"workflowAssignmentIssues");function wR(t,e,n={}){let r=new Map;return{slots:gR(t,e,n.slots??t.map(s=>s.slot),{person:o(s=>`person:${s}`,"person"),creator:o(()=>(n.creator===void 0&&ke("INVALID","[assignment/noCreator] Die zutreffende Zeile weist die anlegende Person zu, aber es wurde kein --creator angegeben (ein Selbststart hat keine)."),`creator:${n.creator}`),"creator"),rotation:o((s,{slot:a})=>{let l=n.rotationPrevious?.[a]??null,d=uR({pool:s.configKeys,mode:s.mode,previous:l,eligible:new Set(s.configKeys.filter(c=>!(n.left??[]).includes(c))),openCounts:new Map(s.configKeys.map(c=>[c,n.openCounts?.[c]??0]))});return d===null&&ke("INVALID",`[assignment/rotationEmpty] slot '${a}': everyone in the pool has left`),r.set(a,{pool:[...s.configKeys],mode:s.mode,previous:l,picked:d}),`person:${d}`},"rotation")}).map(s=>{let a=r.get(s.slot);return{slot:s.slot,row:s.ruleIndex+1,assign:s.assign,value:s.value.kind==="queue"?"queue":s.value.value,...a!==void 0?{rotation:a}:{}}})}}o(wR,"simulateRules");function kR(t,e){let n={};for(let r of e??[]){let i=r.lastIndexOf("=");if(i<=0||i===r.length-1)throw new Error(`assignment simulate: ${t} takes <key>=<value>, got '${r}'`);let s=r.slice(0,i);if(Object.hasOwn(n,s))throw new Error(`assignment simulate: ${t} names '${s}' twice`);n[s]=r.slice(i+1)}return n}o(kR,"parsePairs");function Hq(t){let e={};for(let[n,r]of Object.entries(kR("--open",t))){let i=Number(r);if(!Number.isInteger(i)||i<0)throw new Error(`assignment simulate: --open ${n}=${r} is no count`);e[n]=i}return e}o(Hq,"parseCounts");function Qq(t,e){if(t===void 0==(e===void 0))throw new Error("assignment simulate: pass exactly one of --env-json '<json>' or --env-file <path>");let n=t??zq(e,"utf8"),r=JSON.parse(n);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("assignment simulate: the environment must be a JSON object");return r}o(Qq,"parseEnv");var kg=class extends Re{static{o(this,"AssignmentSimulateCommand")}static paths=[["assignment","simulate"]];static usage=I.Usage({category:"Admission",description:"Evaluate an offer bundle's assignment rule over an application's environment ($env), offline",details:`
|
|
194
|
+
The environment carries every key the rule reads ($env): offer
|
|
195
|
+
{key,title}, unit {key,name} (key = the unit's configKey), stage
|
|
196
|
+
{key,name,gradeLevel|null}, run {key,name,startDate|null}, applicant
|
|
197
|
+
{language: 'de'|'en'|null (null = no applicant account), channel:
|
|
198
|
+
'self-service'|'staff'}. A missing key fails loud, exactly like a start.
|
|
199
|
+
`,examples:[["Portal application to an offer",`$0 assignment simulate --dir ~/scratch/kindergarten-r17 --env-json '{"applicant":{"language":"de","channel":"self-service"}}'`],["The next pick of a \u201EReihum\u201C row whose last start took 'finanzen'","$0 assignment simulate --dir <bundle> --env-file env.json --rotation-previous team:finanzen=finanzen"],["A leastLoaded rotation with open-task counts","$0 assignment simulate --dir <bundle> --env-file env.json --open finanzen=3 --open finanzen_2=1"]]});dir=p.String("--dir",{required:!0,description:"Offer bundle directory (its workflow.json carries the rule)"});envJson=p.String("--env-json",{description:"The application's environment ($env) as JSON"});envFile=p.String("--env-file",{description:"\u2026or a file holding it"});creator=p.String("--creator",{description:"Label for the staff creator (only a staff start has one)"});rotationPrevious=p.Array("--rotation-previous",{description:"<slot>=<personKey>: the last pick of that slot's \u201EReihum\u201C row (repeatable; none = its first start)"});left=p.Array("--left",{description:"<personKey>: someone who has left \u2014 every rotation skips them (repeatable)"});open=p.Array("--open",{description:"<personKey>=<n>: open tasks, for a leastLoaded rotation (repeatable; absent = 0)"});async execute(){let e=_e(this.dir),n=pR(e.workflow?.graph,`bundle ${this.dir}`),r=Qq(this.envJson,this.envFile),i=wR(n,r,{...this.creator!==void 0?{creator:this.creator}:{},rotationPrevious:kR("--rotation-previous",this.rotationPrevious),openCounts:Hq(this.open),left:this.left??[]});return this.print(i,s=>s.slots.map(a=>({slot:a.slot,row:`#${a.row}`,value:a.value,rotation:a.rotation===void 0?"":`${a.rotation.mode} [${a.rotation.pool.join(", ")}] after ${a.rotation.previous??"\u2014"} \u2192 ${a.rotation.picked}`}))),0}},vR=[kg];var vg=class extends V{static{o(this,"InteressentenListCommand")}static paths=[["interessenten","list"]];static usage=I.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 interessenten list"],["As JSON","plexus-cli interessenten list --json"]]});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.leads.listForManagement,{client:n});return this.print(r,i=>i.map(s=>({name:s.personDisplayName??"\u2014",angebot:s.programName===null?"\u2014":Fe(s.programName),stufe:s.stageName===null?"\u2014":Fe(s.stageName),lauf:s.runName===null?"\u2014":Fe(s.runName)})),["name","angebot","stufe","lauf"]),0}},SR=[vg];import{readFileSync as Yq}from"node:fs";import{createHash as Jq}from"node:crypto";import Sg from"node:path";var Zq={".csv":"text/csv",".mdb":"application/x-msaccess",".accdb":"application/x-msaccess",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xls":"application/vnd.ms-excel",".json":"application/json",".xml":"application/xml",".zip":"application/zip"};function Xq(t){return Zq[Sg.extname(t).toLowerCase()]??"application/octet-stream"}o(Xq,"guessContentType");async function eB(t,e,n,r){let i=Sg.resolve(r),s;try{s=Yq(i)}catch{throw new Error(`File not found: ${r}`)}let a=Sg.basename(i),l=Xq(a),{uploadUrl:d,uploadTicket:c}=await t.mutation(R.imports.generateUploadUrl,{client:e,configKey:n}),u=await t.upload(d,new Uint8Array(s),l);return await t.mutation(R.uploads.registerUpload,{uploadTicket:c,storageId:u}),{storageId:u,fileName:a,fileSize:s.length,fileContentType:l,fileSha256:Jq("sha256").update(s).digest("hex")}}o(eB,"uploadImportFile");var xg=class extends V{static{o(this,"ImportsStatusCommand")}static paths=[["imports","status"]];static usage=I.Usage({category:"Imports",description:"Show the active tenant's import controls + recent runs."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.imports.model,{client:n});return this.print({canStartManualImports:r.canStartManualImports,manualControls:r.manualControls,runs:r.runs},i=>i.manualControls.map(s=>({config:s.configKey,kind:s.sourceKind,requiresFile:s.requiresFile?"\u2713":"",canStart:s.canStart?"\u2713":"",reason:s.disabledReason??""})),["config","kind","requiresFile","canStart","reason"]),0}},Ag=class extends V{static{o(this,"ImportsTriggerCommand")}static paths=[["imports","trigger"]];static usage=I.Usage({category:"Imports",description:"Trigger a manual import for the active tenant."});configKey=p.String("--config",{required:!0,description:"configKey."});dryRun=p.Boolean("--dry-run",!1,{description:"Probelauf \u2014 writes nothing."});file=p.String("--file",{description:"Source file to upload (when required)."});limit=p.String("--limit",{description:"Cap primary rows (testing)."});confirm=p.String("--confirm",{description:"Required for a real run: the configKey/sourceKey or tenant slug."});engageUser=p.String("--engage-user",{description:"Engage username."});engagePassword=p.String("--engage-password",{description:"Engage password."});async execute(){let e=await this.caller(),n=this.requireTenant(e);if(!this.dryRun&&!this.confirm)throw this.context.stderr.write(`A real import is destructive. Re-run with --dry-run, or pass --confirm <configKey-or-tenant-slug>.
|
|
200
|
+
`),new Error("imports trigger: missing --confirm for a real run.");let r=this.file?await eB(e,n,this.configKey,this.file):{},i=this.limit===void 0?void 0:Number.parseInt(this.limit,10);if(i!==void 0&&Number.isNaN(i))throw new Error(`imports trigger: --limit must be an integer, got "${this.limit}".`);let s=this.engageUser??process.env.PLEXUS_ENGAGE_USER,a=this.engagePassword??process.env.PLEXUS_ENGAGE_PASSWORD,l=await e.mutation(R.imports.enqueueManualImport,{client:n,configKey:this.configKey,dryRun:this.dryRun,confirmation:this.dryRun?"":this.confirm??"",...i!==void 0?{limit:i}:{},...s?{engageUsername:s}:{},...a?{engagePassword:a}:{},...r});return this.print(l,d=>[{field:"jobId",value:d.jobId},{field:"runId",value:d.runId},{field:"importRunId",value:d.importRunId}]),0}},Eg=class extends V{static{o(this,"ImportsTriggerAllCommand")}static paths=[["imports","trigger-all"]];static usage=I.Usage({category:"Imports",description:"Trigger file-less imports across all accessible tenants (dry-run by default)."});executeFlag=p.Boolean("--execute",!1,{description:"Actually run (default is dry-run for safety)."});async execute(){let e=await this.caller(),n=await Dc(e),r=!this.executeFlag,i=[];for(let s of n){let a=s.slug,l=await e.query(R.imports.model,{client:a}).catch(d=>d instanceof Error?d:new Error(String(d)));if(l instanceof Error){i.push({tenant:a,config:"",dryRun:r?"\u2713":"",result:`model failed: ${l.message}`});continue}for(let d of l.manualControls){if(d.requiresFile){i.push({tenant:a,config:d.configKey,dryRun:r?"\u2713":"",result:"skipped: requires a file"});continue}try{let c=await e.mutation(R.imports.enqueueManualImport,{client:a,configKey:d.configKey,dryRun:r,confirmation:r?"":a});i.push({tenant:a,config:d.configKey,dryRun:r?"\u2713":"",result:c.runId})}catch(c){i.push({tenant:a,config:d.configKey,dryRun:r?"\u2713":"",result:`error: ${Dn(c)}`})}}}return this.print({dryRun:r,results:i},s=>s.results.map(a=>({...a})),["tenant","config","dryRun","result"]),0}},xR=[xg,Ag,Eg];function Ng(t){return t==null?"":new Date(t).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}o(Ng,"ts");function AR(t){return t==null?"":`${Math.round((Date.now()-t)/6e4)}m`}o(AR,"ago");var Rg=class extends V{static{o(this,"JobsListCommand")}static paths=[["jobs","list"]];static usage=I.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)."});async execute(){let e=await this.caller(),n=this.limit?Number(this.limit):100,r=await e.paginate(R.jobs.listPage,this.status?{status:this.status}:{},{max:n,pageSize:Math.min(n,100)}),i=this.kind?r.filter(s=>s.kind===this.kind):r;return this.print(i,s=>s.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:AR(a.updatedAt)})),["id","kind","status","tenant","phase","progress","tries","worker","updated"]),0}},Tg=class extends V{static{o(this,"JobsShowCommand")}static paths=[["jobs","show"]];static usage=I.Usage({category:"Jobs",description:"Show one job's full detail + per-attempt run timeline."});jobId=p.String({required:!0});async execute(){let n=await(await this.caller()).query(R.jobs.getDetail,{jobId:this.jobId});if(n===null)throw new Error(`Job ${this.jobId} not found.`);return this.print(n),0}},Ig=class extends V{static{o(this,"JobsLogsCommand")}static paths=[["jobs","logs"]];static usage=I.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 n=await(await this.caller()).query(R.jobs.tailLog,{jobId:this.jobId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:Ng(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},$g=class extends V{static{o(this,"JobsCancelCommand")}static paths=[["jobs","cancel"]];static usage=I.Usage({category:"Jobs",description:"Cancel a queued/running job (the worker aborts; the domain row is failed)."});jobId=p.String({required:!0});async execute(){return await(await this.caller()).mutation(R.jobs.cancel,{jobId:this.jobId}),this.print({canceled:this.jobId}),0}},_g=class extends V{static{o(this,"WorkersLogsCommand")}static paths=[["workers","logs"]];static usage=I.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 n=await(await this.caller()).query(R.workers.tailLog,{workerId:this.workerId,...this.limit?{limit:Number(this.limit)}:{}});return this.print(n,r=>r.map(i=>({at:Ng(i.at),stream:i.stream,text:i.text})),["at","stream","text"]),0}},Og=class extends V{static{o(this,"WorkersReaperStatusCommand")}static paths=[["workers","reaper-status"]];static usage=I.Usage({category:"Platform",description:"Show the last worker-reaper tick (confirm the cron is firing)."});async execute(){let n=await(await this.caller()).query(R.workers.reaperStatus,{});return n===null?(this.print({reaper:"no tick recorded yet"}),0):(this.print({...n,ranAt:Ng(n.ranAt)}),0)}},Cg=class extends V{static{o(this,"WorkersReapCommand")}static paths=[["workers","reap"]];static usage=I.Usage({category:"Platform",description:"Force a reaper pass NOW (free dead leases / fail stalled jobs)."});async execute(){let n=await(await this.caller()).mutation(R.workers.reap,{});return this.print(n),0}},Pg=class extends V{static{o(this,"ImportsCleanupOrphansCommand")}static paths=[["imports","cleanup-orphaned"]];static usage=I.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 e=await this.caller(),n=this.allTenants?void 0:this.requireTenant(e),r=await e.mutation(R.imports.failOrphanedRuns,{...n?{tenantSlug:n}:{},confirm:this.confirm});return this.print(r,i=>i.orphans.map(s=>({id:s.id,tenant:s.tenantSlug,importRunId:s.importRunId,phase:s.phase??"",updated:AR(s.updatedAt),action:i.confirmed?"failed":"would-fail"})),["id","tenant","importRunId","phase","updated","action"]),0}},ER=[Rg,Tg,Ig,$g,_g,Og,Cg,Pg];function RR(t){return t.filter(e=>e.state!=="success")}o(RR,"unfinishedPending");function Dg(t){return t.map(e=>({name:e.name,state:e.state,processed:String(e.processed),ended:e.latestEnd===null?"":new Date(e.latestEnd).toISOString(),error:e.error??""}))}o(Dg,"migrationRows");var TR=["name","state","processed","ended","error"],Fg=class extends V{static{o(this,"MigrationsStatusCommand")}static paths=[["migrations","status"]];static usage=I.Usage({category:"Platform",description:"Show the pending migrations of the deployed release (exit 1 while one is not success)",details:"Reads `migrations:getStatus` (needs `_platform.config.read`). `pending` lists PENDING_MIGRATIONS in run order; --recent adds the 20 most recently started migrations of any name."});recent=p.Boolean("--recent",!1,{description:"Also list the 20 most recently started migrations"});async execute(){let e=await this.caller(),n=await e.query(R.migrations.getStatus,{}).catch(i=>{throw i instanceof Error&&i.message.includes("Could not find public function")?new Error(`migrations status: ${e.convexUrl} has no migrations:getStatus \u2014 check --env; a local worktree backend needs \`pnpm dev\` in that worktree.`,{cause:i}):i}),r=RR(n.pending);if(this.json?this.print({...n,unfinished:r.map(i=>i.name)}):(this.context.stdout.write(n.pending.length===0?`pending: none \u2014 this release carries no migration
|
|
201
|
+
`:`pending:
|
|
202
|
+
`),n.pending.length>0&&this.print(n.pending,Dg,TR),this.recent&&(this.context.stdout.write(`
|
|
203
|
+
recent:
|
|
204
|
+
`),this.print(n.recent,Dg,TR))),r.length>0){let i=r.slice(0,5).map(a=>`${a.name} (${a.state})`).join(", "),s=r.length>5?` and ${r.length-5} more`:"";return this.context.stderr.write(`not finished: ${r.length} of ${n.pending.length} \u2014 ${i}${s}
|
|
205
|
+
`),1}return 0}},IR=[Fg];import{readFileSync as sB}from"node:fs";var ti={filename:D.string(),mimeType:D.string(),sizeBytes:D.number(),sha256:D.string()},tB=D.object({storageId:D.id("_storage"),filename:ti.filename,mimeType:ti.mimeType,sizeBytes:ti.sizeBytes,sha256:D.optional(ti.sha256)}),cse=D.object({...tB.fields,url:D.union(D.string(),D.null())});var gse=D.union(D.literal("de"),D.literal("en")),yse=D.record(D.string(),D.string()),ru=D.object({de:D.string(),en:D.string()}),bse=D.object({title:ru,body:ru,confirmLabel:ru}),wse=D.union(D.string(),ru);function _R(t){return At.includes(t)}o(_R,"isSupportedLocale");var nB=D.object({street:D.string(),hausnr:D.string(),plz:D.string(),ort:D.string(),land:D.string()}),$R=D.object({storageId:D.string(),filename:ti.filename,mimeType:ti.mimeType,sizeBytes:ti.sizeBytes,uploadedAt:D.number()}),kse=D.union(D.string(),D.number(),D.boolean(),D.null(),nB,$R,D.array(D.string()),D.array($R)),Qt=D.union(D.object({kind:D.literal("person"),id:D.string(),bucket:D.string(),role:D.optional(D.string())}),D.object({kind:D.literal("organization"),id:D.string(),orgKind:D.string(),role:D.optional(D.string())})),rB=D.object({beneficiary:Qt,custodyHolders:D.array(Qt),additionalContacts:D.optional(D.array(Qt))}),iB=D.object({beneficiary:Qt,custodyHolders:D.array(Qt),additionalContacts:D.optional(D.array(Qt)),amt:Qt}),oB=D.object({beneficiary:Qt,custodyHolders:D.array(Qt),additionalContacts:D.optional(D.array(Qt)),bevollmaechtigt:Qt}),eu=D.object({primaryList:D.string(),cohort:D.optional(D.string())}),tu=D.optional(D.array(D.object({ref:Qt,role:D.string(),signs:D.boolean()}))),nu=D.optional(D.string()),vse=D.union(D.object({outcome:D.literal("standard"),parties:rB,signers:D.array(Qt),contractParties:tu,listAssignmentHints:eu,committedAt:D.number(),committedBy:nu}),D.object({outcome:D.literal("jugendamtCase"),parties:iB,signers:D.array(Qt),contractParties:tu,listAssignmentHints:eu,committedAt:D.number(),committedBy:nu}),D.object({outcome:D.literal("vollmachtCase"),parties:oB,signers:D.array(Qt),contractParties:tu,listAssignmentHints:eu,committedAt:D.number(),committedBy:nu}),D.object({outcome:D.literal("blocked"),parties:D.object({}),signers:D.array(Qt),contractParties:tu,listAssignmentHints:eu,committedAt:D.number(),committedBy:nu})),Sse=D.record(D.string(),D.string());function iu(t){return t==null?"":new Date(t).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}o(iu,"ts");function Hg(t,e){if(t===void 0)throw new Error(`notifications ${e}: --locale is required (${At.join("|")}) \u2014 every letter exists in each language, and each is worded on its own`);if(!_R(t))throw new Error(`notifications: --locale "${t}" is not a supported locale (${At.join("|")})`);return t}o(Hg,"parseLocale");function aB(t,e){let n={},r=o((i,s,a)=>{let l=s.indexOf("=");if(l<=0)throw new Error(`notifications letters: malformed ${i} "${s}" (expected <blockKey>=<value>)`);let d=s.slice(0,l).trim();if(!d)throw new Error(`notifications letters: malformed ${i} "${s}" (empty block key)`);if(d in n)throw new Error(`notifications letters: block "${d}" given twice \u2014 one value per block.`);n[d]=a(s.slice(l+1))},"put");for(let i of t??[])r("--slot",i,s=>s);for(let i of e??[])r("--slot-file",i,s=>sB(s.trim(),"utf8"));return n}o(aB,"parseSlots");var Lg=class extends V{static{o(this,"NotificationsListCommand")}static paths=[["notifications","list"]];static usage=I.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)."});async execute(){let e=await this.caller(),n=this.limit?Number(this.limit):100,r=await e.paginate(R.notifications.listPage,{...this.status?{status:this.status}:{},...this.template?{templateId:this.template}:{},...this.to?{recipientEmail:this.to}:{},...this.since?{since:Fc(this.since)}:{}},{max:n,pageSize:Math.min(n,100)});return this.print(r,i=>i.map(s=>({id:s.id,template:s.templateId,status:s.status,tenant:s.tenantSlug??"",to:s.recipientEmail,files:s.attachmentCount>0?String(s.attachmentCount):"",tries:`${s.attempts}/${s.maxAttempts}`,error:s.errorCode??"",mode:s.transportMode??"",dup:s.possibleDuplicate?"!":"",created:iu(s.createdAt),settled:iu(s.settledAt),smtp:s.lastSmtpResponse??""})),["id","template","status","tenant","to","files","tries","error","mode","dup","created","settled","smtp"]),0}};function lB(t){if(t.letter===null)return{...t,attachments:[]};let{attachments:e,...n}=t.letter;return{...t,attachments:e.map(({filename:r,contentType:i,size:s})=>({filename:r,contentType:i,size:s})),letter:n}}o(lB,"showView");var Mg=class extends V{static{o(this,"NotificationsShowCommand")}static paths=[["notifications","show"]];static usage=I.Usage({category:"Notifications",description:"Show one delivery in full: SMTP evidence, lease, sweeper bookkeeping, template summary."});deliveryId=p.String({required:!0});async execute(){let n=await(await this.caller()).query(R.notifications.getDetail,{deliveryId:this.deliveryId});if(n===null)throw new Error(`Delivery ${this.deliveryId} not found.`);return this.print(lB(n)),0}},qg=class extends V{static{o(this,"NotificationsRetryCommand")}static paths=[["notifications","retry"]];static usage=I.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(R.notifications.retry,{deliveryId:this.deliveryId}),this.print({deliveryId:this.deliveryId,status:"queued"}),0}},Bg=class extends V{static{o(this,"NotificationsSweeperStatusCommand")}static paths=[["notifications","sweeper-status"]];static usage=I.Usage({category:"Notifications",description:"Last tick of the notification sweeper cron (deadLastHour is the number to watch)."});async execute(){let n=await(await this.caller()).query(R.notifications.sweeperStatus,{});return n===null?(this.print({ranAt:null,note:"sweeper has not run since deploy"}),0):(this.print({...n,ranAt:iu(n.ranAt),lastDeadAt:iu(n.lastDeadAt)}),0)}},Vg=class extends V{static{o(this,"NotificationsSelfTestCommand")}static paths=[["notifications","self-test"]];static usage=I.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 n=await(await this.caller()).action(R.notificationActions.selfTest,{recipient:this.to});return this.print(n),n.ok?0:1}},Kg=class extends V{static{o(this,"NotificationsLettersListCommand")}static paths=[["notifications","letters","list"]];static usage=I.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 e=await this.caller(),n=await e.query(R.notifications.letterWorkspace,{tenantSlug:this.requireTenant(e),locale:"de"});return this.print(n.letters,r=>r.map(i=>({template:i.id,label:i.label,blocks:i.slots.map(s=>s.key).join(", "),reworded:i.rewordedIn.join(", ")})),["template","label","blocks","reworded"]),0}},Ug=class extends V{static{o(this,"NotificationsLettersShowCommand")}static paths=[["notifications","letters","show"]];static usage=I.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 (${At.join("|")}) \u2014 required; each language is worded on its own`});async execute(){let e=await this.caller(),n=await e.query(R.notifications.letterWorkspace,{tenantSlug:this.requireTenant(e),locale:Hg(this.locale,"letters show")}),r=n.letters.find(i=>i.id===this.templateId);if(r===void 0)throw new Error(`notifications letters show: "${this.templateId}" is not a letter this school may reword \u2014 known: ${n.letters.map(i=>i.id).join(", ")}`);if(!this.json){let i=r.placeholders.map(s=>`{{${s.key}}}${s.required?" (Pflicht)":""}`).join(", ");this.context.stdout.write(`${r.label} \u2014 ${r.occasion.de}
|
|
206
|
+
Platzhalter: ${i||"\u2014"}
|
|
207
|
+
|
|
208
|
+
`)}return this.print(r,i=>i.slots.map(s=>{let a=i.override?.[s.key];return{block:s.key,label:s.label,deviates:a===void 0?"":"yes",text:(a??s.default).replace(/\s+/g," ").slice(0,80)}}),["block","label","deviates","text"]),0}},jg=class extends V{static{o(this,"NotificationsLettersSetCommand")}static paths=[["notifications","letters","set"]];static usage=I.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 (${At.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 e=aB(this.slot,this.slotFile);if(Object.keys(e).length===0)throw new Error("notifications letters set: nothing to write \u2014 pass --slot <blockKey>=<text> or --slot-file <blockKey>=<path>");let n=await this.caller(),r=await n.mutation(R.notifications.saveLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Hg(this.locale,"letters set"),slots:e});return this.print({templateId:this.templateId,submitted:Object.keys(e),...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}},Gg=class extends V{static{o(this,"NotificationsLettersResetCommand")}static paths=[["notifications","letters","reset"]];static usage=I.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 (${At.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 e=(this.slot??[]).map(i=>i.trim()).filter(Boolean);if(this.all&&e.length>0)throw new Error("notifications letters reset: --all resets everything \u2014 it cannot be combined with --slot.");if(!this.all&&e.length===0)throw new Error("notifications letters reset: name the blocks with --slot <blockKey>, or pass --all to reset the whole letter.");let n=await this.caller(),r=await n.mutation(R.notifications.resetLetterOverride,{tenantSlug:this.requireTenant(n),templateId:this.templateId,locale:Hg(this.locale,"letters reset"),...this.all?{}:{slotKeys:e}});return this.print({templateId:this.templateId,reset:this.all?"all":e.join(", "),...r},i=>[{key:"letter",value:i.templateId},{key:"reset",value:i.reset},{key:"still deviating",value:i.overriddenSlotKeys.join(", ")||"\u2014 (nothing)"}]),0}},ra=o((t,e)=>t==null?e:t.replace(/\s*\n\s*/g," \u23CE "),"flatCell");function ou(t,e,n){return["de","en"].map(r=>({field:`${t} (${r})`,school:e===null?"\u2014 (platform)":e[r]===""?"\u2014 (untranslated)":ra(e[r],""),...n===null?{}:{platform:ra(n[r],"")}}))}o(ou,"chromeTextRows");var Wg=class extends V{static{o(this,"NotificationsChromeShowCommand")}static paths=[["notifications","chrome","show"]];static usage=I.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 e=await this.caller(),n=await e.query(R.notifications.getTenantChrome,{tenantSlug:this.requireTenant(e)});return this.print(n,r=>[...ou("greeting",r.greeting,r.defaults.greeting),...ou("closing",r.closing,r.defaults.closing),{field:"senderName",school:ra(r.senderName,"\u2014 (platform)"),platform:ra(r.defaults.senderName,"")}],["field","school","platform"]),0}},zg=class extends V{static{o(this,"NotificationsChromeSetCommand")}static paths=[["notifications","chrome","set"]];static usage=I.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 e=o((l,d,c)=>{if(!(d===void 0&&c===void 0)){if(d===void 0||c===void 0)throw new Error(`notifications chrome set: --${l}-de and --${l}-en go together \u2014 the frame is worded in every language`);return{de:d,en:c}}},"pair"),n=e("greeting",this.greetingDe,this.greetingEn),r=e("closing",this.closingDe,this.closingEn);if(n===void 0&&r===void 0&&this.senderName===void 0)throw new Error("notifications chrome set: nothing to change \u2014 pass --greeting-de/--greeting-en, --closing-de/--closing-en or --sender-name");let i=await this.caller(),s=this.requireTenant(i);await i.mutation(R.notifications.saveTenantChrome,{tenantSlug:s,...n!==void 0?{greeting:n}:{},...r!==void 0?{closing:r}:{},...this.senderName!==void 0?{senderName:this.senderName}:{}});let a=await i.query(R.notifications.getTenantChrome,{tenantSlug:s});return this.print(a,l=>[...ou("greeting",l.greeting,null),...ou("closing",l.closing,null),{field:"senderName",school:ra(l.senderName,"\u2014 (platform)")}],["field","school"]),0}},OR=[Lg,Mg,qg,Bg,Vg,Kg,Ug,jg,Gg,Wg,zg];import{execFileSync as PR}from"node:child_process";var Qg="SmartKomm/plexus",NR="feedback",Po=["offen","todo","bearbeitung","klaerung","abgeschlossen","spaeter"],su=["bug","feature","task"],dB={bug:"d73a4a",feature:"0e8a16",task:"1d76db"};function au(t){return Math.trunc(t.number)}o(au,"issueNumber");function DR(...t){try{return PR("gh",t,{encoding:"utf8"}).trim()}catch(e){throw new Error(`gh ${t.join(" ")} failed: ${Dn(e)}`,{cause:e})}}o(DR,"gh");function Yg(t){try{return{ok:!0,stdout:PR("gh",t,{encoding:"utf8"}),stderr:""}}catch(e){let n=e;return{ok:!1,stdout:n.stdout?.toString()??"",stderr:n.stderr?.toString()??""}}}o(Yg,"ghRaw");function FR(t,e){let n=(t||"").toUpperCase()==="CLOSED"?"closed":"open",r={COMPLETED:"completed",NOT_PLANNED:"not_planned",REOPENED:"reopened"}[(e||"").toUpperCase()];return{state:n,reason:r}}o(FR,"mapGhState");async function LR(t){try{let e=await fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);return{bytes:new Uint8Array(await e.arrayBuffer()),contentType:e.headers.get("content-type")}}catch(e){throw new Error(`Could not download feedback screenshot: ${Dn(e)}`,{cause:e})}}o(LR,"downloadScreenshot");function MR(t,e,n){let{screenshotUrl:r,noScreenshot:i}=n;if(r!==void 0&&i)throw new Error("Pass either --screenshot-url or --no-screenshot, not both.");if(!e){if(r!==void 0)throw new Error(`Feedback ${t} has no screenshot \u2014 drop --screenshot-url.`);return null}if(i)return null;if(r===void 0)throw new Error(`Feedback ${t} has a screenshot. Save it with \`plexus-cli feedback screenshot ${t} --out <file>\`, upload it with your environment's upload tool as an EXPIRING (presigned) link \u2014 feedback screenshots can show customer data \u2014 and pass --screenshot-url <url>. Or file without it: --no-screenshot.`);let s;try{s=new URL(r)}catch{throw new Error(`--screenshot-url is not a URL: ${JSON.stringify(r)}`)}if(s.protocol!=="https:")throw new Error(`--screenshot-url must be https: ${JSON.stringify(r)}`);return s.href}o(MR,"screenshotForIssue");function qR(t){let e=new URL(t),n=e.hostname.split("."),r=n.indexOf("db");if(r===-1)throw new Error(`Cannot derive the app URL from convexUrl ${JSON.stringify(t)} (expected a 'db.' host label).`);return n.splice(r,1),`${e.protocol}//${n.join(".")}`}o(qR,"appBaseUrl");function BR(t,e,n){return`${t}/${e}/feedback?item=${encodeURIComponent(n)}`}o(BR,"feedbackItemUrl");function cB(t){let e=(t.name??"").trim(),n=(t.email??"").trim();return e&&n&&e!==n?`${e} (${n})`:n||e}o(cB,"reportedBy");function CR(t){return(t||"").split(`
|
|
209
|
+
`).map(e=>`> ${e}`).join(`
|
|
210
|
+
`)}o(CR,"blockquote");function VR(t,e){let n=`type:${e}`;return Yg(["label","create",n,"--repo",t,"--force","--color",dB[e]]),n}o(VR,"ensureTypeLabel");function KR(t){return`[${t.tags?.[0]?.name||"feedback"}] ${(t.summary||"").slice(0,80)}`}o(KR,"issueTitle");function UR(t,e,n){let r=["## Feedback",n,"",`Mandant **${t.tenantSlug}**`,`Gemeldet von: ${cB(t.submittedBy??{})}`,"","## Beschreibung",CR(t.summary??"")],i=[["Situation","situation"],["Ziel","goal"],["Ben\xF6tigte Information","needToSee"],["Ben\xF6tigte Aktion","needToDo"],["Grund","reason"],["Aktueller Workaround","currentWorkaround"]];for(let[s,a]of i){let l=t[a];typeof l=="string"&&l.length>0&&r.push("",`## ${s}`,CR(l))}return e&&r.push("","## Screenshot",``),r.filter(s=>s!==null).join(`
|
|
211
|
+
`)}o(UR,"issueBody");function ia(t){if(/^\d+$/.test(t))return Number.parseInt(t,10);let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`Invalid date ${JSON.stringify(t)} \u2014 use ISO (e.g. 2026-06-20) or epoch ms.`);return e}o(ia,"parseDateMs");async function lu(t,e){if(e==="@me"||e==="me")return(await t.query(R.platformFeedback.whoAmI,{})).userId;if(!e.includes("@"))return e;let r=(await t.query(R.platformFeedback.listPlatformAdmins,{})).find(i=>i.email.toLowerCase()===e.toLowerCase());if(r===void 0)throw new Error(`No platform admin with email ${JSON.stringify(e)}.`);return r.userId}o(lu,"resolveAssigneeUserId");var oa=class extends V{static{o(this,"FeedbackListCommand")}static paths=[["feedback","list"]];static usage=I.Usage({category:"Feedback",description:"List feedback (active tenant, or --all-tenants for a platform admin)."});limit=p.String("--limit",{description:"Max rows (default 50)."});fetchAll=p.Boolean("--all",!1,{description:"Fetch every page."});allTenants=p.Boolean("--all-tenants",!1,{description:"Cross-tenant platform view (requires _platform.feedback.read)."});status=p.String("--status",{description:"Filter by status (offen|todo|klaerung|abgeschlossen|spaeter)."});withIssues=p.Boolean("--with-issues",!1,{description:"Only items linked to a GitHub issue."});withoutIssues=p.Boolean("--without-issues",!1,{description:"Only items NOT yet linked to a GitHub issue."});text=p.String("--text",{description:"Filter: summary or submitter name/email contains this text."});tagIds=p.Array("--tag",{description:"Filter: item carries any of these tag ids (repeatable)."});assignee=p.String("--assignee",{description:"Filter: assignee @me, userId, or email (platform; needs --all-tenants)."});deadlineFrom=p.String("--deadline-from",{description:"Filter: deadline >= ISO/epoch (platform; needs --all-tenants)."});deadlineTo=p.String("--deadline-to",{description:"Filter: deadline <= ISO/epoch (platform; needs --all-tenants)."});async execute(){let e=await this.caller(),n=this.limit===void 0?50:Number.parseInt(this.limit,10);if(Number.isNaN(n))throw new Error(`feedback list: --limit must be an integer, got "${this.limit}".`);let r=this.fetchAll?void 0:n,i=this.assignee||this.deadlineFrom||this.deadlineTo;if(!this.allTenants){if(this.withIssues||this.withoutIssues||i)throw new Error("--with-issues/--without-issues/--assignee/--deadline-* require --all-tenants (the GitHub link, assignee and deadline are platform-admin-only).");let d=this.requireTenant(e),c=await e.paginate(R.feedback.listTenant,{client:d},{max:r});return c=this.applyTextTagFilter(c),this.print(c),0}let s=this.parseStatus(),a={};s!==void 0&&(a.status=s),this.text!==void 0&&(a.text=this.text),this.tagIds&&this.tagIds.length>0&&(a.tagIds=this.tagIds),this.assignee!==void 0&&(a.assigneeUserId=await lu(e,this.assignee)),this.deadlineFrom!==void 0&&(a.deadlineFrom=ia(this.deadlineFrom)),this.deadlineTo!==void 0&&(a.deadlineTo=ia(this.deadlineTo));let l=await e.paginate(R.platformFeedback.listAllPlatform,a,{max:r});return this.withIssues&&(l=l.filter(d=>d.githubIssue)),this.withoutIssues&&(l=l.filter(d=>!d.githubIssue)),this.print(l,d=>d.map(uB),["id","tenant","status","tags","summary","issue","resolved"]),0}applyTextTagFilter(e){let n=this.text?.trim().toLowerCase(),r=this.tagIds&&this.tagIds.length>0?new Set(this.tagIds):null;return e.filter(i=>!(n&&!`${i.summary??""} ${i.submittedBy?.name??""} ${i.submittedBy?.email??""}`.toLowerCase().includes(n)||r&&!(i.tags??[]).some(s=>r.has(s.id))))}parseStatus(){if(this.status!==void 0){if(!Po.includes(this.status))throw new Error(`feedback list: --status must be one of ${Po.join("|")}.`);return this.status}}};function uB(t){let e=t.githubIssue;return{id:t.id,tenant:t.tenantSlug,status:t.status,tags:(t.tags??[]).map(n=>n.name).join(", "),summary:(t.summary??"").slice(0,50),issue:e?`#${au(e)} (${e.state})`:"",resolved:t.resolved?"\u2713":""}}o(uB,"platformRow");var sa=class extends V{static{o(this,"FeedbackToIssueCommand")}static paths=[["feedback","to-issue"]];static usage=I.Usage({category:"Feedback",description:"Create + link a GitHub issue for a feedback item (idempotent)."});feedbackId=p.String({required:!0,name:"feedbackId"});repo=p.String("--repo",Qg,{description:`Default ${Qg}.`});issueType=p.String("--type",{description:`Triage type (${su.join("|")}) \u2014 added as a 'type:<t>' label.`});dryRun=p.Boolean("--dry-run",!1,{description:"Render the issue without creating it."});screenshotUrl=p.String("--screenshot-url",{description:"Hosted (expiring) link to the item's screenshot \u2014 required when the item has one. Save it with `feedback screenshot <id> --out <file>` first."});noScreenshot=p.Boolean("--no-screenshot",!1,{description:"File an item that has a screenshot without it."});async execute(){let e=await this.caller(),n=this.feedbackId,r=await e.query(R.platformFeedback.getById,{feedbackItemId:n}),i=r.githubIssue;if(i&&!this.dryRun)return this.print({feedbackId:this.feedbackId,issue:i.url,alreadyLinked:!0},y=>[{field:"feedbackId",value:y.feedbackId},{field:"issue",value:y.issue},{field:"alreadyLinked",value:"\u2713"}]),0;if(this.issueType!==void 0&&!su.includes(this.issueType))throw new Error(`Invalid --type ${JSON.stringify(this.issueType)} \u2014 expected one of ${su.join("|")}.`);let s=this.issueType,a=KR(r),l=BR(qR(e.convexUrl),r.tenantSlug,this.feedbackId),d=[NR,...s?[`type:${s}`]:[]],c=MR(this.feedbackId,!!r.screenshotUrl,{screenshotUrl:this.screenshotUrl,noScreenshot:this.noScreenshot}),u=UR(r,c,l);if(this.dryRun)return this.print({repo:this.repo,title:a,labels:d,hasScreenshot:!!r.screenshotUrl,screenshotUrl:c,body:u}),0;s&&VR(this.repo,s);let f=d.flatMap(y=>["--label",y]),h=DR("issue","create","--repo",this.repo,"--title",a,...f,"--body",u);if(!h.startsWith("https://github.com/"))throw new Error(`Unexpected gh output (not an issue URL): ${JSON.stringify(h)}`);let g=Number.parseInt(h.replace(/\/+$/,"").split("/").pop()??"",10);if(Number.isNaN(g))throw new Error(`Could not parse issue number from gh output: ${JSON.stringify(h)}`);let b=await e.mutation(R.platformFeedback.attachGithubIssue,{feedbackItemId:n,repo:this.repo,number:g,url:h,state:"open"});return this.print({feedbackId:this.feedbackId,issue:h,link:b},y=>[{field:"feedbackId",value:y.feedbackId},{field:"issue",value:y.issue}]),0}},aa=class extends V{static{o(this,"FeedbackSyncCommand")}static paths=[["feedback","sync"]];static usage=I.Usage({category:"Feedback",description:"Fetch GitHub issue state onto linked feedback (issue closed \u21D2 resolved)."});allTenants=p.Boolean("--all-tenants",!1);async execute(){let e=await this.caller();if(!this.allTenants)throw new Error("feedback sync requires --all-tenants (the GitHub link is platform-admin-only).");let r=(await e.paginate(R.platformFeedback.listAllPlatform,{})).filter(s=>s.githubIssue),i=[];for(let s of r){let a=s.githubIssue;if(!a)continue;let l=au(a),d=`${a.repo}#${l}`,c=Yg(["issue","view",String(l),"--repo",a.repo,"--json","state,stateReason"]);if(!c.ok){i.push({id:s.id,issue:d,state:"error",resolved:""});continue}let u;try{u=JSON.parse(c.stdout)}catch{i.push({id:s.id,issue:d,state:"error",resolved:""});continue}let{state:f,reason:h}=FR(u.state??"",u.stateReason??"");await e.mutation(R.platformFeedback.syncGithubIssueState,{feedbackItemId:s.id,state:f,...h!==void 0?{stateReason:h}:{}}),i.push({id:s.id,issue:d,state:f,resolved:f==="closed"?"\u2713":""})}return this.print(i,s=>s.map(a=>({...a})),["id","issue","state","resolved"]),0}};var la=class extends V{static{o(this,"FeedbackSetStatusCommand")}static paths=[["feedback","set-status"]];static usage=I.Usage({category:"Feedback",description:"Manually move a feedback item to a board status."});feedbackId=p.String({required:!0,name:"feedbackId"});status=p.String({required:!0,name:"status"});async execute(){let e=await this.caller();if(!Po.includes(this.status))throw new Error(`feedback set-status: status must be one of ${Po.join("|")}.`);return await e.mutation(R.platformFeedback.setFeedbackStatus,{feedbackItemId:this.feedbackId,status:this.status}),this.print({feedbackId:this.feedbackId,status:this.status},n=>[{field:"feedbackId",value:n.feedbackId},{field:"status",value:n.status}]),0}},da=class extends V{static{o(this,"FeedbackReassignCommand")}static paths=[["feedback","reassign"]];static usage=I.Usage({category:"Feedback",description:"Move a feedback item to another tenant (by target tenant slug)."});feedbackId=p.String({required:!0,name:"feedbackId"});tenantSlug=p.String({required:!0,name:"tenantSlug"});async execute(){let e=await this.caller(),n=await e.query(R.platformFeedback.listAllTenantsForAssignment,{}),r=n.find(i=>i.slug===this.tenantSlug);if(r===void 0){let i=n.map(s=>s.slug).join(", ");throw new Error(`feedback reassign: no tenant "${this.tenantSlug}". Available: ${i||"(none)"}.`)}return await e.mutation(R.platformFeedback.reassignTenant,{feedbackItemId:this.feedbackId,newTenantId:r.id}),this.print({feedbackId:this.feedbackId,tenantSlug:this.tenantSlug},i=>[{field:"feedbackId",value:i.feedbackId},{field:"tenantSlug",value:i.tenantSlug}]),0}},ca=class extends V{static{o(this,"FeedbackReplyCommand")}static paths=[["feedback","reply"]];static usage=I.Usage({category:"Feedback",description:"Post a platform reply on a feedback item (public by default; --internal for a platform-only note)."});feedbackId=p.String({required:!0,name:"feedbackId"});body=p.String({required:!0,name:"body"});internal=p.Boolean("--internal",!1,{description:"Post as an internal note (not visible to the tenant)."});async execute(){let n=await(await this.caller()).mutation(R.platformFeedback.addComment,{feedbackItemId:this.feedbackId,body:this.body,visibility:this.internal?"internal":"public"});return this.print(n,r=>[{field:"id",value:r.id},{field:"visibility",value:r.visibility},{field:"author",value:r.authorName}]),0}},ua=class extends V{static{o(this,"FeedbackCommentsCommand")}static paths=[["feedback","comments"]];static usage=I.Usage({category:"Feedback",description:"List the conversation (public replies + internal notes) on a feedback item."});feedbackId=p.String({required:!0,name:"feedbackId"});async execute(){let n=await(await this.caller()).query(R.platformFeedback.listComments,{feedbackItemId:this.feedbackId});return this.print(n,r=>r.map(i=>({id:i.id,visibility:i.visibility,author:i.authorName,body:i.body})),["id","visibility","author","body"]),0}},fa=class extends V{static{o(this,"FeedbackDeadlineCommand")}static paths=[["feedback","deadline"]];static usage=I.Usage({category:"Feedback",description:"Set or clear a feedback item's deadline (platform admin)."});feedbackId=p.String({required:!0,name:"feedbackId"});date=p.String({required:!1,name:"date"});clear=p.Boolean("--clear",!1,{description:"Clear the deadline."});async execute(){let e=await this.caller();if(!this.clear&&this.date===void 0)throw new Error("feedback deadline: pass a date (ISO/epoch) or --clear.");let n=this.clear?null:ia(this.date);return await e.mutation(R.platformFeedback.setDeadline,{feedbackItemId:this.feedbackId,deadline:n}),this.print({feedbackId:this.feedbackId,deadline:n===null?"(cleared)":new Date(n).toISOString()},r=>[{field:"feedbackId",value:r.feedbackId},{field:"deadline",value:r.deadline}]),0}},pa=class extends V{static{o(this,"FeedbackAdminsCommand")}static paths=[["feedback","admins"]];static usage=I.Usage({category:"Feedback",description:"List platform admins (valid feedback assignees)."});async execute(){let n=await(await this.caller()).query(R.platformFeedback.listPlatformAdmins,{});return this.print(n,r=>r.map(i=>({userId:i.userId,name:i.name,email:i.email})),["userId","name","email"]),0}},ma=class extends V{static{o(this,"FeedbackAssignCommand")}static paths=[["feedback","assign"]];static usage=I.Usage({category:"Feedback",description:"Assign a feedback item to a platform admin (userId or email), or --clear."});feedbackId=p.String({required:!0,name:"feedbackId"});assignee=p.String({required:!1,name:"assignee"});clear=p.Boolean("--clear",!1,{description:"Unassign."});async execute(){let e=await this.caller();if(!this.clear&&this.assignee===void 0)throw new Error("feedback assign: pass a userId/email or --clear.");let n=this.clear?null:await lu(e,this.assignee);return await e.mutation(R.platformFeedback.assign,{feedbackItemId:this.feedbackId,assigneeUserId:n}),this.print({feedbackId:this.feedbackId,assignee:n??"(cleared)"},r=>[{field:"feedbackId",value:r.feedbackId},{field:"assignee",value:r.assignee}]),0}};function du(t){return[{field:"id",value:t.id},{field:"name",value:t.name},{field:"color",value:t.color},{field:"scope",value:t.scope}]}o(du,"tagRows");function jR(t){if(t==="public"||t==="platform")return t;throw new Error(`Invalid visibility "${t}" \u2014 expected "public" or "platform".`)}o(jR,"parseTagScope");var ha=class extends V{static{o(this,"FeedbackTagsListCommand")}static paths=[["feedback","tags","list"]];static usage=I.Usage({category:"Feedback",description:"List the global feedback tag catalog (incl. platform-only tags)."});async execute(){let n=await(await this.caller()).query(R.feedbackTags.listAllTags,{});return this.print(n,r=>r.map(i=>({id:i.id,name:i.name,color:i.color,scope:i.scope})),["id","name","color","scope"]),0}},ga=class extends V{static{o(this,"FeedbackTagsCreateCommand")}static paths=[["feedback","tags","create"]];static usage=I.Usage({category:"Feedback",description:"Create a tag (platform admin). --color is a 6-hex code, e.g. d73a4a; --visibility is public (default) or platform."});name=p.String({required:!0,name:"name"});color=p.String("--color",{required:!0,description:"6-hex colour (no '#')."});visibility=p.String("--visibility",{description:"public (default) or platform (platform-admins only)."});async execute(){let n=await(await this.caller()).mutation(R.feedbackTags.createTag,{name:this.name,color:this.color,scope:this.visibility?jR(this.visibility):"public"});return this.print(n,du),0}},ya=class extends V{static{o(this,"FeedbackTagsVisibilityCommand")}static paths=[["feedback","tags","visibility"]];static usage=I.Usage({category:"Feedback",description:"Set a tag's visibility: public (everyone) or platform (platform-admins only)."});tagId=p.String({required:!0,name:"tagId"});scope=p.String({required:!0,name:"scope"});async execute(){let n=await(await this.caller()).mutation(R.feedbackTags.setTagVisibility,{tagId:this.tagId,scope:jR(this.scope)});return this.print(n,du),0}},ba=class extends V{static{o(this,"FeedbackTagsRenameCommand")}static paths=[["feedback","tags","rename"]];static usage=I.Usage({category:"Feedback",description:"Rename a tag (platform admin)."});tagId=p.String({required:!0,name:"tagId"});name=p.String({required:!0,name:"name"});async execute(){let n=await(await this.caller()).mutation(R.feedbackTags.renameTag,{tagId:this.tagId,name:this.name});return this.print(n,du),0}},wa=class extends V{static{o(this,"FeedbackTagsRecolorCommand")}static paths=[["feedback","tags","recolor"]];static usage=I.Usage({category:"Feedback",description:"Recolour a tag (platform admin). Colour is a 6-hex code."});tagId=p.String({required:!0,name:"tagId"});color=p.String({required:!0,name:"color"});async execute(){let n=await(await this.caller()).mutation(R.feedbackTags.recolorTag,{tagId:this.tagId,color:this.color});return this.print(n,du),0}},ka=class extends V{static{o(this,"FeedbackTagsDeleteCommand")}static paths=[["feedback","tags","delete"]];static usage=I.Usage({category:"Feedback",description:"Delete a tag and detach it from all items (platform admin)."});tagId=p.String({required:!0,name:"tagId"});async execute(){return await(await this.caller()).mutation(R.feedbackTags.deleteTag,{tagId:this.tagId}),this.print({tagId:this.tagId,deleted:!0},n=>[{field:"tagId",value:n.tagId},{field:"deleted",value:"\u2713"}]),0}},va=class extends V{static{o(this,"FeedbackTagAttachCommand")}static paths=[["feedback","tag"]];static usage=I.Usage({category:"Feedback",description:"Attach an existing tag to a feedback item (uses the active --tenant)."});feedbackId=p.String({required:!0,name:"feedbackId"});tagId=p.String({required:!0,name:"tagId"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.feedbackTags.attachTag,{client:n,feedbackItemId:this.feedbackId,tagId:this.tagId}),this.print({feedbackId:this.feedbackId,tagId:this.tagId,attached:!0},r=>[{field:"feedbackId",value:r.feedbackId},{field:"tagId",value:r.tagId},{field:"attached",value:"\u2713"}]),0}},Sa=class extends V{static{o(this,"FeedbackUntagCommand")}static paths=[["feedback","untag"]];static usage=I.Usage({category:"Feedback",description:"Detach a tag from a feedback item (uses the active --tenant)."});feedbackId=p.String({required:!0,name:"feedbackId"});tagId=p.String({required:!0,name:"tagId"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.feedbackTags.detachTag,{client:n,feedbackItemId:this.feedbackId,tagId:this.tagId}),this.print({feedbackId:this.feedbackId,tagId:this.tagId,detached:!0},r=>[{field:"feedbackId",value:r.feedbackId},{field:"tagId",value:r.tagId},{field:"detached",value:"\u2713"}]),0}};var xa=class extends V{static{o(this,"FeedbackLinkCommand")}static paths=[["feedback","link"]];static usage=I.Usage({category:"Feedback",description:"Link two feedback items together (platform admin)."});feedbackId=p.String({required:!0,name:"feedbackId"});otherId=p.String({required:!0,name:"otherFeedbackId"});async execute(){return await(await this.caller()).mutation(R.platformFeedback.linkItems,{feedbackItemId:this.feedbackId,otherFeedbackItemId:this.otherId}),this.print({a:this.feedbackId,b:this.otherId,linked:!0},n=>[{field:"feedbackId",value:n.a},{field:"linkedTo",value:n.b},{field:"linked",value:"\u2713"}]),0}},Aa=class extends V{static{o(this,"FeedbackUnlinkCommand")}static paths=[["feedback","unlink"]];static usage=I.Usage({category:"Feedback",description:"Remove a link between two feedback items (platform admin)."});feedbackId=p.String({required:!0,name:"feedbackId"});otherId=p.String({required:!0,name:"otherFeedbackId"});async execute(){return await(await this.caller()).mutation(R.platformFeedback.unlinkItems,{feedbackItemId:this.feedbackId,otherFeedbackItemId:this.otherId}),this.print({a:this.feedbackId,b:this.otherId,unlinked:!0},n=>[{field:"feedbackId",value:n.a},{field:"unlinkedFrom",value:n.b},{field:"unlinked",value:"\u2713"}]),0}},Ea=class extends V{static{o(this,"FeedbackLinksCommand")}static paths=[["feedback","links"]];static usage=I.Usage({category:"Feedback",description:"List the feedback items linked to a given item (platform admin)."});feedbackId=p.String({required:!0,name:"feedbackId"});async execute(){let n=await(await this.caller()).query(R.platformFeedback.listLinks,{feedbackItemId:this.feedbackId});return this.print(n,r=>r.map(i=>({id:i.id,status:i.status,tenant:i.tenantSlug,summary:i.summary})),["id","status","tenant","summary"]),0}};var Ra=class extends V{static{o(this,"FeedbackCreateCommand")}static paths=[["feedback","create"]];static usage=I.Usage({category:"Feedback",description:"File platform-level feedback (tenant-less, no screenshot). Needs _platform.feedback.read."});summary=p.String("--summary",{required:!0,description:"Short one-line summary (required)."});tag=p.Array("--tag",{description:"Catalog tag id to attach (repeatable). Platform admins may attach internal tags."});situation=p.String("--situation",{description:"What happened."});goal=p.String("--goal",{description:"What you were trying to do."});needToSee=p.String("--need-to-see",{description:"What you expected to see."});needToDo=p.String("--need-to-do",{description:"What you needed to do."});reason=p.String("--reason",{description:"Why it matters."});workaround=p.String("--workaround",{description:"Current workaround, if any."});async execute(){if(this.summary.trim().length===0)throw new Error("feedback create: --summary must not be empty.");let e=this.tag??[],r=await(await this.caller()).mutation(R.platformFeedback.createPlatformFeedback,{summary:this.summary,...e.length>0?{tagIds:e}:{},...this.situation!==void 0?{situation:this.situation}:{},...this.goal!==void 0?{goal:this.goal}:{},...this.needToSee!==void 0?{needToSee:this.needToSee}:{},...this.needToDo!==void 0?{needToDo:this.needToDo}:{},...this.reason!==void 0?{reason:this.reason}:{},...this.workaround!==void 0?{currentWorkaround:this.workaround}:{},context:{pathname:"/cli",search:"",hash:"",pageTitle:"plexus-cli feedback create",viewport:{width:0,height:0,devicePixelRatio:1},locale:"de",timezone:"UTC"}});return this.print({feedbackId:r.feedbackId,tags:e.join(", "),summary:this.summary},i=>[{field:"feedbackId",value:i.feedbackId},{field:"tags",value:i.tags},{field:"summary",value:i.summary}]),0}};import{existsSync as fB}from"node:fs";import{writeFile as pB}from"node:fs/promises";import mB from"node:path";var Ta=class extends V{static{o(this,"FeedbackScreenshotCommand")}static paths=[["feedback","screenshot"]];static usage=I.Usage({category:"Feedback",description:"Save a feedback item's screenshot to a local file.",details:"Feedback screenshots can show customer data. To put one in a GitHub issue, upload the file with your environment's upload tool as an EXPIRING (presigned) link and pass it to `feedback to-issue --screenshot-url`.",examples:[["Save a screenshot","$0 --env prod feedback screenshot <feedbackId> --out ./feedback.webp"]]});feedbackId=p.String({required:!0,name:"feedbackId"});out=p.String("--out",{required:!0,description:"File to write (refused if it exists, unless --force)."});force=p.Boolean("--force",!1,{description:"Overwrite an existing --out file."});async execute(){let e=mB.resolve(this.out);if(fB(e)&&!this.force)throw new Error(`${e} exists \u2014 pick another --out or pass --force.`);let r=await(await this.caller()).query(R.platformFeedback.getById,{feedbackItemId:this.feedbackId});if(!r.screenshotUrl)throw new Error(`Feedback ${this.feedbackId} has no screenshot.`);let{bytes:i,contentType:s}=await LR(r.screenshotUrl);return await pB(e,i),this.print({feedbackId:this.feedbackId,file:e,bytes:i.byteLength,contentType:s},a=>[{field:"feedbackId",value:a.feedbackId},{field:"file",value:a.file},{field:"bytes",value:String(a.bytes)},{field:"contentType",value:a.contentType??"(none)"}]),0}};var GR=[oa,Ra,Ta,sa,aa,la,da,ca,ua,ha,ga,ba,wa,ya,ka,va,Sa,fa,pa,ma,xa,Aa,Ea];function WR(t){return t.de??t.en??Object.values(t)[0]??""}o(WR,"titleDe");function hB(t){return{id:t._id,kind:t.kind,status:t.status,title:WR(t.title).slice(0,50),assignee:t.assigneeUserId??"",group:t.queueGroupId??"",outcome:t.outcome??""}}o(hB,"row");var gB=["id","kind","status","title","assignee","group","outcome"],Jg=class extends V{static{o(this,"WorkItemsListCommand")}static paths=[["work-items","list"]];static usage=I.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 e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.workItems.list,{client:n,...this.mine?{mine:!0}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{},...this.openOnly?{openOnly:!0}:{}});return this.print(r,i=>i.map(hB),gB),0}},Zg=class extends V{static{o(this,"WorkItemsShowCommand")}static paths=[["work-items","show"]];static usage=I.Usage({category:"Work-Items",description:"Show one work-item by id."});workItemId=p.String({required:!0,name:"workItemId"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.workItems.get,{client:n,workItemId:this.workItemId});if(r===null)throw new Error(`work-item ${this.workItemId} not found in tenant ${n}.`);return this.print(r,i=>[{field:"id",value:i._id},{field:"kind",value:i.kind},{field:"status",value:i.status},{field:"title",value:WR(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}},Xg=class extends V{static{o(this,"WorkItemsCreateCommand")}static paths=[["work-items","create"]];static usage=I.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 e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.workItems.createManual,{client:n,title:this.title,...this.description?{description:this.description}:{},...this.application?{applicationId:this.application}:{},...this.group?{queueGroupId:this.group}:{},...this.assignee?{assigneeUserId:this.assignee}:{}});return this.print({workItemId:r.workItemId},i=>[{field:"workItemId",value:i.workItemId}]),0}},ey=class extends V{static{o(this,"WorkItemsCompleteCommand")}static paths=[["work-items","complete"]];static usage=I.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 e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.workItems.complete,{client:n,workItemId:this.workItemId,...this.outcome?{outcome:this.outcome}:{}});return this.print({workItemId:r.workItemId,status:"done"},i=>[{field:"workItemId",value:i.workItemId},{field:"status",value:i.status}]),0}},ty=class extends V{static{o(this,"WorkItemsAssignCommand")}static paths=[["work-items","assign"]];static usage=I.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 e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.workItems.assign,{client:n,workItemId:this.workItemId,...this.user?{userId:this.user}:{}});return this.print({workItemId:r.workItemId,assignee:this.user??"(cleared)"},i=>[{field:"workItemId",value:i.workItemId},{field:"assignee",value:i.assignee}]),0}},zR=[Jg,Zg,Xg,ey,ty];import Qb from"node:path";var yB="-stufe-",bB=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ny(t){return`${t}${yB}`}o(ny,"stageKeyPrefix");function ry(t,e){return`${ny(t)}${e}`}o(ry,"stageStorageKey");function QR(t,e){let n=ny(t);return e.startsWith(n)&&e.length>n.length}o(QR,"isUnderProgram");function In(t,e){let n=ny(t);return QR(t,e)||ke("CONFLICT",`[stage/foreignKey] Der Stufenschl\xFCssel \u201E${e}\u201C liegt nicht unter dem Programm \u201E${t}\u201C (erwartet: \u201E${n}<key>\u201C). F\xFChren Sie die Stufe in bundle.yaml unter einem neuen Schl\xFCssel auf; der n\xE4chste Apply archiviert diese Zeile (hinter der Archivsperre) und legt die Stufe mit dem neuen Schl\xFCssel an.`),e.slice(n.length)}o(In,"bareStageKey");function cu(t){let e=[],n=new Map;return t.forEach((r,i)=>{let s=wt(r.name),a=s!=="not-localized"&&!s.includes("de")?r.name.de:void 0,l=`program.stages[${i}]${a!==void 0?` ("${a}")`:""}`;s==="not-localized"||s.length===2?e.push({code:"stage/nameMissing",index:i,message:`[stage/nameMissing] ${l}: every stage needs a \`name\` in German and English (\`{ de, en }\`)`}):s.length>0&&e.push({code:"stage/nameUntranslated",index:i,message:`[i18n/missingTranslation] ${l}.name fehlt in: ${s.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let d=r.key;if(d==null||d===""){e.push({code:"stage/keyMissing",index:i,message:`[stage/keyMissing] ${l}: every stage needs a stable \`key\` \u2014 the name is display only`});return}if(typeof d!="string"||!bB.test(d)){e.push({code:"stage/keyInvalid",index:i,message:`[stage/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`});return}let c=n.get(d);if(c!==void 0){e.push({code:"stage/duplicateKey",index:i,message:`[stage/duplicateKey] ${l}: key "${d}" is already used by program.stages[${c}]`});return}n.set(d,i)}),e}o(cu,"stageSpecIssues");function HR(t){return{de:t.de.trim(),en:t.en.trim()}}o(HR,"trimmedText");function wB(t,e){let n=[];return t.de!==e.de&&n.push(`"${t.de}" \u2192 "${e.de}"`),t.en!==e.en&&n.push(`en "${t.en}" \u2192 "${e.en}"`),n.join(", ")}o(wB,"describeNameChange");function uu(t,e,n){if(t===null)return e.length>0&&W("planStageReconcile: stages exist but the offer has no program key"),n.map((a,l)=>({op:"insert",key:a.key,name:HR(a.name),...a.gradeLevel!==void 0?{gradeLevel:a.gradeLevel}:{},sequence:l+1}));let r=new Map(e.map(a=>[a.key,a])),i=new Set,s=[];n.forEach(({name:a,...l},d)=>{let c={...l,name:HR(a)},u=ry(t,c.key);i.add(u);let f=d+1,h=r.get(u);if(h===void 0){s.push({op:"insert",key:c.key,name:c.name,...c.gradeLevel!==void 0?{gradeLevel:c.gradeLevel}:{},sequence:f});return}let g={};Jn(h.name,c.name)||(g.name=[h.name,c.name]);let b=h.gradeLevel??null,y=c.gradeLevel??null;b!==y&&(g.gradeLevel=[b,y]),h.sequence!==f&&(g.sequence=[h.sequence,f]),(Object.keys(g).length>0||h.archived)&&s.push({op:"update",key:c.key,stageId:h.stageId,name:c.name,changes:g,unarchive:h.archived})});for(let a of[...e].sort((l,d)=>l.sequence-d.sequence))a.archived||i.has(a.key)||s.push({op:"archive",key:QR(t,a.key)?In(t,a.key):a.key,stageId:a.stageId,name:a.name});return s}o(uu,"planStageReconcile");function fu(t){switch(t.op){case"insert":return`+stage ${t.key} (${t.name.de})`;case"archive":{let e=t.occupancy,n=[...e&&e.activeApplications>0?[`REFUSED: ${e.activeApplications} active application(s) \u2014 [stage/hasActiveApplications]`]:[],...e&&e.openLeads>0?[`${e.openLeads} open lead(s)`]:[]];return`-stage ${t.key} (${t.name.de})${n.length>0?` \u2014 ${n.join("; ")}`:""}`}case"update":{let e=[];if(t.unarchive&&e.push("restored"),t.changes.name&&e.push(wB(t.changes.name[0],t.changes.name[1])),t.changes.gradeLevel){let[n,r]=t.changes.gradeLevel;e.push(`grade ${n??"\u2013"} \u2192 ${r??"\u2013"}`)}return t.changes.sequence&&e.push(`position ${t.changes.sequence[0]} \u2192 ${t.changes.sequence[1]}`),`~stage ${t.key} (${e.join(", ")})`}}}o(fu,"describeStageStep");var kB=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Ir(t,e){return`${t}-${e}`}o(Ir,"runStorageKey");function No(t,e){typeof e!="string"&&ke("CONFLICT",`[run/keyNotServed] Das Deployment liefert f\xFCr ein Schuljahr von \u201E${t}\u201C keinen Schl\xFCssel \u2014 es l\xE4uft ein \xE4lteres Release als die CLI. Nach dem n\xE4chsten Release erneut versuchen.`);let n=`${t}-`;return(!e.startsWith(n)||e.length===n.length)&&ke("CONFLICT",`[run/foreignKey] Der Schl\xFCssel \u201E${e}\u201C des Schuljahrs liegt nicht unter dem Programm \u201E${t}\u201C (erwartet: \u201E${n}<key>\u201C).`),e.slice(n.length)}o(No,"bareRunKey");function pu(t){let e=[],n=new Map;return t.forEach((r,i)=>{let s=wt(r.name),a=s!=="not-localized"&&!s.includes("de")?r.name.de:void 0,l=`program.runs[${i}]${a!==void 0?` ("${a}")`:""}`;s==="not-localized"||s.length===2?e.push({code:"run/nameMissing",index:i,message:`[run/nameMissing] ${l}: every run needs a \`name\` in German and English (\`{ de, en }\`)`}):s.length>0&&e.push({code:"run/nameUntranslated",index:i,message:`[i18n/missingTranslation] ${l}.name fehlt in: ${s.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let d=r.key;if(d==null||d===""){e.push({code:"run/keyMissing",index:i,message:`[run/keyMissing] ${l}: every run needs a stable \`key\` \u2014 the name is display only`});return}if(typeof d!="string"||!kB.test(d)){e.push({code:"run/keyInvalid",index:i,message:`[run/keyInvalid] ${l}: key ${JSON.stringify(d)} must be a lowercase slug string (a-z, 0-9, single "-")`});return}let c=n.get(d);if(c!==void 0){e.push({code:"run/duplicateKey",index:i,message:`[run/duplicateKey] ${l}: key "${d}" is already used by program.runs[${c}]`});return}n.set(d,i)}),e}o(pu,"runSpecIssues");var vB={capacity:null,isOpen:!1},SB={capacity:null,isOpen:!0};function xB(t){return t===null||t==="unlimited"||typeof t=="number"&&Number.isInteger(t)&&t>=0}o(xB,"isCapacity");function mu(t,e){let n=[],r=e===void 0?void 0:new Set(e);return t.forEach((i,s)=>{if(i.capacities===void 0)return;let a=`program.runs[${s}] ("${i.key}")`;if(i.isOpen!==void 0&&n.push(`[capacity/runIsOpenWithCells] ${a}: \`isOpen\` on the run AND \`capacities\` \u2014 the open state lives on each cell; drop the run-level \`isOpen\``),i.capacities===null||typeof i.capacities!="object"||Array.isArray(i.capacities)){n.push(`[capacity/shape] ${a}: \`capacities\` must map stage keys to { isOpen, capacity }`);return}for(let[l,d]of Object.entries(i.capacities)){let c=`${a}.capacities.${l}`;r!==void 0&&!r.has(l)&&n.push(`[capacity/unknownStage] ${c}: no stage with key "${l}" in program.stages (have: ${[...r].join(", ")||"none"})`);let u=d;if(u===null||typeof u!="object"){n.push(`[capacity/shape] ${c}: expected { isOpen, capacity }`);continue}typeof u.isOpen!="boolean"&&n.push(`[capacity/isOpen] ${c}: \`isOpen\` must be true or false`),(!("capacity"in u)||!xB(u.capacity))&&n.push(`[capacity/value] ${c}: \`capacity\` must be a whole number \u2265 0, "unlimited", or null (unconfigured) \u2014 got ${JSON.stringify(u.capacity)}`)}}),n}o(mu,"capacitySpecIssues");function JR(t,e,n={stageKeys:[],runKeys:[]}){let r=t.programKey,i=new Map;if(r!==null)for(let c of t.stages)c.archived||i.set(In(r,c.key),c.stageId);let s=new Set(n.stageKeys),a=new Set(n.runKeys),l=new Map(t.runStages.map(c=>[`${c.runId}|${c.stageId}`,c])),d=[];for(let c of e){if(c.capacities===void 0)continue;let u=r===null?void 0:t.runs.find(f=>f.key===Ir(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,h]of Object.entries(c.capacities)){let g=i.get(f);if(g===void 0&&!s.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 b={capacity:h.capacity,isOpen:h.isOpen},y=u!==void 0&&g!==void 0?l.get(`${u.runId}|${g}`):void 0,w=y!==void 0?{capacity:y.capacity,isOpen:y.isOpen}:u===void 0?vB:SB;w.capacity===b.capacity&&w.isOpen===b.isOpen||d.push({run:c.key,stageKey:f,from:w,to:b})}}return d}o(JR,"planRunCapacities");function YR(t){return`${t.capacity===null?"unconfigured":String(t.capacity)}/${t.isOpen?"open":"closed"}`}o(YR,"describeCell");function hu(t){return`~cap ${t.run}\xD7${t.stageKey} ${YR(t.from)} \u2192 ${YR(t.to)}`}o(hu,"describeCapacityStep");function ZR(t){let e=new Map,n=t.programKey;if(n===null)return e;let r=new Map;for(let i of t.stages)i.archived||r.set(i.stageId,In(n,i.key));for(let i of t.runs){let s={};for(let a of t.stages){let l=r.get(a.stageId);if(l===void 0)continue;let d=t.runStages.find(c=>c.runId===i.runId&&c.stageId===a.stageId);d!==void 0&&(s[l]={isOpen:d.isOpen,capacity:d.capacity})}e.set(No(n,i.key),s)}return e}o(ZR,"exportRunCapacities");var AB=["formExports"],EB=["inputSchema","parties","schemaDigest","parts"],RB=["reads"];function Do(t){if(t===null||typeof t!="object")return t;let e={...t};return Array.isArray(e.nodes)&&(e.nodes=e.nodes.map(n=>{if(n===null||typeof n!="object")return n;let r={...n};for(let i of AB)delete r[i];for(let i of RB)Array.isArray(r[i])&&r[i].length===0&&delete r[i];if(r.resolver!==null&&typeof r.resolver=="object"){let i={...r.resolver};for(let s of EB)delete i[s];r.resolver=i}return r})),e}o(Do,"comparableWorkflowGraph");var TB={createManifest:R.workflow.createManifest,getManifestData:R.workflow.getManifestData,saveManifestDraft:R.workflow.saveManifestDraft,publishManifest:R.workflow.publishManifest,publishOfferInternal:R.workflow.publishOfferInternal,publishOfferExternal:R.workflow.publishOfferExternal,getOfferPublishState:R.workflow.getOfferPublishState,upsertCustomField:R.admission.upsertCustomField,upsertDerivedAttributeRule:R.admission.upsertDerivedAttributeRule,createSmartForm:R.forms.createSmartForm,getSmartFormBySlug:R.forms.getSmartFormBySlug,saveSmartFormDraft:R.forms.saveSmartFormDraft,publishSmartForm:R.forms.publishSmartForm,createWorkflow:R.workflow.createWorkflow,getWorkflowGraph:R.workflow.getWorkflowGraph,saveWorkflowDraft:R.workflow.saveWorkflowDraft,publishWorkflow:R.workflow.publishWorkflow},wle={createManifest:xt.workflow.createManifestInternal,getManifestData:xt.workflow.getManifestDataInternal,saveManifestDraft:xt.workflow.saveManifestDraftInternal,publishManifest:xt.workflow.publishManifestInternal,publishOfferInternal:xt.workflow.publishOfferInternalInternal,publishOfferExternal:xt.workflow.publishOfferExternalInternal,getOfferPublishState:xt.workflow.getOfferPublishStateInternal,upsertCustomField:xt.admission.upsertCustomFieldInternal,upsertDerivedAttributeRule:xt.admission.upsertDerivedAttributeRuleInternal,createSmartForm:xt.forms.createSmartFormInternal,getSmartFormBySlug:xt.forms.getSmartFormBySlugInternal,saveSmartFormDraft:xt.forms.saveSmartFormDraftInternal,publishSmartForm:xt.forms.publishSmartFormInternal,createWorkflow:xt.workflow.createWorkflowInternal,getWorkflowGraph:xt.workflow.getWorkflowGraphInternal,saveWorkflowDraft:xt.workflow.saveWorkflowDraftInternal,publishWorkflow:xt.workflow.publishWorkflowInternal};function XR(t){let e=o(n=>Array.isArray(n)?n.map(e):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,e(n[r])])):n,"sort");return JSON.stringify(e(t))}o(XR,"canonicalJson");function iy(t,e){return e==null?!0:XR(t)!==XR(e)}o(iy,"changed");async function eT(t,e,n,r={},i=TB){let{index:s}=e,a=[],l=s.tenant,d=!1,u=(await t.mutation(i.createManifest,{client:l,slug:s.slugs.manifest,label:s.label,...s.sortOrder!==void 0?{sortOrder:s.sortOrder}:{}})).offerVersionId,f=await t.query(i.getManifestData,{offerVersionId:u});if(iy(e.manifest,f?.data)?(n.dryRun||await t.mutation(i.saveManifestDraft,{offerVersionId:u,data:e.manifest}),d=!0,a.push({step:"manifest",action:n.publish?"updated+published":"created"})):a.push({step:"manifest",action:"unchanged"}),!n.dryRun&&r.afterManifestPublish){let w=await r.afterManifestPublish(u);a.push({step:"link",action:"scaffolded",...w?{detail:w}:{}})}let g=[];if(!n.dryRun){for(let w of s.customFields??[])await t.mutation(i.upsertCustomField,{client:l,key:w.key,label:w.label,data:w.data}),g.push(`field:${w.key}`);for(let w of s.derivedAttributes??[])await t.mutation(i.upsertDerivedAttributeRule,{client:l,key:w.key,type:w.type,expression:w.expression}),g.push(`derived:${w.key}`)}(s.customFields?.length??0)+(s.derivedAttributes?.length??0)>0&&a.push({step:"catalog",action:"scaffolded",detail:g.join(", ")||"(dry-run)"}),(s.contractTemplates?.length??0)>0&&ke("INVALID","Das Angebot deklariert contractTemplates[], die beim Anwenden noch nicht unterst\xFCtzt werden. Entfernen Sie diese Eintr\xE4ge.");let b={};if(e.smartforms!==void 0)for(let[w,S]of Object.entries(e.smartforms)){Ur(S.label)||ke("INVALID",`[i18n/missingTranslation] SmartForm "${w}": \`label\` muss ein zweisprachiger Text ({ de, en }) sein.`);let A=S.label,N=(await t.mutation(i.createSmartForm,{client:l,slug:w,label:A,offerVersionId:u})).smartFormDefinitionId;b[w]=N;let F=s.smartforms?.[w]?.outcomeFnRef,x=await t.query(i.getSmartFormBySlug,{client:l,offerVersionId:u,slug:w}),v=iy({definition:S,outcomeFnRef:F??null},x?.def?{definition:x.def.definition,outcomeFnRef:x.def.outcomeFnRef??null}:void 0);v&&!n.dryRun&&await t.mutation(i.saveSmartFormDraft,{smartFormDefinitionId:N,definition:S,...F?{outcomeFnRef:F}:{}}),v&&(d=!0),a.push({step:`smartform:${w}`,action:v?"created":"unchanged"})}let y;if(e.workflow!==void 0){let w=s.slugs.workflow;w||ke("INVALID","Das B\xFCndel enth\xE4lt einen Workflow, aber slugs.workflow fehlt."),y=(await t.mutation(i.createWorkflow,{client:l,slug:w,label:s.label,offerVersionId:u})).workflowDefinitionId;let A=await t.query(i.getWorkflowGraph,{workflowDefinitionId:y}),T={graph:Do(e.workflow.graph),progressWiring:e.workflow.progressWiring},N=A?{graph:Do(A.graph),progressWiring:A.progressWiring}:void 0,F=iy(T,N);F&&!n.dryRun&&await t.mutation(i.saveWorkflowDraft,{workflowDefinitionId:y,graph:e.workflow.graph,...e.workflow.progressWiring?{progressWiring:e.workflow.progressWiring}:{}}),F&&(d=!0),a.push({step:"workflow",action:F?"created":"unchanged"})}if(n.publish){let w=n.publishStage??"external",S=await t.query(i.getOfferPublishState,{client:l,offerKey:s.slugs.manifest});S===null&&ke("NOT_FOUND",`Der Mandant \u201E${l}\u201C hat keine Angebotsfamilie \u201E${s.slugs.manifest}\u201C zum Ver\xF6ffentlichen. Pr\xFCfen Sie den Mandanten und den Manifest-Slug.`);let A=w==="internal"?S.draftDiffersFromInternal:S.draftDiffersFromExternal,T=n.dryRun&&d||A;if(T&&!n.dryRun){let N=w==="external"&&S.internalCandidateMatchesDraft;if(!N){for(let F of Object.values(b))await t.mutation(i.publishSmartForm,{smartFormDefinitionId:F});y!==void 0&&await t.mutation(i.publishWorkflow,{workflowDefinitionId:y})}if(r.beforeOfferPublish){let F=await r.beforeOfferPublish(u,y);a.push({step:"pre-publish",action:"scaffolded",...F?{detail:F}:{}})}w==="internal"?await t.mutation(i.publishOfferInternal,{offerVersionId:u}):N?await t.mutation(i.publishOfferExternal,{offerVersionId:u}):await t.mutation(i.publishManifest,{offerVersionId:u}),a.push({step:w==="internal"?"offer:internal":"offer",action:"published",...N?{detail:"promoted the tested candidate"}:{}})}else a.push({step:w==="internal"?"offer:internal":"offer",action:T?"published":"already-live"})}return{steps:a,offerVersionId:u,...y!==void 0?{workflowDefinitionId:y}:{},...Object.keys(b).length>0?{smartFormDefIds:b}:{}}}o(eT,"applyOfferSteps");function IB(t){let e=t?.nodes??[],n=[],r=new Set;for(let i of e){if(i.type!=="form")continue;let a=i.inputs?.smartForm,l=a?.kind==="literal"?a.value:void 0;typeof l=="string"&&l&&!r.has(l)&&(r.add(l),n.push(l))}return n}o(IB,"collectFormNodeSmartformSlugs");function oy(t){if(t.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")}o(oy,"assertBackendHasStageKeys");async function sy(t,e,n,r){let i=await t.query(R.programAdmin.getAngebotConfig,{client:e,offerKey:n,includeArchived:!0}),s=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}));oy(i);let a=uu(i.programKey,s,r),l=a.flatMap(u=>u.op==="archive"?[u.stageId]:[]);if(l.length===0)return a;let d=await t.query(R.programAdmin.getStageOccupancy,{client:e,offerKey:n,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}}})}o(sy,"planStages");async function gu(t,e,n,r){let i=r.program?.runs??[];if(!i.some(c=>c.capacities!==void 0))return[];let s=n===null?{programKey:null,stages:[],runs:[],runStages:[]}:await t.query(R.programAdmin.getAngebotConfig,{client:e,offerKey:n});oy(s);let a=new Set(s.programKey===null?[]:s.stages.map(c=>In(s.programKey,c.key))),l=r.program?.stages?.map(c=>c.key)??[],d=s.programKey;return JR(s,i,{stageKeys:l.filter(c=>!a.has(c)),runKeys:i.map(c=>c.key).filter(c=>d===null||!s.runs.some(u=>u.key===Ir(d,c)))})}o(gu,"planCapacities");async function $B(t,e,n,r){let i=(r.program?.runs??[]).map(d=>d.key);if(i.length===0)return;let s=await t.query(R.programAdmin.getAngebotConfig,{client:e,offerKey:n,includeArchived:!0}),a=s.programKey;if(a===null)return;let l=i.filter(d=>s.runs.some(c=>c.key===Ir(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`)}o($B,"assertNoArchivedRunKey");var Ia={name:"admission",smartformSlugsFromWorkflow:IB,async scaffold(t,e,n,r){let i=n.tenant,s=n.program?.stages,a=[...cu(s??[]),...pu(n.program?.runs??[])];if(a.length>0)throw new Error(`offer[admission]: ${a.map(y=>y.message).join("; ")}`);let l=mu(n.program?.runs??[],s?.map(y=>y.key));if(l.length>0)throw new Error(`offer[admission]: ${l.join("; ")}`);await $B(t,i,e,n);let d=await gu(t,i,e,n),c=await t.query(R.programAdmin.getAngebotConfig,{client:i,offerKey:e}),u=_B(n);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(y=>y.key===u);if(!f)throw new Error(`offer[admission]: unit "${u}" not found in tenant "${i}". Available keys: ${c.units.flatMap(y=>y.key===null?[]:[y.key]).join(", ")||"(none)"}`);let h=[];if(r.dryRun||(await t.mutation(R.programAdmin.linkManifestPedagogyUnit,{client:i,offerKey:e,unitId:f.unitId}),await t.mutation(R.programAdmin.createProgramForAngebot,{client:i,offerKey:e,unitId:f.unitId})),h.push(`unit=${u}`),s!==void 0)if(r.dryRun){let y=await sy(t,i,e,s);h.push(...y.map(fu))}else{let y=await t.mutation(R.programAdmin.reconcileProgramStages,{client:i,offerKey:e,stages:s.map(w=>({key:w.key,name:w.name,...w.gradeLevel!==void 0?{gradeLevel:w.gradeLevel}:{}}))});h.push(...y.steps,...y.warnings.map(w=>`warning ${w}`))}let g=r.dryRun?c:await t.query(R.programAdmin.getAngebotConfig,{client:i,offerKey:e});for(let y of n.program?.runs??[]){let w=g.programKey===null?void 0:g.runs.find(S=>S.key===Ir(g.programKey,y.key));if(w!==void 0){Jn(w.name,y.name)||(r.dryRun||await t.mutation(R.programAdmin.updateProgramRun,{client:i,offerKey:e,runId:w.runId,name:y.name}),h.push(`~run ${y.key} ("${Fe(w.name)}" \u2192 "${Fe(y.name)}")`));continue}r.dryRun||await t.mutation(R.programAdmin.addProgramRun,{client:i,offerKey:e,key:y.key,name:y.name,isOpen:y.capacities!==void 0?!1:y.isOpen??!0,...y.startDate?{startDate:y.startDate}:{},...y.endDate?{endDate:y.endDate}:{}}),h.push(`+run ${y.key} (${Fe(y.name)})`)}let b=r.dryRun?d:await gu(t,i,e,n);if(!r.dryRun&&b.length>0){let y=await t.query(R.programAdmin.getAngebotConfig,{client:i,offerKey:e}),w=y.programKey;if(w===null)throw new Error("offer[admission]: capacities need a program \u2014 none was linked");for(let S of b){let A=y.runs.find(N=>N.key===Ir(w,S.run))?.runId,T=y.stages.find(N=>In(w,N.key)===S.stageKey)?.stageId;if(A===void 0||T===void 0)throw new Error(`offer[admission]: cell ${S.run}\xD7${S.stageKey} vanished between plan and write`);await t.mutation(R.programAdmin.setRunStageCapacity,{client:i,offerKey:e,runId:A,stageId:T,capacity:S.to.capacity,isOpen:S.to.isOpen})}}return h.push(...b.map(hu)),h.join(", ")},async exportExtras(t,e,n){let r=n,i=await t.query(R.workflow.getManifestById,{client:e,offerKey:r}),s=await t.query(R.programAdmin.getAngebotConfig,{client:e,offerKey:r}),a=i?.pedagogy?.unitId,l;if(a!==void 0){let f=s.units.find(h=>h.unitId===a);if(f===void 0||f.key===null)throw new Error(`offer[admission]: the offer's pedagogy unit (${a}) has no config key \u2014 bring the unit under config-as-code (\`plexus-cli config apply\`) before exporting`);l=f.key}oy(s);let d=s.programKey,c=d===null?void 0:s.stages.map(f=>({key:In(d,f.key),name:f.name,...f.gradeLevel!==void 0?{gradeLevel:f.gradeLevel}:{}})),u=ZR(s);return{...l!==void 0?{unitKey:l}:{},spec:{...l!==void 0?{unitKey:l}:{},...c!==void 0?{stages:c}:{},runs:d===null?[]:s.runs.map(f=>{let h=No(d,f.key);return{key:h,name:f.name,...f.startDate?{startDate:f.startDate}:{},...f.endDate?{endDate:f.endDate}:{},capacities:u.get(h)??{}}})}}}};function _B(t){let e=t.program?.unitKey,n=t.links?.unitKey;if(e!==void 0&&n!==void 0&&e!==n)throw new Error(`offer[admission]: bundle.yaml names two units \u2014 program.unitKey "${e}" and links.unitKey "${n}"; keep one`);return e??n}o(_B,"bundleUnitKey");function ni(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.itemKey=="string"&&e.itemKey.length>0&&Array.isArray(e.grantKeys)&&e.grantKeys.every(n=>typeof n=="string"&&n.length>0)&&(e.reduction===void 0||Bi(e.reduction)===null&&e.reduction.kind==="amount")}o(ni,"isPricedItemValue");var Fo=["freetext","recommendation","choice","pricedItem","record","reduction"],yu=[...Fo,"appointment"];function nT(t){return typeof t=="string"&&yu.includes(t)}o(nT,"isTaskResultKind");function ri(t){return typeof t=="string"&&Fo.includes(t)}o(ri,"isRecordedTaskResultKind");function Lo(t){return ri(t.kind)}o(Lo,"isRecordedTaskResult");var ay=["number","boolean","enum"];function ly(t){return typeof t=="string"&&ay.includes(t)}o(ly,"isRecordFieldType");var rT=["form","siblingRank"];var $r={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(t){return(t.kind==="freetext"||t.kind==="recommendation"||t.kind==="choice")&&t.writes===void 0}o(Ui,"isProseResult");function bu(t){return t.kind==="record"?(t.fields??[]).filter(e=>typeof e.writes=="string"&&e.writes.length>0&&ly(e.type)).map(e=>({key:e.writes,valueType:e.type,field:e})):OB(t)}o(bu,"draftResultStoreWrites");function OB(t){let e=$r[t.kind].valueType;return t.writes===void 0||e===null?[]:[{key:t.writes,valueType:e}]}o(OB,"singleStoreWrite");var tT="team:";function wu(t){if(t==="all")return{kind:"all"};if(t==="external"||t.length===0)return null;if(t.startsWith(tT)){let e=t.slice(tT.length);return e.length===0?null:{kind:"team",groupKey:e}}return{kind:"channel",channelKey:t}}o(wu,"parseTaskResultChat");var qe={unknownKind:"[taskResult/unknownKind]",onApproval:"[taskResult/onApproval]",unknownField:"[taskResult/unknownField]",needsTeam:"[taskResult/needsTeam]",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]",filesOnKind:"[taskResult/filesOnKind]",labelMissing:"[taskResult/labelMissing]",appointmentInvalidDuration:"[taskResult/appointmentInvalidDuration]",recordFields:"[taskResult/recordFields]",fieldsOnNonRecord:"[taskResult/fieldsOnNonRecord]",recordSuggest:"[taskResult/recordSuggest]",reductionPrices:"[taskResult/reductionPrices]",pricesOnNonReduction:"[taskResult/pricesOnNonReduction]"};function ku(t){let e=t.pricingRules;return e===void 0?[]:(Array.isArray(e)||W("graph.pricingRules must be an array \u2014 the graph validator refuses anything else"),e)}o(ku,"pricingRuleSets");function dy(t){return t.derive!==void 0}o(dy,"isDerivedKey");function CB(t,e){let n=ku(t);return(e.rules??[]).map(r=>{let i=n.find(s=>s.key===r);return i===void 0&&W(`[process] derivation names the unknown rule set "${r}" \u2014 publish refuses that`),i})}o(CB,"ruleSetsOfDerivation");function oT(t){return[...new Set(t.rows.flatMap(e=>dt(Mn(e.when))))]}o(oT,"ruleSetDependencies");function sT(t){let e=xr(t);return e!==null&&fe(e)===t?e:null}o(sT,"ruleIdentifierAddress");function cy(t,e){let r=[...new Set(CB(t,e).flatMap(oT))].map(s=>{let a=sT(s);return a===null&&W(`[address/bareIdentifier] rule identifier "${s}" is no address \u2014 publish refuses that`),{address:a,id:s,role:"rule"}}),i=e.reduction;return i===void 0?r:(Se(i)||W(`[address/bareIdentifier] derive.reduction ${JSON.stringify(i)} is no address \u2014 publish refuses that`),[...r,{address:i,id:fe(i),role:"reduction"}])}o(cy,"derivationSources");function aT(t,e){let n=ku(t);for(let r of e.rules??[]){let i=n.find(s=>s.key===r);if(i===void 0||i.rows.some(s=>$a(s.when)!==null)||oT(i).some(s=>sT(s)===null))return null}return e.reduction!==void 0&&!Se(e.reduction)?null:cy(t,e)}o(aT,"draftDerivationSources");function $a(t){if(typeof t!="string"||t.trim().length===0)return"leere Bedingung";try{return Mn(t),null}catch(e){return e instanceof Error?e.message:String(e)}}o($a,"conditionIssue");function iT(t){return t.item!==void 0&&t.group===void 0?{kind:"item",key:t.item}:t.group!==void 0&&t.item===void 0?{kind:"group",key:t.group}:null}o(iT,"rowTarget");function uy(t){if(t.byStage===void 0){let e=iT(t);return e===null?[]:[{...e,stages:null}]}return t.item!==void 0||t.group!==void 0?[]:t.byStage.flatMap(e=>{let n=iT(e);return n===null?[]:[{...n,stages:e.stages}]})}o(uy,"derivationTargets");var fy=null;function lT(t){fy=t}o(lT,"setSpecs");function dT(){return fy||W("[workflow/registry] Specs not initialised. Import convex/model/admission/registry before calling specFor()."),fy}o(dT,"requireSpecs");function je(t){let e=dT(),n=e[t.type];return n===void 0&&ke("INVALID",`[workflow/registry] Unbekannter Knotentyp "${String(t.type)}" (Knoten "${String(t.id)}"). Registrierte Typen: ${Object.keys(e).sort().join(", ")}.`),n}o(je,"specFor");function cT(){return Object.keys(dT()).sort()}o(cT,"registeredNodeTypes");var uT=Kc.filter(t=>Er[t].cohortBound!==!0);function py(t){return Ln(t)&&Er[t].cohortBound!==!0}o(py,"isEnvAddressLeaf");function my(t){return Mi(t).type}o(my,"envType");function hy(t){return Mi(t).label}o(hy,"envLabel");function vu(t){if(t.scope==="env"||t.path===void 0)return t;switch(t.scope){case"node":return{scope:"node",owner:t.owner,key:t.key};case"task":return{scope:"task",owner:t.owner,key:t.key};case"derived":return{scope:"derived",key:t.key}}}o(vu,"addressBase");function Pa(t){return t.scope==="node"&&t.key===$n&&t.path===void 0}o(Pa,"isInstanceAddress");function Xe(t){return Se(t)&&t.scope==="node"&&t.key===$n&&t.path!==void 0}o(Xe,"isFormFieldAddress");function fT(t){return Xe(t)?{owner:t.owner,path:t.path}:null}o(fT,"formFieldOf");function gy(t){return dt(Mn(t)).map(e=>{if(!e.startsWith("$"))return{identifier:e,address:null,reason:"bareIdentifier"};let n=xr(e);return n===null?{identifier:e,address:null,reason:"shape"}:{identifier:e,address:n}})}o(gy,"expressionAddresses");var $n="admission",Na="document",Mo="contract",Su="contracts",pT="payment",yy=new Set(["adoptForm","setFlagTarget","form","familyRequestFrom"]);function ar(t){return Array.isArray(t)?t:[]}o(ar,"listOf");function Mt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}o(Mt,"record");function mT(t){switch(t.type){case"countersign":return["contract"];case"engagePush":return["form","contract","payment"];case"governedDocument":return t.production==="resolver"?["form"]:[];default:return[]}}o(mT,"dataSourceFieldsOf");function hT(t){return t.type==="engagePush"?["form"]:mT(t)}o(hT,"requiredDataSourceFields");function Da(t,e={}){let n=[],r=t,i=`nodes.${t.id}`,s=o((l,d,c,u={})=>{n.push({kind:l,at:d,nodeId:t.id,value:c,judgedTogether:null,...u})},"field"),a=new Map(e.slotTypes===!1?[]:(je(t).inputs?.(t)??[]).map(l=>[l.id,l.type]));for(let[l,d]of Object.entries(Mt(r.inputs)??{})){let c=Mt(d);if(c?.kind!=="binding")continue;let u=a.get(l);s("binding",`${i}.inputs.${l}`,"address"in c?c.address:c.path,u!==void 0?{expectedType:u}:{})}for(let[l,d]of ar(r.reads).entries())s("nodeReads",`${i}.reads.${l}`,d,{judgedTogether:`${i}.reads`});for(let[l,d]of ar(r.requires).entries())s("requires",`${i}.requires.${l}`,d,{judgedTogether:`${i}.requires`});t.type==="form"&&r.adoptForm!==void 0&&s("adoptForm",`${i}.adoptForm`,r.adoptForm),t.type==="setFlag"&&r.target!==void 0&&s("setFlagTarget",`${i}.target`,r.target);for(let l of mT(t))r[l]!==void 0&&s(l,`${i}.${l}`,r[l]);t.type==="if"&&r.condition!==void 0&&s("condition",`${i}.condition`,r.condition);for(let[l,d]of ar(r.tasks).entries())n.push(...gT(t.id,d,l));return n}o(Da,"nodeAddressFields");function gT(t,e,n){let r=Mt(e);if(r===null)return[];let i=[],s=typeof r.key=="string"?r.key:String(n),a=`nodes.${t}.tasks.${s}`,l=o((f,h,g,b={})=>{i.push({kind:f,at:h,nodeId:t,taskKey:s,value:g,judgedTogether:null,...b})},"field"),d=`${a}.evidence`;r.when!==void 0&&l("taskWhen",`${a}.when`,r.when,{expectedType:"boolean",judgedTogether:d});for(let[f,h]of ar(r.reads).entries())l("taskReads",`${a}.reads.${f}`,h,{judgedTogether:d});for(let[f,h]of ar(r.documents).entries()){let g=Mt(h);g===null||g.kind==="artifact"||l("taskDocument",`${a}.documents.${f}`,"address"in g?g.address:g.key)}let c=Mt(r.familyRequest);if(c!==null){for(let[f,h]of ar(c.fields).entries())l("familyRequestFields",`${a}.familyRequest.fields.${f}`,h,{judgedTogether:`${a}.familyRequest.fields`});c.from!==void 0&&l("familyRequestFrom",`${a}.familyRequest.from`,c.from)}let u=Mt(r.result);if(u?.kind==="record")for(let[f,h]of ar(u.fields).entries()){let g=Mt(Mt(h)?.suggest);if(g?.kind!=="form")continue;let b=Mt(h)?.type;l("suggest",`${a}.result.fields.${f}.suggest`,"address"in g?g.address:g.key,typeof b=="string"?{expectedType:b}:{})}return i}o(gT,"taskAddressFields");function xu(t){let e=[];for(let[n,r]of ar(t.processStore).entries()){let i=Mt(Mt(r)?.derive);if(i?.reduction!==void 0){let s=String(Mt(r)?.key);e.push({kind:"reduction",at:`processStore.${n}.derive.reduction`,nodeId:null,priceKey:s,value:i.reduction,judgedTogether:null})}}for(let[n,r]of ar(t.pricingRules).entries())for(let[i,s]of ar(Mt(r)?.rows).entries())e.push({kind:"pricingRule",at:`pricingRules.${n}.rows.${i}.when`,nodeId:null,value:Mt(s)?.when,judgedTogether:null});return e}o(xu,"priceAddressFields");function qo(t){return by(t)?(Au(t.value)??[]).flatMap(e=>e.address===null?[]:[e.address]):Se(t.value)?[t.value]:[]}o(qo,"addressesInField");function by(t){return t.kind==="pricingRule"||t.kind==="condition"}o(by,"isExpressionField");function Au(t){return $a(t)===null?gy(t):null}o(Au,"ruleConditionAddresses");function ii(t){return t.type==="form"&&t.adoptForm!==void 0&&t.adoptForm!==!1}o(ii,"adoptsForm");function PB(t,e){return t.type!=="governedDocument"||t.production!=="resolver"||e!==Na?e:t.resolver?.parts!==void 0?Su:Mo}o(PB,"addressKeyOfPort");function wy(t){let e=t.result;return e===void 0||!Lo(e)?[]:bu(e).map(n=>n.key)}o(wy,"storeWritesOf");function Oa(t,e){return(Array.isArray(t.processStore)?t.processStore:[]).find(n=>n.key===e)}o(Oa,"declaredKey");function lr(t,e){let n=[];if(!ii(e))for(let r of je(e).outputs?.(e)??[])n.push({address:{scope:"node",owner:e.id,key:PB(e,r.name)},type:r.type,...r.label!==void 0?{label:r.label}:{},nodeId:e.id,nodePort:r});for(let r of Array.isArray(e.tasks)?e.tasks:[])for(let i of wy(r)){let s=Oa(t,i);n.push({address:{scope:"task",owner:r.key,key:i},type:s?.type??"unknown",...s!==void 0?{label:s.label}:{},nodeId:e.id})}return n}o(lr,"producedAddresses");function yT(t,e,n){for(let r of t.nodes)for(let i of Array.isArray(r.tasks)?r.tasks:[])if(i.key===e&&wy(i).includes(n))return{nodeId:r.id,template:i};return null}o(yT,"taskWriter");function dr(t,e,n){return yT(t,e,n)?.nodeId??null}o(dr,"taskOwnerNode");function Ca(t,e){let n=Oa(t,e)?.derive;if(n===void 0)return null;let r=Array.isArray(t.pricingRules)?t.pricingRules:[],i=[];for(let a of n.rules??[]){let l=r.find(d=>d.key===a);if(l===void 0)return null;for(let d of l.rows){let c=Au(d.when);if(c===null)return null;for(let u of c)u.address!==null&&i.push(u.address)}}let s=n.reduction;return Se(s)&&i.push(s),NB(i)}o(Ca,"derivedSources");function NB(t){let e=new Set;return t.filter(n=>{let r=fe(n);return e.has(r)?!1:(e.add(r),!0)})}o(NB,"dedupe");function DB(t){return Da(t,{slotTypes:!1}).flatMap(e=>qo(e).map(n=>({address:n,field:e})))}o(DB,"writtenAddressesOf");function ji(t,e){let n=[],r=new Set,i=o((l,d,c,u)=>{let f=`${fe(l)}|${d}|${c.at}|${u===void 0?"":fe(u)}`;r.has(f)||(r.add(f),n.push({address:l,origin:d,field:c,...u!==void 0?{via:u}:{}}))},"push"),s=o((l,d,c=new Set)=>{let u=fe(l);if(!c.has(u)){if(c.add(u),l.scope==="task"){let f=yT(t,l.owner,l.key);if(f===null)return;for(let h of gT(f.nodeId,f.template))if(!(h.kind!=="taskWhen"&&h.kind!=="taskReads"))for(let g of qo(h))i(g,"evidence",d,l)}if(l.scope==="derived")for(let f of Ca(t,l.key)??[])i(f,"derivedSource",d,l),s(f,d,c)}},"carried");for(let{address:l,field:d}of DB(e))i(l,"written",d),s(l,d);let a=new Set((Array.isArray(e.tasks)?e.tasks:[]).flatMap(l=>wy(l).map(d=>`${l.key}.${d}`)));for(let l of xu(t))if(!(l.kind!=="reduction"||!Se(l.value)||l.value.scope!=="task")&&a.has(`${l.value.owner}.${l.value.key}`))for(let d of Ca(t,l.priceKey)??[])d.scope==="task"&&a.has(`${d.owner}.${d.key}`)||(i(d,"priceCheck",l,{scope:"derived",key:l.priceKey}),s(d,l));return n}o(ji,"addressReadsOf");function ky(t,e){switch(e.scope){case"env":return Ln(e.key)?my(e.key):Js(t,e.key)?.type;case"derived":case"task":{if(e.path!==void 0||e.scope==="task"&&dr(t,e.owner,e.key)===null)return;let n=Oa(t,e.key);return n===void 0||e.scope==="derived"!=(n.derive!==void 0)?void 0:n.type}case"node":{let n=t.nodes.find(i=>i.id===e.owner);if(n===void 0)return;let r=lr(t,n).find(i=>i.address.scope==="node"&&i.address.key===e.key);return r===void 0?void 0:e.path===void 0?r.type:r.nodePort?.schema?.find(i=>i.key===e.path)?.type}}}o(ky,"addressType");function _a(t,e){let n=Mt(t)?.[e];return typeof n=="string"&&n.length>0?n:void 0}o(_a,"labelText");function We(t,e,n){let r=t.nodes.find(i=>i.id===e);return _a(r?.label,n)??e}o(We,"nodeDisplayName");function Gi(t,e,n){for(let r of t.nodes){let i=(Array.isArray(r.tasks)?r.tasks:[]).find(s=>s.key===e);if(i!==void 0)return _a(i.title,n)??e}return e}o(Gi,"taskDisplayName");function nt(t,e,n){let r=[];switch(e.scope){case"env":r.push(Ln(e.key)?hy(e.key)[n]:Js(t,e.key)?.label[n]??e.key);break;case"derived":r.push(_a(Oa(t,e.key)?.label,n)??e.key);break;case"task":r.push(Gi(t,e.owner,n),_a(Oa(t,e.key)?.label,n)??e.key);break;case"node":{r.push(We(t,e.owner,n));let i=t.nodes.find(a=>a.id===e.owner),s=i===void 0?void 0:lr(t,i).find(a=>a.address.scope==="node"&&a.address.key===e.key);r.push(_a(s?.label,n)??e.key);break}}return e.scope!=="env"&&e.path!==void 0&&r.push(e.path),`${r.join(" \u203A ")} (${fe(e)})`}o(nt,"displayAddress");var Fa=["beneficiary","signers"];function bT(t,e){return Array.isArray(t.artifacts)&&t.artifacts.some(n=>n?.key===e)}o(bT,"ownsSlot");function Eu(t){let e=[];for(let[n,r]of Object.entries(Mt(t.inputs)??{})){let i=Mt(r);i?.kind==="binding"&&Se(i.address)&&e.push({slot:n,address:i.address})}return e}o(Eu,"bindingAddresses");var FB="addresses";function vy(t){t.dataFlow!==FB&&ke("CONFLICT",`Das ist im Moment nicht m\xF6glich, weil dieses Angebot gerade umgestellt wird. Bereits gemachte Eingaben bleiben gespeichert; bitte versuchen Sie es sp\xE4ter noch einmal. [graph/preAddresses] Workflow \u201E${String(t.id)}" liest noch nicht \xFCber Adressen (dataFlow: ${JSON.stringify(t.dataFlow??null)}) \u2014 Migration abwarten bzw. neu ver\xF6ffentlichen.`)}o(vy,"assertAddressGraph");function wT(t,e){let n=o(i=>i.scope==="node"&&i.owner===e||i.scope==="task"&&dr(t,i.owner,i.key)===e,"names");return[...t.nodes.filter(i=>i.id!==e).flatMap(i=>Da(i,{slotTypes:!1})),...xu(t)].flatMap(i=>qo(i).filter(n).map(s=>({at:i.at,nodeId:i.nodeId,address:s})))}o(wT,"addressesNaming");var kT={role:"control",effect:"pure",cardinality:"N-to-1"};var vT={role:"effect",effect:"pure",progressEvents:["enrolled","declined"],inputs:o(()=>[{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:o(()=>[{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")};var Sy=["add","remove","replace"];function ST(t,e){let n=t.inputs?.[e];if(!(!n||n.kind!=="literal"))return n.value!=null?String(n.value):void 0}o(ST,"roleAssignLiteral");var xT={role:"method",effect:"context-mutation",inputs:o(()=>[{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:o((t,e,n)=>{let r=[],i=ST(t,"roleKey")?.trim()??"",s=ST(t,"mode")??"add";return i===""?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.roleKey`,reason:`[roleAssign/missingRoleKey] roleAssign-Knoten "${t.id}" nennt keine Rolle \u2014 welche Rolle vergeben wird, muss der Autor aus dem Rollenkatalog des Mandanten w\xE4hlen.`,severity:"error"}):n?.roleKeys!==void 0&&!n.roleKeys.has(i)?r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.roleKey`,reason:`[roleAssign/unknownRoleKey] Rolle "${i}" existiert nicht im Rollenkatalog des Mandanten \u2014 der Knoten w\xFCrde bei jeder Ausf\xFChrung abbrechen. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`,severity:"error"}):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(i)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.roleKey`,reason:`[roleAssign/nonLeafRoleKey] Rolle "${i}" hat untergeordnete Rollen und ist deshalb nicht vergebbar \u2014 eine Partei bekommt ein Blatt, keine Oberkategorie. Vergebbare Rollen: ${[...n.assignableRoleKeys].sort().join(", ")}.`,severity:"error"}),Sy.includes(s)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.inputs.mode`,reason:`[roleAssign/unknownMode] roleAssign-Knoten "${t.id}" deklariert Modus "${s}" \u2014 erlaubt sind ${Sy.join(" | ")}.`,severity:"error"}),r},"validate")};var Ru="bewerbungOffen";function hn(t){let e=[];for(let n of t){let r=n.next;if(r)for(let[i,s]of Object.entries(r))e.push({id:`${n.id}|${i}`,source:n.id,target:s.to,sourceBranchId:i})}return e}o(hn,"derivedEdges");var AT={validate:o((t,e)=>{let n=t.outcomes??[];if(n.length===0)return[];if(!!new Set(hn(e.nodes).map(a=>a.target)).has(t.id))return[];if(n.some(a=>a.id===Ru))return[];let s=n.map(a=>a.id).join(", ");return[{layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.outcomes`,reason:`[eventTrigger/unreachableStartOutcome] Start-Knoten "${t.id}" deklariert die Outcomes [${s}], aber keinen mit der id "${Ru}". Der Start dispatcht genau diese id \u2014 jede Bewerbung w\xFCrde auf dem Start-Knoten stehen bleiben. Benenne einen Outcome in "${Ru}" um (das Label bleibt frei w\xE4hlbar) oder entferne die Outcomes ganz, damit der Trigger direkt weiterl\xE4uft.`,severity:"error"}]},"validate")};var LB="submit",ET=[{id:LB,kind:"advance",label:{de:"Absenden",en:"Submit"},availableIn:["draft"]}];function RT(t){return t==="draft"}o(RT,"isWritableSmartFormState");var xy=["draft","committed"],Ade=xy.filter(t=>RT(t));async function TT(t,e,n){let r=await t.db.query("smart_form_instances").withIndex("by_applicationId_and_formNodeId",i=>i.eq("applicationId",e).eq("formNodeId",n)).take(2);return r.length>1&&W(`application ${e}: two form instances for node "${n}" (${r[0]._id}, ${r[1]._id}) \u2014 at most one may exist`),r.length===0&&await MB(t,e),r[0]??null}o(TT,"getSmartFormInstance");async function MB(t,e){let n=await t.db.query("artifacts").withIndex("by_applicationId_workflowNodeId",r=>r.eq("applicationId",e)).filter(r=>r.eq(r.field("type"),"smartform")).collect();for(let r of n)await t.db.query("smart_form_instances").withIndex("by_legacyArtifactId",s=>s.eq("legacyArtifactId",r._id)).first()===null&&W(`application ${e}: form artifact ${r._id} (node "${r.workflowNodeId}") has no form instance yet \u2014 run migrations.copySmartFormsToInstances`)}o(MB,"assertNoUnmovedForm");var IT="form:fill",Ay="request:collectPayment";var qB={key:IT,recipient:"external",title:{de:"Bewerbung ausf\xFCllen & absenden",en:"Complete & submit application"},unlocks:["submit"],advancesNode:!0},$T={role:"user-action",effect:"side-effect",progressEvents:[lE,Mc],actions:o(()=>ET,"actions"),workItemTemplates:o(()=>[qB],"workItemTemplates"),states:xy,currentState:o(async(t,e)=>{let n=await TT(t,e.applicationId,e.node.id);return n===null?"draft":n.state},"currentState"),inputs:o(t=>[{id:"smartForm",label:{de:"Formular",en:"Form"},type:"form",required:t.adoptForm===void 0,inspector:"literal-only"}],"inputs"),outputs:o(t=>[{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"}},...t.formExports??[]]}],"outputs"),validate:o(t=>{let e=[],n=t.inputs?.smartForm,r=n?.kind==="literal"&&typeof n.value=="string"&&n.value.length>0,i=t.adoptForm!==void 0;return r&&i?e.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.adoptForm`,reason:`[form.adopt-xor-create] Form-Knoten "${t.id}" hat sowohl ein smartForm als auch adoptForm \u2014 genau eines ist erlaubt.`,severity:"error"}):!r&&!i&&e.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.smartForm`,reason:`[form.adopt-xor-create] Form-Knoten "${t.id}" braucht entweder ein smartForm (neu erzeugen) oder adoptForm (bestehende Instanz \xFCbernehmen).`,severity:"error"}),e},"validate")};var _T={role:"system-action",effect:"side-effect",notificationEvents:o(t=>[{id:"unlocked",label:{de:"Abschnitt freigeschaltet",en:"Section unlocked"},audience:"external",required:t.value!==!1,args:[{key:"applicationId",type:"string",required:!0},{key:"sectionLabel",type:"localizedText",required:!0}]}],"notificationEvents"),validate:o(t=>{let e=[];return(typeof t.flagKey!="string"||t.flagKey.length===0)&&e.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.flagKey`,reason:`[setFlag/missingFlagKey] setFlag-Knoten "${t.id}" hat keinen flagKey.`,severity:"error"}),e},"validate")};var BB="true",VB="false",Ey=[{id:BB,label:{de:"Ja",en:"Yes"}},{id:VB,label:{de:"Nein",en:"No"}}];var OT={role:"control",effect:"pure",cardinality:"1-to-N",outcomes:Ey,validate:o((t,e,n)=>KB(t,e,n),"validate")};function KB(t,e,n){let r=o(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.condition`,reason:`[if/condition] Knoten "${t.id}": ${d}`,severity:"error"}),"issue"),i=Ey.filter(d=>t.next?.[d.id]===void 0).map(d=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.next.${d.id}`,reason:`[if/unroutedOutcome] Knoten "${t.id}": Ausgang \u201E${d.label.de}\u201C (${d.id}) f\xFChrt nirgendwohin.`,severity:"error"}));if(typeof t.condition!="string"||t.condition.trim()==="")return[...i,r("Bedingung fehlt.")];let s=EE(e),a=Zc(t.condition,s).filter(d=>d.severity==="error").map(d=>r(d.message)),l=[...i,...a];if(a.length>0||n?.liveEnvKeys===void 0)return l;for(let d of pg(t.condition,s)){let c=lR(d.path,n.liveEnvKeys);c===null&&W(`[if/condition] no live-key universe for '${d.path}' \u2014 extend liveKeyUniverse`),c.has(d.value)||l.push(r(`$env.${d.path} == '${d.value}' nennt keinen Schl\xFCssel dieses Mandanten.`))}return l}o(KB,"ifNodeIssues");var UB=["documentChangeRequested","documentReturned"];function CT(t){return UB.includes(t)}o(CT,"isNonAdvancingExternalEvent");var PT="open",Bo="done";var jB="optionalAction:";function NT(t){return`${jB}${t}:trigger`}o(NT,"optionalActionTriggerActionId");var GB="processDecide";function DT(t){let e=t.optionalActions;return e==null?[]:(Array.isArray(e)||W(`[optionalAction/corrupt-section] node's 'optionalActions' is ${typeof e}, not an array \u2014 corrupt pinned graph (publish stores the section as authored)`),e)}o(DT,"optionalActionBindings");function FT(t){return DT(t).map(e=>({id:NT(e.key),kind:"internal",label:e.label,surface:GB,placement:"overflow",superUserOnly:!0}))}o(FT,"optionalActionTriggers");function LT(t){let e=new Set;for(let n of DT(t))if(n.action==="spawnTasks")for(let r of n.tasks??[])e.add(r);return e}o(LT,"referencedTaskTemplateKeys");var La="decision",WB=new Set(["decision","review"]),tce=new Set([...WB,"governedDocument"]);var MT=[{id:"approved",label:{de:"Freigeben",en:"Approve"}},{id:"rejected",label:{de:"Ablehnen",en:"Reject"}},{id:"waitlisted",label:{de:"Auf Warteliste",en:"Waitlist"}}];function qT(t){return t==="approved"||t==="accepted"||t==="admitted"||t==="direkt"?"granted":t==="rejected"||t==="absage"||t==="declined"?"rejected":t==="waitlisted"||t==="warteliste"?"waitlisted":"other"}o(qT,"outcomeSemantic");var oi={role:"user-action",effect:"side-effect",outcomes:MT,progressEvents:["released"],notificationEvents:o(t=>(t.outcomes??[]).map(e=>({id:e.id,label:e.label,audience:"external",args:[{key:"applicationId",type:"string",required:!0},{key:"comment",type:"string"}]})),"notificationEvents"),actions:o(t=>[...(t.outcomes??[]).map(e=>({id:e.id,kind:"advance",outcome:e.id,label:e.label})),...FT(t)],"actions"),optionalActionKinds:["spawnTasks"],workItemTemplates:o(t=>[{key:La,recipient:"internal",title:t.decisionAsTask?.title??{de:"Entscheidung",en:"Decision"},unlocks:(t.outcomes??[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0),gatesNode:!1,advancesNode:!0,dueInDays:t.decisionAsTask?.dueInDays}],"workItemTemplates"),taskDocuments:o((t,e)=>e===La&&Array.isArray(t.reads)?t.reads.map(n=>({kind:"field",address:n})):[],"taskDocuments"),validate:Ry};function Ry(t,e,n){let r=[],i=t.outcomes??[];i.length===0&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.outcomes`,reason:`[decision/missingOutcomes] Entscheidungs-Knoten "${t.id}" hat keine Outcomes \u2014 die Entscheidung w\xE4re niemals aufl\xF6sbar.`,severity:"error"});let s=new Set(i.map(c=>c.id));for(let c of i){let u=c.label;(typeof u=="string"?u.trim().length>0:u!=null&&typeof u=="object"&&Object.values(u).some(h=>typeof h=="string"&&h.trim().length>0))||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.outcomes.${c.id}`,reason:`[decision/outcomeMissingLabel] Outcome "${c.id}" von "${t.id}" hat keine Beschriftung \u2014 sie ist der Text des Knopfs im Cockpit.`,severity:"error"})}for(let c of Object.keys(t.commentRequired??{}))s.has(c)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.commentRequired.${c}`,reason:`[decision/commentRequiredUnknownOutcome] Unbekanntes Outcome "${c}" in commentRequired; erlaubt: ${[...s].join(", ")}`,severity:"error"});let a=t.assign?.decision;a!==void 0&&(typeof a!="string"||a.length===0)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.assign.decision`,reason:`[decision/invalidAssignDecision] assign.decision muss ein nicht-leerer Gruppen-Key sein, erhalten ${JSON.stringify(a)}.`,severity:"error"});let l=typeof a=="string"&&a.length>0?a:void 0;l!==void 0&&n?.permissionGroupKeys!==void 0&&!n.permissionGroupKeys.has(l)&&r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.assign.decision`,reason:`[decision/unknownPermissionGroup] Berechtigungsgruppe "${l}" existiert nicht im Mandanten \u2014 niemand k\xF6nnte diese Entscheidung treffen. Bekannte Gruppen: ${[...n.permissionGroupKeys].sort().join(", ")}.`,severity:"error"});let d=t.decisionAsTask?.title;return d!==void 0&&(d!==null&&typeof d=="object"&&Object.values(d).some(u=>typeof u=="string"&&u.length>0)||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.decisionAsTask.title`,reason:"[decision/decisionTaskMissingTitle] decisionAsTask.title ist gesetzt, aber leer \u2014 entweder einen nicht-leeren lokalisierten Text angeben oder das Feld weglassen (dann greift der Standardtitel).",severity:"error"})),r}o(Ry,"validateDecisionNode");var Ty=[{id:"promoted",label:{de:"Nachger\xFCckt",en:"Moved up"}},{id:"closed",label:{de:"Warteliste geschlossen",en:"Waiting list closed"}}],BT=[{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 cr="processFooter";var Iy="promoted";var VT="promote",KT="Nachr\xFCcken";var UT={outcomes:Ty,pausesApplicationTasks:!0,progressEvents:["waitlisted","promoted","closed"],notificationEvents:o(()=>[{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:o(t=>(t.outcomes!==void 0&&t.outcomes.length>0?t.outcomes:Ty).some(n=>n.id===Iy)?[{id:VT,kind:"advance",outcome:Iy,label:{de:KT,en:"Promote from waitlist"},surface:cr,superUserOnly:!0}]:[],"actions")};var zB=/^(\d{4})-(\d{2})-(\d{2})$/;function HB(t){return t>=1900&&t<=2100}o(HB,"isSupportedYear");function QB(t,e,n){let r=new Date(Date.UTC(t,e-1,n));return r.getUTCFullYear()===t&&r.getUTCMonth()===e-1&&r.getUTCDate()===n}o(QB,"isRealDate");function $y(t){if(typeof t!="string")return null;let e=zB.exec(t);if(e===null)return null;let[,n,r,i]=e;return n===void 0||r===void 0||i===void 0||!HB(Number(n))||!QB(Number(n),Number(r),Number(i))?null:{year:n,month:r,day:i}}o($y,"isoDateParts");var YB="Europe/Berlin";function GT(){return YB}o(GT,"tenantTimeZone");var jT=new Map;function JB(t){let e=jT.get(t);if(e)return e;let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:t,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{ke("INVALID",`Unbekannte Zeitzone "${t}".`)}return jT.set(t,n),n}o(JB,"formatterFor");function ZB(t,e){let n=new Map(JB(t).formatToParts(new Date(e)).map(a=>[a.type,a.value])),r=o(a=>{let l=n.get(a);return l===void 0&&W(`Zeitzone "${t}" 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(e/1e3)*1e3}o(ZB,"zoneOffsetAt");function _y(t,e){let n=t+ZB(e,t);return{wallClock:new Date(n).toISOString().slice(0,19),timeZone:e}}o(_y,"instantToLocalDateTime");var Oy=3;function WT(t){return _y(t,GT()).wallClock.slice(0,10)}o(WT,"localIsoDate");var zT=o(t=>(t??[]).map(e=>`\u201E${e}\u201C`).join(", "),"list"),HT=o(t=>(t??[]).map(e=>`"${e}"`).join(", "),"listEn"),eV={"address/shape":{de:o(t=>({problem:`${t.where}: \u201E${t.address}\u201C ist keine g\xFCltige Adresse.`,remedy:"W\xE4hle die Adresse in der Auswahl neu."}),"de"),en:o(t=>({problem:`${t.where}: "${t.address}" is not a valid address.`,remedy:"Choose the address again from the picker."}),"en")},"address/missing":{de:o(t=>({problem:`${t.where}: Hier fehlt die Adresse, ohne die dieser Schritt nicht arbeiten kann.`,remedy:"W\xE4hle sie in der Auswahl."}),"de"),en:o(t=>({problem:`${t.where}: The address this step cannot work without is missing.`,remedy:"Choose it from the picker."}),"en")},"address/bareIdentifier":{de:o(t=>({problem:`${t.where}: \u201E${t.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:o(t=>({problem:`${t.where}: "${t.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:o(t=>({problem:`${t.where}: ${t.address} nennt einen Knoten oder eine Aufgabe, die es im Ablauf nicht gibt.`,remedy:"W\xE4hle eine Adresse aus der Auswahl."}),"de"),en:o(t=>({problem:`${t.where}: ${t.address} names a node or task the workflow does not have.`,remedy:"Choose an address from the picker."}),"en")},"address/unknownKey":{de:o(t=>({problem:`${t.where}: ${t.producer??"der Erzeuger"} erzeugt ${t.address} nicht.`,remedy:"W\xE4hle einen Wert, den der Erzeuger tats\xE4chlich liefert."}),"de"),en:o(t=>({problem:`${t.where}: ${t.producer??"the producer"} does not produce ${t.address}.`,remedy:"Choose a value the producer actually delivers."}),"en")},"address/envCohortBound":{de:o(t=>({problem:`${t.where}: ${t.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:o(t=>({problem:`${t.where}: ${t.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:o(t=>({problem:`${t.where}: ${t.address} ist eine interne Angabe beim Anlegen \u2014 sie lenkt nur eine Weiche (\u201EWenn\u201C-Knoten).`,remedy:"Lies sie in der Bedingung eines \u201EWenn\u201C-Knotens; in Dokumente und Felder wird sie nicht \xFCbernommen."}),"de"),en:o(t=>({problem:`${t.where}: ${t.address} is a staff input set at the start \u2014 it only steers a branch (an "If" node).`,remedy:'Read it in the condition of an "If" node; it is not carried into documents or fields.'}),"en")},"address/ownerNotWriter":{de:o(t=>({problem:`${t.where}: Die Aufgabe \u201E${t.producer}\u201C schreibt ${t.address} nicht.`,remedy:"W\xE4hle den Wert \xFCber seinen Schl\xFCssel; die schreibende Aufgabe folgt daraus."}),"de"),en:o(t=>({problem:`${t.where}: The task "${t.producer}" does not write ${t.address}.`,remedy:"Choose the value by its key; the writing task follows from it."}),"en")},"address/taskOwnerTaken":{de:o(t=>({problem:`${t.where}: Den Aufgaben-Schl\xFCssel gibt es mehrfach (${zT(t.names)}), und eine dieser Aufgaben schreibt Prozesswerte.`,remedy:"Gib der schreibenden Aufgabe einen Schl\xFCssel, den keine andere Aufgabe tr\xE4gt."}),"de"),en:o(t=>({problem:`${t.where}: The task key is used more than once (${HT(t.names)}), and one of these tasks writes process values.`,remedy:"Give the writing task a key no other task carries."}),"en")},"address/notVisible":{de:o(t=>({problem:t.producerNode!==void 0&&t.producerNode!==t.producer?`${t.where}: ${t.address} \u2014 \u201E${t.producer}\u201C h\xE4ngt an \u201E${t.producerNode}\u201C, das nicht auf jedem Weg vor \u201E${t.reader}\u201C liegt.`:`${t.where}: ${t.address} \u2014 \u201E${t.producer}\u201C liegt nicht auf jedem Weg vor \u201E${t.reader}\u201C.`,remedy:`Lies nur, was auf jedem Weg vor \u201E${t.reader}\u201C entsteht, oder ordne die Schritte so, dass der Erzeuger immer vorher l\xE4uft.`}),"de"),en:o(t=>({problem:t.producerNode!==void 0&&t.producerNode!==t.producer?`${t.where}: ${t.address} \u2014 "${t.producer}" hangs on "${t.producerNode}", which does not lie before "${t.reader}" on every path.`:`${t.where}: ${t.address} \u2014 "${t.producer}" does not lie before "${t.reader}" on every path.`,remedy:`Read only what is produced before "${t.reader}" on every path, or order the steps so the producer always runs first.`}),"en")},"address/pathNotInTarget":{de:o(t=>({problem:`${t.where}: ${t.address} \u2014 ${t.producer??"der Erzeuger"} hat dieses Feld nicht.`,remedy:"W\xE4hle ein Feld, das es dort gibt."}),"de"),en:o(t=>({problem:`${t.where}: ${t.address} \u2014 ${t.producer??"the producer"} has no such field.`,remedy:"Choose a field that exists there."}),"en")},"address/typeMismatch":{de:o(t=>({problem:`${t.where}: erwartet ${t.expected}, ${t.address} ist ${t.actual}.`,remedy:`W\xE4hle einen Wert vom Typ ${t.expected}.`}),"de"),en:o(t=>({problem:`${t.where}: expects ${t.expected}, ${t.address} is ${t.actual}.`,remedy:`Choose a value of type ${t.expected}.`}),"en")},"address/notFormInstance":{de:o(t=>({problem:`${t.where}: ${t.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:o(t=>({problem:`${t.where}: ${t.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:o(t=>({problem:`${t.where}: Die Liste liest Felder aus mehreren Formularen (${zT(t.names)}), beurteilt wird sie aber an einem Formular.`,remedy:"W\xE4hle alle Felder dieser Liste aus demselben Formular."}),"de"),en:o(t=>({problem:`${t.where}: The list reads fields of several forms (${HT(t.names)}) but is judged on one.`,remedy:"Choose every field of this list from the same form."}),"en")},"workItems/keyFormat":{de:o(t=>({problem:`${t.where}: Der Aufgaben-Schl\xFCssel \u201E${t.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:o(t=>({problem:`${t.where}: The task key "${t.address}" does not match ^[a-z][a-zA-Z0-9_]*$.`,remedy:'Rename the task in camelCase, e.g. "siblingRank".'}),"en")}};function Tu(t,e,n){let{problem:r,remedy:i}=eV[t][n](e);return`[${t}] ${r} ${i}`}o(Tu,"addressMessage");function Iu(t,e,n){if(e===n)return!0;let r=new Map,i=new Set;for(let l of hn(t.nodes)){let d=r.get(l.source)??[];d.push(l.target),r.set(l.source,d),i.add(l.target)}let s=t.nodes.filter(l=>!i.has(l.id)&&l.id!==e).map(l=>l.id),a=new Set(s);for(;s.length>0;){let l=s.shift();if(l===n)return!1;for(let d of r.get(l)??[])d===e||a.has(d)||(a.add(d),s.push(d))}return!0}o(Iu,"dominates");function QT(t,e,n){if(e===n)return!0;let r=new Map;for(let a of hn(t.nodes)){let l=r.get(a.source)??[];l.push(a.target),r.set(a.source,l)}let i=[e],s=new Set(i);for(;i.length>0;){let a=i.shift();for(let l of r.get(a)??[]){if(l===n)return!0;s.has(l)||(s.add(l),i.push(l))}}return!1}o(QT,"reaches");function Cy(t,e){let n=[],r=o(a=>({address:a.address,type:a.type,...a.label!==void 0?{label:a.label}:{},nodeId:a.nodeId}),"toVisible");for(let a of t.nodes)if(Iu(t,a.id,e))for(let l of lr(t,a))n.push(r(l));for(let a of uT)n.push({address:{scope:"env",key:a},type:my(a),label:hy(a),nodeId:null});let i=new Set(n.map(a=>fe(a.address))),s=(Array.isArray(t.processStore)?t.processStore:[]).filter(a=>a.derive!==void 0);for(let a=!0;a;){a=!1;for(let l of s){let d=fe({scope:"derived",key:l.key});if(i.has(d))continue;let c=Ca(t,l.key);c===null||!c.every(u=>i.has(fe(vu(u))))||(n.push({address:{scope:"derived",key:l.key},type:l.type,label:l.label,nodeId:null}),i.add(d),a=!0)}}return n}o(Cy,"visibleAddressesAt");function ur(t,e){let n=t?.readinessFormFieldsByFormNode?.get(e.owner);if(n!==void 0)return n.get(e.path)??null}o(ur,"formFieldEntryOf");var YT={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"}},tV=new Set(["nodeReads","requires","taskReads","taskDocument","familyRequestFields"]);function nV(t,e,n){let r=[];e.taskKey!==void 0&&r.push(`${n==="de"?"Aufgabe":"task"} \u201E${Gi(t,e.taskKey,n)}\u201C`);let i=e.kind==="binding"?` \u201E${e.at.split(".").pop()}\u201C`:"";return r.push(`${YT[e.kind][n]}${i}`),r.join(" \u203A ")}o(nV,"addressFieldWhere");function Ma(t,e,n){let r=nV(t,e,n);return e.nodeId===null?r:`\u201E${We(t,e.nodeId,n)}\u201C \u203A ${r}`}o(Ma,"whereOf");function JT(t,e,n){if(e.scope==="node")return We(t,e.owner,n);if(e.scope==="task")return Gi(t,e.owner,n)}o(JT,"producerName");function ZT(t,e){let n=[],r=new Set,i=o((l,d,c)=>{let u=Tu(l,c("de"),"de"),f=`${d}|${u}`;r.has(f)||(r.add(f),n.push({layer:"GRAPH",kind:"nodeRule",path:d,reason:u,severity:"error"}))},"report"),s=new Map(t.nodes.map(l=>[l.id,l])),a=[...t.nodes.flatMap(l=>Da(l)),...xu(t)];for(let l of a){let d=o(c=>Ma(t,l,c),"where");for(let c of rV(t,l,i))oV(t,l,c,i)&&(aV(t,l,c,e,i),yy.has(l.kind)&&!dV(s,c)&&i("address/notFormInstance",l.at,u=>({where:d(u),address:nt(t,c,u)})))}return cV(t,i),uV(t,a,i),hV(t,i),yV(t,i),n}o(ZT,"checkAddresses");function rV(t,e,n){let r=o(i=>Ma(t,e,i),"where");if(by(e)){let i=Au(e.value)??[];for(let s of i)s.address===null&&n(s.reason==="bareIdentifier"?"address/bareIdentifier":"address/shape",e.at,a=>({where:r(a),address:s.identifier}));return qo(e)}return typeof e.value=="string"?(n("address/bareIdentifier",e.at,i=>({where:r(i),address:e.value})),[]):Se(e.value)?[e.value]:(n("address/shape",e.at,i=>({where:r(i),address:JSON.stringify(e.value)??"undefined"})),[])}o(rV,"checkFieldShape");function XT(t,e,n,r){let i=JT(t,n,r);return{where:Ma(t,e,r),address:nt(t,n,r),...i!==void 0?{producer:i}:{}}}o(XT,"addressParams");function iV(t,e,n){return py(e)?null:Js(t,e)!==void 0?n==="condition"?null:"address/staffInputConditionOnly":Ln(e)?"address/envCohortBound":"address/unknownKey"}o(iV,"envAddressRefusal");function oV(t,e,n,r){let i=o(s=>XT(t,e,n,s),"params");switch(n.scope){case"env":{let s=iV(t,n.key,e.kind);return s===null?!0:(r(s,e.at,i),!1)}case"derived":return(t.processStore??[]).find(a=>a.key===n.key)?.derive!==void 0?!0:(r("address/unknownKey",e.at,i),!1);case"task":return t.nodes.some(a=>(a.tasks??[]).some(l=>l.key===n.owner))?(t.processStore??[]).some(a=>a.key===n.key&&a.derive===void 0)?dr(t,n.owner,n.key)===null?(r("address/ownerNotWriter",e.at,i),!1):!0:(r("address/unknownKey",e.at,i),!1):(r("address/unknownOwner",e.at,i),!1);case"node":{let s=t.nodes.find(a=>a.id===n.owner);return s===void 0?(r("address/unknownOwner",e.at,i),!1):lr(t,s).some(a=>a.address.scope==="node"&&a.address.key===n.key)?!0:(r(yy.has(e.kind)&&ii(s)?"address/notFormInstance":"address/unknownKey",e.at,i),!1)}}}o(oV,"resolves");function sV(t,e){return t===void 0||e===void 0||mn(e)===void 0?!0:mn(t)!==void 0&&zc(t,e)}o(sV,"addressTypeFits");function aV(t,e,n,r,i){let s=o(l=>XT(t,e,n,l),"params");if(n.scope!=="env"&&n.path!==void 0&&!lV(t,e,n,r)){i("address/pathNotInTarget",e.at,s);return}if(e.expectedType===void 0)return;let a=ky(t,n);sV(a,e.expectedType)||i("address/typeMismatch",e.at,l=>({...s(l),expected:e.expectedType,actual:a}))}o(aV,"checkPathAndType");function lV(t,e,n,r){if(n.scope!=="node")return!1;if(ky(t,n)!==void 0)return!0;if(n.key!==$n)return!1;if(!tV.has(e.kind))return t.nodes.find(s=>s.id===n.owner)?.formExports===void 0;let i=r?.readinessFormFieldsByFormNode?.get(n.owner);return i===void 0||i.has(n.path)}o(lV,"pathExists");function dV(t,e){if(!Pa(e))return!1;let n=t.get(e.owner);return n!==void 0&&n.type==="form"&&!ii(n)}o(dV,"isCreatingFormInstance");function cV(t,e){for(let n of t.nodes){let r=new Set(Da(n).map(s=>s.kind)),i=[...hT(n),...n.type==="setFlag"?["setFlagTarget"]:[]];for(let s of i){if(r.has(s))continue;let a=`nodes.${n.id}.${s==="setFlagTarget"?"target":s}`;e("address/missing",a,l=>({where:`\u201E${We(t,n.id,l)}\u201C \u203A ${YT[s][l]}`}))}}}o(cV,"checkRequiredFields");function uV(t,e,n){let r=new Map;for(let i of e)if(i.judgedTogether!==null)for(let s of qo(i)){if(s.scope!=="node"||s.key!==$n)continue;let a=r.get(i.judgedTogether)??[];a.push({field:i,owner:s.owner}),r.set(i.judgedTogether,a)}for(let[i,s]of r){let a=[...new Set(s.map(l=>l.owner))];a.length<2||n("address/mixedForms",i,l=>({where:Ma(t,s[0].field,l),names:a.map(d=>We(t,d,l))}))}}o(uV,"checkMixedForms");function fV(t,e){return t.type==="engagePush"&&e.kind==="payment"}o(fV,"readSkipsAbsentProducer");function pV(t,e,n){return e!==n&&QT(t,e,n)}o(pV,"precedesOnSomePath");function mV(t,e,n,r){let i=vu(n.address);return r.has(fe(i))||!gV(t,i)?!0:n.origin==="written"&&i.scope==="node"&&fV(e,n.field)&&pV(t,i.owner,e.id)}o(mV,"readPassesVisibility");function hV(t,e){for(let n of t.nodes){let r=ji(t,n);if(r.length===0)continue;let i=new Set(Cy(t,n.id).map(s=>fe(s.address)));for(let s of r){let a=vu(s.address);if(mV(t,n,s,i))continue;let l=a.scope==="task"?dr(t,a.owner,a.key):a.scope==="node"?a.owner:null;e("address/notVisible",s.field.at,d=>({where:Ma(t,s.field,d),address:nt(t,s.address,d),producer:JT(t,a,d)??nt(t,a,d),...l!==null?{producerNode:We(t,l,d)}:{},reader:We(t,n.id,d)}))}}}o(hV,"checkVisibility");function gV(t,e){if(e.scope==="env")return py(e.key);if(e.scope==="derived")return Ca(t,e.key)!==null;let n=fe(e);return t.nodes.some(r=>lr(t,r).some(i=>fe(i.address)===n))}o(gV,"producedSomewhere");function yV(t,e){let n=new Map;for(let r of t.nodes){let i=new Set(lr(t,r).flatMap(s=>s.address.scope==="task"?[s.address.owner]:[]));for(let[s,a]of(r.tasks??[]).entries()){let l=a.key;if(typeof l!="string"||!rr.test(l)){e("workItems/keyFormat",`nodes.${r.id}.tasks.${s}.key`,c=>({where:`\u201E${We(t,r.id,c)}\u201C`,address:String(l)}));continue}let d=n.get(l)??[];d.push({nodeId:r.id,writes:i.has(l)}),n.set(l,d)}}for(let[r,i]of n)if(!(i.length<2||!i.some(s=>s.writes)))for(let s of i)e("address/taskOwnerTaken",`nodes.${s.nodeId}.tasks.${r}`,a=>({where:`\u201E${We(t,s.nodeId,a)}\u201C \u203A ${a==="de"?"Aufgabe":"task"} \u201E${Gi(t,r,a)}\u201C`,names:i.map(l=>We(t,l.nodeId,a))}))}o(yV,"checkTaskKeys");function $u(t,e){return t.label[e]??""}o($u,"wordingIn");function Wi(t,e){let n=eI(t,e),r=$u(t.qualifier,e);return n===""||r===""&&$u(t.qualifier,"de")!==""?"":r===""?n:`${r} \xB7 ${n}`}o(Wi,"fieldLabelIn");function eI(t,e){return $u(t,e)}o(eI,"fieldOwnLabelIn");function si(t){return{key:t.key,kind:t.kind,type:t.kind==="entered"?t.type:null,repeated:t.kind==="entered"&&t.repeated,name:{de:Wi(t,"de"),en:Wi(t,"en")}}}o(si,"catalogField");function ai(t,e,n){switch(t){case"nodeReads":return e.repeated?"repeated":n==="review"&&e.kind==="computed"?"computed":null;case"requires":return e.repeated?"repeated":e.kind==="computed"?"computed":e.name.en===""?"untranslated":null;case"taskDocument":return e.repeated?"repeated":e.kind==="entered"&&e.type==="docRef"?null:"notDocument";case"taskReads":case"familyRequestFields":return null}}o(ai,"catalogFieldRefusal");var bV="complete",_u="acceptedIncomplete",Ou="rejected",wV="absage",tI="closeWithoutDocuments",nI="rejectAtCompleteness",rI="Ohne Nachreichung abschlie\xDFen",iI="Ablehnen",oI="awaitingDocuments",Py="documentsComplete",Ny="closedWithoutDocuments",Dy="rejected",Fy="withdrawn",sI="requested",Jce={[bV]:{event:Py,status:"complete",endsRole:!0},[_u]:{event:Ny,status:"acceptedIncomplete",endsRole:!1},[Ou]:{event:Dy,status:"rejected",endsRole:!0},[wV]:{event:Fy,status:"withdrawn",endsRole:!0}};var Ly=o(()=>Fa[0],"beneficiary"),aI=366;function kV(t){let e=t.reads,n=Eu(t).flatMap(({address:r})=>Xe(r)&&!Fa.includes(r.path)?[r]:[]);return[...Array.isArray(e)?e.filter(Xe):[],...n]}o(kV,"printedFields");function vV(t,e){let n=fe(e);return t.nodes.filter(r=>r.type==="governedDocument"&&kV(r).some(i=>fe(i)===n))}o(vV,"documentsPrinting");function SV(t,e){if(!Xe(e)||e.path!==Ly())return!1;let n=t.nodes.find(r=>r.id===e.owner);return n!==void 0&&n.type==="form"&&!ii(n)}o(SV,"isCreatedFormBeneficiary");function qt(t,e,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.${e}`,reason:n,severity:"error"}}o(qt,"issue");var lI={outcomes:BT,progressEvents:[oI,Py,Ny,Dy,Fy],notificationEvents:o(()=>[{id:sI,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:o(t=>{let e=o(r=>t.next?.[r]!==void 0,"wired"),n=[];return e(_u)&&n.push({id:tI,kind:"advance",outcome:_u,label:{de:rI,en:"Close without documents"},surface:cr,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"}}}),e(Ou)&&n.push({id:nI,kind:"advance",outcome:Ou,label:{de:iI,en:"Reject application"},surface:cr,superUserOnly:!0,confirm:{title:{de:"Unterlagen unvollst\xE4ndig",en:"Documents incomplete"},body:{de:"Der Platz wird abgesagt und die Anfrage an die Familie geschlossen. Das l\xE4sst sich nicht r\xFCckg\xE4ngig machen.",en:"The application is rejected and the request to the family is closed. This cannot be undone."},confirmLabel:{de:"Ablehnen",en:"Reject"}}}),n},"actions"),inputs:o(()=>[{id:"person",label:{de:"Person (Gasth\xF6rer-Rolle)",en:"Person (guest role)"},type:"personRef",required:!1}],"inputs"),validate:o((t,e,n)=>{let r=[],i=`Vollst\xE4ndigkeitspr\xFCfung \u201E${t.label?.de??t.id}\u201C (${t.id})`,s=o(b=>nt(e,b,"de"),"shown"),a=t.requires;if(!Array.isArray(a)||a.length===0)r.push(qt(t,"requires",`[completenessCheck/missingRequires] ${i} nennt keine Felder \u2014 \`requires\` muss mindestens ein Feld eines Formulars enthalten ($node.<formular>.admission.<feld>).`));else{let b=new Set;for(let y of a){if(!Se(y))continue;let w=fe(y);if(b.has(w)){r.push(qt(t,"requires",`[completenessCheck/duplicateField] Feld ${s(y)} steht doppelt in \`requires\`.`));continue}if(b.add(w),!Xe(y)){r.push(qt(t,"requires",`[completenessCheck/unknownField] ${s(y)} ist kein Feld eines Formulars \u2014 \`requires\` nennt Felder ($node.<formular>.admission.<feld>).`));continue}let S=ur(n,y);if(S==null)continue;let A=ai("requires",si(S));A==="computed"||A==="repeated"?r.push(qt(t,"requires",`[completenessCheck/fieldNotRequestable] Feld ${s(y)} ist ${S.kind==="computed"?"berechnet":"ein Feld einer wiederholten Gruppe"} \u2014 die Familie kann es nicht nachreichen.`)):A==="untranslated"&&r.push(qt(t,"requires",`[completenessCheck/fieldNameUntranslated] Feld ${s(y)} (\u201E${Wi(S,"de")}") hat keinen englischen Namen (Feld oder Person/Abschnitt) \u2014 der Brief \u201EUnterlagen angefordert" nennt es in der Sprache der Familie.`))}}let l=t.deadline,d=typeof l=="object"&&l!==null?l:{},c="inDays"in d,u="until"in d;if(c===u)r.push(qt(t,"deadline",`[completenessCheck/deadlineShape] Vollst\xE4ndigkeitspr\xFCfung "${t.id}" braucht genau eine Frist: \`{ inDays: n }\` (Tage ab Eintritt) oder \`{ until: "JJJJ-MM-TT" }\`.`));else if(c){let b=d.inDays;(typeof b!="number"||!Number.isInteger(b)||b<0||b>aI)&&r.push(qt(t,"deadline.inDays",`[completenessCheck/deadlineDays] Frist "${String(b)}" ist keine ganze Zahl von 0 bis ${aI} Tagen.`))}else typeof d.until!="string"||$y(d.until)===null?r.push(qt(t,"deadline.until",`[completenessCheck/deadlineDate] Frist "${String(d.until)}" ist kein g\xFCltiges Datum (JJJJ-MM-TT).`)):d.until<WT(Date.now())&&r.push({...qt(t,"deadline.until",`[completenessCheck/deadlinePassed] Frist "${d.until}" liegt in der Vergangenheit \u2014 jede Anfrage bek\xE4me den Tag des Eintritts als Frist. Datum aktualisieren?`),severity:"warning"});if(Array.isArray(a)){let b=new Map(a.filter(Xe).map(y=>[fe(y),y]));for(let y of b.values())for(let w of vV(e,y))r.push(qt(t,"requires",`[completenessCheck/requiresConsumedUpstream] Feld ${s(y)} flie\xDFt in das Dokument \u201E${w.label?.de??w.id}" (${w.id}) ein \u2014 nach dessen Ausstellung kann die Familie es nicht mehr nachreichen. Feld aus \`requires\` oder aus dem Dokument nehmen.`))}let f=t.guestRole,h=t.inputs?.person,g=h?.kind==="binding"?h.address:null;f!==void 0&&(typeof f!="string"||f.trim()===""?r.push(qt(t,"guestRole","[completenessCheck/guestRoleEmpty] `guestRole` ist leer \u2014 Rollenschl\xFCssel angeben oder das Feld weglassen.")):n?.roleKeys!==void 0&&!n.roleKeys.has(f)?r.push(qt(t,"guestRole",`[completenessCheck/unknownRole] Rolle "${f}" existiert nicht im Rollenkatalog des Mandanten. Bekannte Rollen: ${[...n.roleKeys].sort().join(", ")}.`)):n?.assignableRoleKeys!==void 0&&!n.assignableRoleKeys.has(f)&&r.push(qt(t,"guestRole",`[completenessCheck/nonLeafRole] Rolle "${f}" hat untergeordnete Rollen und ist nicht vergebbar.`)),g===null&&r.push(qt(t,"inputs.person",`[completenessCheck/guestRoleNeedsPerson] ${i} vergibt die Rolle "${String(f)}", aber der Eingang \u201Eperson" ist nicht gebunden (z. B. an $node.<formular>.${$n}.${Ly()}).`))),Se(g)&&!SV(e,g)&&r.push(qt(t,"inputs.person",`[completenessCheck/personNotFormParty] Eingang \u201Eperson" ist an ${s(g)} gebunden \u2014 die Pr\xFCfung vergibt die Rolle der Person, f\xFCr die ein Formular abgeschickt wurde ($node.<anlegender Formularknoten>.${$n}.${Ly()}).`)),g!==null&&f===void 0&&r.push(qt(t,"inputs.person",'[completenessCheck/personWithoutRole] Eingang \u201Eperson" ist gebunden, aber es wird keine Rolle vergeben \u2014 die Bindung wirkt nicht.'));for(let b of["complete","rejected","absage"])t.next?.[b]===void 0&&r.push(qt(t,`next.${b}`,`[completenessCheck/unroutedOutcome] Vollst\xE4ndigkeitspr\xFCfung "${t.id}" leitet den Ausgang "${b}" nirgendwohin.`));return r},"validate")};var My="checkField",dI="reviewed",cI="reviewing";var xV=[{id:dI,label:{de:"Gepr\xFCft",en:"Reviewed"}}],qa=o(t=>t,"asDecision"),uI={role:"user-action",effect:"side-effect",outcomes:xV,progressEvents:[cI],notificationEvents:o(t=>oi.notificationEvents(qa(t)),"notificationEvents"),actions:o(t=>[...oi.actions(qa(t)).map(e=>e.kind==="advance"&&(t.outcomes??[]).length===1?{...e,label:{de:"Pr\xFCfung abschlie\xDFen",en:"Complete review"}}:e),{id:My,kind:"internal",label:{de:"Feld abhaken",en:"Tick field"}}],"actions"),optionalActionKinds:oi.optionalActionKinds,workItemTemplates:o(t=>oi.workItemTemplates(qa(t)).map(e=>e.key===La?{...e,title:t.decisionAsTask?.title??{de:"Angaben pr\xFCfen",en:"Review the application"},unlocks:[...e.unlocks,My]}:e),"workItemTemplates"),taskDocuments:o((t,e)=>oi.taskDocuments(qa(t),e),"taskDocuments"),validate:o((t,e,n)=>{let r=Ry(qa(t),e,n),i=Array.isArray(t.reads)?t.reads:[];for(let s of t.outcomes??[]){let a=qT(s.id);a!=="rejected"&&a!=="waitlisted"||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.outcomes`,reason:`[review/rejectingOutcome] Pr\xFCf-Knoten "${t.id}" deklariert das Outcome "${s.id}" \u2014 eine Pr\xFCfung lehnt nicht ab und setzt nicht auf die Warteliste; das ist die Entscheidung der Freigabe bzw. \u201EBewerbung ablehnen".`,severity:"error"})}for(let s of i){if(!Xe(s))continue;let a=ur(n,s);a==null||ai("nodeReads",si(a),t.type)!=="computed"||r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.reads`,reason:`[review/readsNotTickable] Pr\xFCf-Knoten \u201E${t.label?.de??t.id}\u201C (${t.id}) soll das berechnete Feld ${fe(s)} abhaken lassen \u2014 nur eingegebene Felder haben einen Wert, den jemand pr\xFCfen kann.`,severity:"error"})}return r},"validate")};function AV(t){if(t.context!==void 0)return{...t,...t.context};t.createdVia===void 0&&W(`readWorkItem: legacy work_item ${t._id} has neither context nor createdVia`);let e=t.applicationId===void 0?{kind:"task",createdVia:"human"}:{kind:"admission",recipient:t.recipient??(t.recipientAuthId===void 0?"internal":"external"),isApproval:t.isApproval,artifactVersionId:t.artifactVersionId,artifactSlotKey:t.artifactSlotKey,reason:t.reason,recipientAuthId:t.recipientAuthId,createdVia:t.createdVia,templateKey:t.templateKey,applicationId:t.applicationId,nodeId:t.nodeId,gatesNode:t.gatesNode,blocks:t.blocks,revisesWorkItemId:t.revisesWorkItemId,threadRootWorkItemId:t.threadRootWorkItemId,originatingWorkItemId:t.originatingWorkItemId};return{...t,context:e,...e}}o(AV,"readWorkItem");async function qy(t,e){let n,r;if(e.nodeId!==void 0)[n,r]=await Promise.all([t.db.query("work_items").withIndex("by_applicationId_and_nodeId",s=>s.eq("context.applicationId",e.applicationId).eq("context.nodeId",e.nodeId)).collect(),t.db.query("work_items").withIndex("by_legacyApplicationId_and_nodeId",s=>s.eq("applicationId",e.applicationId).eq("nodeId",e.nodeId)).collect()]);else if(e.isOpen!==void 0){let s=e.isOpen;[n,r]=await Promise.all([t.db.query("work_items").withIndex("by_applicationId_and_isOpen",a=>a.eq("context.applicationId",e.applicationId).eq("isOpen",s)).collect(),t.db.query("work_items").withIndex("by_legacyApplicationId_and_isOpen",a=>a.eq("applicationId",e.applicationId).eq("isOpen",s)).collect()])}else[n,r]=await Promise.all([t.db.query("work_items").withIndex("by_applicationId_and_nodeId",s=>s.eq("context.applicationId",e.applicationId)).collect(),t.db.query("work_items").withIndex("by_legacyApplicationId_and_nodeId",s=>s.eq("applicationId",e.applicationId)).collect()]);let i=[...n,...r].filter(s=>e.isOpen===void 0||s.isOpen===e.isOpen).map(AV);return[...new Map(i.map(s=>[s._id,s])).values()]}o(qy,"listWorkItemsForApplication");var fI=["awaitingAnswer","answered"];async function pI(t,e){return(await qy(t,{applicationId:e.applicationId,nodeId:e.nodeId})).filter(r=>r.templateKey===e.templateKey).some(r=>r.isOpen)?"awaitingAnswer":"answered"}o(pI,"externalRequestState");var Ba=["online","separate"];function Cu(t){return Ba.includes(t)}o(Cu,"isCollectPaymentSettlement");var Vo="paid",By="skipPayment",li="article",_r="settlement",mI=["one_time"];var gI=[{id:Vo,label:{de:"Bezahlt",en:"Paid"}}],Fue=new Set(gI.map(t=>t.id));var EV=Vo,hI=[{id:EV,kind:"advance",outcome:Vo,label:{de:"Zahlung eingegangen",en:"Payment received"},availableIn:["awaitingAnswer"]}],RV={id:By,kind:"advance",outcome:Vo,label:{de:"Zahlung \xFCberspringen",en:"Skip payment"},surface:cr,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"}}},TV={id:By,kind:"advance",outcome:Vo,label:{de:"Ohne Online-Zahlung abschlie\xDFen",en:"Close without online payment"},surface:cr,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 yI(t,e){let n=t.inputs?.[e];return n?.kind==="literal"?n.value:void 0}o(yI,"literalOf");function Va(t){let e=yI(t,_r);return Cu(e)?e:null}o(Va,"settlementOrNull");function IV(t){let e=yI(t,li);return typeof e=="string"&&e.length>0?e:null}o(IV,"articleKeyOrNull");var $V=[{id:li,label:{de:"Artikel",en:"Article"},type:"article",required:!0,inspector:"literal-only",optionSource:"programArticles"},{id:_r,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)"}}]}],_V=["amount","currency","settlement"];var bI={outputs:o(()=>[{name:pT,type:"object",label:{de:"Zahlung",en:"Payment"}}],"outputs"),role:"user-action",effect:"side-effect",inputs:o(()=>$V,"inputs"),outcomes:gI,progressEvents:["awaitingPayment"],notificationEvents:o(t=>Va(t)!=="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:o(t=>{let e=Va(t);return e==="online"?[...hI,TV]:e==="separate"?[RV]:[]},"actions"),states:fI,currentState:o((t,e)=>pI(t,{applicationId:e.applicationId,nodeId:e.node.id,templateKey:Ay}),"currentState"),workItemTemplates:o(t=>{let e=t;return Va(e)!=="online"?[]:[{key:Ay,recipient:"external",title:e.label,unlocks:hI.map(n=>n.id),advancesNode:!0}]},"workItemTemplates"),validate:o((t,e,n)=>{let r=[],i=o((l,d)=>r.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.${l}`,reason:d,severity:"error"}),"push");for(let l of _V)l in t&&i(l,`[collectPayment/retiredField] \u201E${l}" steht nicht mehr am Zahlungsknoten \u2014 Betrag und W\xE4hrung kommen aus dem Artikel (Parameter \u201EArtikel"), die Abrechnung ist der Parameter \u201EAbrechnung" (inputs.settlement).`);Va(t)==="online"&&n?.onlinePaymentsReady===!1&&i(`inputs.${_r}`,'[collectPayment/onlineWithoutStripe] Abrechnung \u201Eonline" setzt voraus, dass Stripe f\xFCr diese Schule eingerichtet ist (Einstellungen \u2192 Integrationen \u2192 Stripe) \u2014 sonst kann keine Familie bezahlen. Bis dahin \u201Eseparat" w\xE4hlen.'),Va(t)===null&&i(`inputs.${_r}`,`[collectPayment/invalidSettlement] Abrechnung muss eine von ${Ba.join(", ")} sein (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); erhalten ${JSON.stringify(t.inputs?.[_r])}.`);let s=IV(t);if(s===null)return i(`inputs.${li}`,'[collectPayment/missingArticle] Der Zahlungsknoten nennt keinen Artikel \u2014 unter \u201EParameter" einen einmaligen Artikel des Programms w\xE4hlen (Finanzen \u2192 Artikel).'),r;let a=`inputs.${li}`;return n?.billingItemKeys!==void 0&&!n.billingItemKeys.has(s)?(i(a,`[collectPayment/unknownArticle] Artikel \u201E${s}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel.`),r):(n?.oneTimeBillingItemKeys!==void 0&&!n.oneTimeBillingItemKeys.has(s)&&i(a,`[collectPayment/articleNotOneTime] Artikel \u201E${s}" ist kein einmaliger Artikel \u2014 eine Geb\xFChr nimmt nur ${mI.join(", ")}.`),n?.offerProgram===null?i(a,"[collectPayment/articleOfferWithoutProgram] Das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben."):n?.offerProgram?.directBillingItemKeys!==void 0&&!n.offerProgram.directBillingItemKeys.has(s)&&i(a,`[collectPayment/articleNotInProgram] Artikel \u201E${s}" ist dem Programm \u201E${n.offerProgram.nameDe}" des Angebots nicht direkt zugeordnet \u2014 unter Finanzen \u2192 Artikel zuordnen (ein Paket z\xE4hlt nicht: es kann den Artikel anders bepreisen).`),r)},"validate")};var _n="traeger",wI={de:"Tr\xE4ger",en:"Provider"};function kI(t){let e=t.inputs?.[_n];return e?.kind==="literal"&&typeof e.value=="string"&&e.value.length>0?e.value:null}o(kI,"traegerKeyOfNode");var Vy={name:"input.traeger.name",address:"input.traeger.anschrift"},que=Object.values(Vy);function vI(t,e){return`[governedDocument/localeFieldMissing] Der Dokumentknoten \u201E${t}\u201C (Vorlage "${e}") nennt kein Sprachfeld \u2014 ein Schreiben entsteht in genau einer Sprache. Ein Pflicht-Auswahlfeld mit den Optionen de/en anlegen, es als template.localeField nennen und 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>>.`}o(vI,"localeFieldMissingReason");var Ky=["muster-angebot","muster-vertrag","muster-vertrag-signiert"];var SI="governedDocument",Ko="prepareDocument",Ka="prepareDocument:revision",di="releaseApproval",zi="documentResponse",fr="responseCheck",Pu="returnSigned";var xI="requestApproval";var AI="issueDocument",EI="correctInPlace",RI="rescindAndReissue",Nu="requestChange";var Uo="releaseArtifact",Hi="signingRecovery",Du="resendESignature",Fu="switchToPaper";var Uy=new Set([Ko,Ka]),TI=["pending","producing","producingHeld","deferred","awaitingApproval","awaitingResponse","responseReturned","responseInCheck","awaitingSignature","signatureStalled","done"],jy=["upload","resolver","template","none"],II=new Set(["resolver","template"]),Ua=1,ja=366;function Lu(t){return typeof t=="number"&&Number.isInteger(t)&&t>=Ua&&t<=ja}o(Lu,"isValidResponseDueInDays");var Gy=["generatedAt","responseDueInDays"],jo=["release","none"],Wy=["confirm","signedUpload","signedUploadChecked","eSignature"];var OV={kind:"confirm",acceptOutcomeId:"accepted",declineOutcomeId:"declined",acceptEvent:"userTaskResolved",producesResponseArtifact:!1,declineIsAnswer:!0,acceptStatus:"accepted",checksReturn:!1,issuesBy:"paper",defaultLabels:{accept:{de:"Annehmen",en:"Accept"},decline:{de:"Ablehnen",en:"Decline"}}},$I={kind:"signedUpload",acceptOutcomeId:"signed",declineOutcomeId:"absage",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"}}},_I={...$I,kind:"signedUploadChecked",acceptEvent:"contractEvent",checksReturn:!0},CV={..._I,kind:"eSignature",issuesBy:"provider"},Or={confirm:OV,signedUpload:$I,signedUploadChecked:_I,eSignature:CV};function ci(t){let e=t.responseStrategy;if(typeof e=="string"&&e in Or)return Or[e];W(`governedDocument node "${t.id}" declares no valid responseStrategy (got ${JSON.stringify(e)}) \u2014 publish validation should have blocked this; corrupt pinned graph`)}o(ci,"responseStrategyOf");function OI(t){if(t.type!==SI||t.production!=="resolver")return!1;let e=t.responseStrategy;return typeof e=="string"&&e in Or?Or[e].acceptEvent==="contractEvent":!1}o(OI,"isFamilySignedContractNode");function Ga(t){return t.label}o(Ga,"governedDocTitle");function zy(t){return t.approval==="release"?xI:AI}o(zy,"submitActionId");function CI(t,e,n){return{key:e,recipient:"internal",title:n,unlocks:[zy(t)],gatesNode:!0,advancesNode:!0}}o(CI,"producerTemplate");function PV(t){return t.titles?.respond??t.label}o(PV,"responseTitle");var Go={de:"\u27E8Titel fehlt\u27E9",en:"\u27E8title missing\u27E9"};function Hy(t){let e=ci(t),n=[];if(t.production!=="none"&&n.push(CI(t,Ko,t.titles?.prepare??Go),CI(t,Ka,t.titles?.revise??Go)),t.approval==="release"&&n.push({key:di,recipient:"internal",title:t.titles?.approve??Go,unlocks:[],verdictResolved:!0,gatesNode:!0,advancesNode:!0}),n.push({key:zi,recipient:"external",title:PV(t),unlocks:e.producesResponseArtifact?[e.checksReturn?Pu:e.acceptOutcomeId,e.declineOutcomeId,Nu]:[e.acceptOutcomeId,e.declineOutcomeId],advancesNode:!0,...t.responseDueInDays!==void 0?{dueInDays:t.responseDueInDays}:{}}),e.checksReturn&&n.push({key:fr,recipient:"internal",title:t.titles?.check??Go,unlocks:[],verdictResolved:!0,gatesNode:!1,advancesNode:!0}),e.issuesBy==="provider"){let r=Ga(t);n.push({key:Hi,recipient:"internal",title:{de:`${r.de}: elektronische Unterschrift kl\xE4ren`,en:`${r.en}: resolve the e-signature`},unlocks:[Du,Fu],gatesNode:!1,advancesNode:!1})}return n}o(Hy,"governedDocIntrinsicTemplates");function NV(t){t.production==="none"&&W(`governedDocSlot: node "${t.id}" has production 'none' \u2014 it governs no artifact slot`);let e=t.artifacts??[];e.length!==1&&W(`governedDocSlot: node "${t.id}" declares ${e.length} artifact slots \u2014 exactly ONE is required (publish validation [governedDocument/slotContract])`);let n=e[0];return(typeof n.key!="string"||n.key.length===0)&&W(`governedDocSlot: node "${t.id}" declares an artifact slot without a key \u2014 corrupt pinned graph`),n}o(NV,"governedDocSlot");function Mu(t){return NV(t).key}o(Mu,"governedDocSlotKey");async function DV(t,e,n){if(n.revisesWorkItemId===void 0)return;let r=await t.db.get(n.revisesWorkItemId),i=r?.context,s=i?.kind==="admission"?e.returnPinOf(i):void 0;return(r===null||i===void 0||i.kind!=="admission"||i.templateKey!==fr||r.status!=="done"||r.outcome!=="rejected"||s===void 0)&&W(`rejectedReturnOfAsk: ask ${n._id} revises ${n.revisesWorkItemId}, which is not a rejected, pinned ${fr} row`),s}o(DV,"rejectedReturnOfAsk");async function PI(t,e){return await e.chain.returned(t,e.applicationId,{askedAbout:e.chain.pinOf(e.ask),rejected:await DV(t,e.chain,e.ask),onUnpinned:e.onUnpinned,where:e.where})}o(PI,"returnedCopyOfAsk");function FV(t){return(t.versionNumber===void 0||t.versionNumber<1||t.storageId===void 0)&&W(`artifactChain: artifact ${t._id} is no content version (versionNumber ${t.versionNumber}) \u2014 corrupt slot`),{_id:t._id,_creationTime:t._creationTime,versionNumber:t.versionNumber,...t.status!==void 0?{status:t.status}:{},...t.origin!==void 0?{origin:t.origin}:{},storageId:t.storageId,...t.mimeType!==void 0?{mimeType:t.mimeType}:{},...t.filename!==void 0?{filename:t.filename}:{}}}o(FV,"toRevision");function LV(t){let e=FV(t);return{_id:e._id,_creationTime:e._creationTime,storageId:e.storageId,...e.filename!==void 0?{filename:e.filename}:{},...e.mimeType!==void 0?{mimeType:e.mimeType}:{},round:e.versionNumber}}o(LV,"toReturn");function NI(t){let e=Mu(t);async function n(i,s){return(await i.db.query("artifacts").withIndex("by_applicationId_and_key_and_versionNumber",l=>l.eq("applicationId",s).eq("key",e)).collect()).filter(l=>(l.versionNumber??0)>=1)}return o(n,"contentRowsAsc"),{reads:{kind:"artifact",async returned(i,s,a){if(a.askedAbout===void 0){if(a.onUnpinned==="notReturned")return null;ke("CONFLICT","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).")}let l=(await n(i,s)).filter(c=>c.storageId!==void 0),d=l[l.length-1];if(d===void 0||d._id===a.askedAbout||d.origin!=="uploaded")return null;if(a.rejected!==void 0){let c=l.find(u=>u._id===a.rejected);if(c===void 0&&W(`returned(${a.where}): the handed-back scan ${a.rejected} is no version of slot "${e}"`),(d.versionNumber??0)<=(c.versionNumber??0))return null}return LV(d)},pinOf(i){return i.artifactVersionId},returnPinOf(i){return i.artifactVersionId}},contentRowsAsc:n}}o(NI,"artifactNodeReads");var Qy=50;async function qu(t,e){let n=await t.db.query("signing_returns").withIndex("by_signingRequestId",r=>r.eq("signingRequestId",e)).take(Qy+1);return n.length>Qy&&W(`signing_returns: Vorgang ${e} has more than ${Qy} returns`),n}o(qu,"returnsOf");var Yy=50;async function Jy(t,e){let n=await t.db.query("signing_return_documents").withIndex("by_signingReturnId_and_order",r=>r.eq("signingReturnId",e)).take(Yy+1);return n.length>Yy&&W(`signing_returns: return ${e} has more than ${Yy} files`),n.length===0&&W(`[signing/unmigrated] return ${e} carries no file (see migrations.moveSigningReturnFilesToDocuments)`),n}o(Jy,"returnDocumentsOf");async function DI(t,e){let n=await Jy(t,e);return n.length!==1&&W(`[signing/severalDocuments] return ${e} carries ${n.length} files; this reader handles one`),n[0]}o(DI,"soleReturnDocumentOf");var Bu=200,yfe=Bu*20;async function MV(t,e){let n=await t.db.get(e);return n===null&&W(`[process] application ${e} not found`),n.redactedAt!==void 0}o(MV,"processRedacted");async function qV(t,e){await MV(t,e)&&ke("CONFLICT","Die Daten dieser Bewerbung wurden gel\xF6scht.")}o(qV,"assertProcessReadable");function FI(t){(t.scope===void 0||t.owner===void 0||t.key===void 0||t.result===void 0)&&W(`[process] store row ${t._id} of application ${t.applicationId} has no address or result \u2014 run migrations.reshapeProcessStoreEntries`);let e=t.result;return e.kind==="redacted"&&W(`[process] store row ${t._id} of application ${t.applicationId} is a retired redacted row \u2014 run migrations.reshapeProcessStoreEntries`),e.kind==="ref"&&(e.ref.kind==="payment"||"artifactId"in e.ref)&&W(`[process] store row ${t._id} of application ${t.applicationId} holds a retired ${e.ref.kind} ref \u2014 run migrations.copySmartFormsToInstances / reshapeProcessStoreEntries`),{_id:t._id,_creationTime:t._creationTime,scope:t.scope,owner:t.owner,key:t.key,result:e,...t.writtenByTaskId!==void 0?{writtenByTaskId:t.writtenByTaskId}:{}}}o(FI,"rowOf");async function LI(t,e,n){await qV(t,e);let r=await t.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",s=>s.eq("applicationId",e).eq("scope",n.scope).eq("owner",n.owner).eq("key",n.key)).order("desc").take(Bu+1);r.length>Bu&&W(`[process] application ${e} has more than ${Bu} results of ${n.scope}.${n.owner}.${n.key}`);let i=await t.db.query("process_store_entries").withIndex("by_applicationId_and_scope_and_owner_and_key",s=>s.eq("applicationId",e).eq("scope",void 0)).first();return i!==null&&FI(i),r.map(FI)}o(LI,"storeHistory");async function BV(t,e,n){let[r]=await LI(t,e,{scope:"node",owner:n.owner,key:n.key});return r===void 0?{state:"pending",reason:null}:{state:"present",result:r.result,row:r}}o(BV,"nodeResultAt");async function Zy(t,e){let n={scope:"node",owner:e.nodeId,key:e.key};return VV(await BV(t,e.applicationId,n),n,e.applicationId)}o(Zy,"readOwnResult");function VV(t,e,n){return t.state!=="present"?{state:"pending"}:((t.result.kind!=="ref"||t.row===null)&&W(`[process] ${fe(e)} of application ${n} holds a value \u2014 this address holds a ref`),{state:"ref",ref:t.result.ref,row:t.row})}o(VV,"refOf");var ui=["docusign","insign"];var Wa={docusign:"DocuSign",insign:"inSign",manual:"Auf Papier",simulated:"Simuliert (Testmodus)"};var Xy={pending:"open",sent:"open",partially_signed:"open",completed:"terminal",declined:"terminal",voided:"terminal",expired:"terminal",failed:"terminal"},UV=Object.keys(Xy),jV=UV.filter(t=>Xy[t]==="open"),Ffe=jV.filter(t=>t!=="pending");function qI(t){return Xy[t]==="terminal"}o(qI,"isTerminalSigningStatus");var GV=qI;function BI(t){return!GV(t.status)&&t.voidRequestedAt===void 0}o(BI,"holdsContract");async function VI(t,e){return await t.db.query("legal_entities").withIndex("by_partyId",n=>n.eq("partyId",e)).unique()}o(VI,"traegerLegalEntityOfParty");async function WV(t,e){return await t.db.query("organizations").withIndex("by_partyId",r=>r.eq("partyId",e)).first()!==null}o(WV,"isOrganizationParty");async function KI(t,e){return await VI(t,e)!==null?"traeger":await WV(t,e)?"organization":"person"}o(KI,"signerKindOf");async function UI(t,e){e.length===0&&W("signingSideOf: a Vorgang without signers asks nobody");for(let n of e)if(await zV(t,n.partyId)==="family")return"family";return"traeger"}o(UI,"signingSideOf");async function zV(t,e){return await KI(t,e)==="traeger"?"traeger":"family"}o(zV,"sideOfParty");var ipe=16*1024;var ope=15*6e4;var spe=10*6e4;var eb=200;async function QV(t,e,n,r){e.length>eb&&W(`${r} is carried by more than ${eb} signing requests`);let i=[],s=new Set;for(let l of e){if(s.has(l.signingRequestId))continue;s.add(l.signingRequestId);let d=await t.db.get(l.signingRequestId);d===null&&W(`signing_request_documents ${l._id} names a missing signing request ${l.signingRequestId}`),i.push(d)}let a=n==="asc"?1:-1;return i.sort((l,d)=>a*(l._creationTime-d._creationTime))}o(QV,"requestsOfMembers");async function YV(t,e){let[n,r,i]="contractSnapshotId"in e?["by_contractSnapshotId","contractSnapshotId",e.contractSnapshotId]:["by_contractId","contractId",e.contractId],s=await t.db.query("signing_requests").withIndex(n,a=>a.eq(r,i)).first();s!==null&&W(`[signing/unmigrated] signing request ${s._id} still names ${r} ${i} on itself \u2014 migrations.moveSigningRequestBindingToDocuments has not run`)}o(YV,"refuseUnmovedBinding");async function jI(t,e,n="asc"){await YV(t,{contractSnapshotId:e});let r=await t.db.query("signing_request_documents").withIndex("by_contractSnapshotId",i=>i.eq("contractSnapshotId",e)).take(eb+1);return await QV(t,r,n,`revision ${e}`)}o(jI,"requestsOfSnapshot");var GI=100;async function JV(t,e){let n=await jI(t,e);n.length>GI&&W(`requestsBySideOf: revision ${e} has more than ${GI} Vorg\xE4nge`);let r={family:[],traeger:[]};for(let i of n.sort((s,a)=>s._creationTime-a._creationTime))r[await UI(t,i.signers)].push(i);return r}o(JV,"requestsBySideOf");async function tb(t,e){return(await JV(t,e)).family}o(tb,"familyRequestsOf");var nb=100;async function ZV(t,e){let n=await t;return n.length>nb&&W(`contractChain: more than ${nb} ${e}`),n}o(ZV,"bounded");async function XV(t,e,n){let r=await Zy(t,{applicationId:e,nodeId:n,key:Mo});return r.state==="pending"?null:(r.ref.kind!=="contract"&&W(`contractChain: $node.${n}.${Mo} of application ${e} is a ${r.ref.kind} ref \u2014 the contract chain writes a contract ref`),r.ref.contractId)}o(XV,"nodeContractRef");async function WI(t,e){return await ZV(t.db.query("contract_snapshots").withIndex("by_contractId_and_revisionNumber",n=>n.eq("contractId",e)).take(nb+1),`revisions on contract ${e}`)}o(WI,"snapshotsAsc");async function rb(t,e){let n=(await tb(t,e)).filter(BI);return n.length>1&&W(`contractChain: revision ${e} has ${n.length} open family Vorg\xE4nge`),n[0]??null}o(rb,"openFamilyRequest");async function zI(t,e){for(let n of await WI(t,e))if((await tb(t,n._id)).some(r=>r.provider==="manual"))return"paper";return"provider"}o(zI,"familyRoute");async function eK(t,e){let n=await DI(t,e._id),r=await t.db.system.get("_storage",n.storageId);return r===null&&W(`contractChain: return ${e._id} holds missing file ${n.storageId}`),{_id:e._id,_creationTime:e._creationTime,storageId:n.storageId,filename:n.filename,...r.contentType!==void 0?{mimeType:r.contentType}:{},round:e._id}}o(eK,"toReturn");function Vu(t){async function e(s,a){return await XV(s,a,t.id)}o(e,"contractOrNull");async function n(s,a,l,d){let c=s.db.normalizeId("contract_snapshots",l),u=c===null?null:await s.db.get(c),f=await e(s,a);return(u===null||f===null||u.contractId!==f)&&W(`${d}: ${l} is no revision of node "${t.id}"'s contract ${f??"(none yet)"} \u2014 corrupt arc`),u}o(n,"snapshotOf");async function r(s,a){let l=await e(s,a);return l===null?null:(await WI(s,l)).at(-1)??null}return o(r,"newestSnapshot"),{reads:{kind:"contract",async returned(s,a,l){if(l.askedAbout===void 0){if(l.onUnpinned==="notReturned")return null;W(`returned(${l.where}): an ask of the contract chain is always pinned to its revision`)}let d=await n(s,a,l.askedAbout,`returned(${l.where})`),c=await rb(s,d._id);if(c===null)return null;let u=(await qu(s,c._id)).filter(f=>f.review.status==="pending"&&f._id!==l.rejected);return u.length>1&&W(`returned(${l.where}): Vorgang ${c._id} has ${u.length} returns pending \u2014 one is checked at a time`),u[0]===void 0?null:await eK(s,u[0])},pinOf(s){return s.contractSnapshotId},returnPinOf(s){return s.signingReturnId}},contractOrNull:e,snapshotOf:n,newestSnapshot:r}}o(Vu,"contractNodeReads");var ib=20;async function tK(t,e){let n=await t.db.query("contract_generation_runs").withIndex("by_generationGroupId",r=>r.eq("generationGroupId",e)).take(ib+1);return n.length>ib&&W(`groupRunsOf: generation group ${e} has more than ${ib} runs`),n.length===0&&W(`groupRunsOf: generation group ${e} has no run`),n.sort((r,i)=>r._creationTime-i._creationTime)}o(tK,"groupRunsOf");async function HI(t,e){let n=await tK(t,e),r=n[0].combinedGeneratorId;(r===void 0||n.some(a=>a.combinedGeneratorId!==r||a.partKey===void 0))&&W(`groupRunsInOrder: the runs of generation group ${e} disagree on their combined generator or lack a part`);let i=await t.db.get(r);(i===null||i.kind!=="combined")&&W(`groupRunsInOrder: group ${e} names ${r}, which is no combined generator`);let s=i.parts.map(a=>a.partKey);return n.sort((a,l)=>s.indexOf(a.partKey)-s.indexOf(l.partKey))}o(HI,"groupRunsInOrder");function QI(t){return t.every(e=>e.status==="succeeded"&&e.contractId!==void 0&&e.contractSnapshotId!==void 0)}o(QI,"isCompleteGroup");var ob=200;function nK(t){let e=t.resolver?.parts;return e===void 0&&W(`groupChain: node "${t.id}" pins no combined generator \u2014 only a combined pin keeps a group chain`),e.map(n=>n.partKey)}o(nK,"groupPartKeys");async function rK(t,e,n){let r=await t.db.query("contract_generation_runs").withIndex("by_applicationId_and_workflowNodeId",i=>i.eq("applicationId",e).eq("workflowNodeId",n)).take(ob+1);return r.length>ob&&W(`groupChain: more than ${ob} generation runs on node ${n}`),r}o(rK,"nodeRuns");async function iK(t,e,n){let r=nK(n),i=new Set;for(let a of await rK(t,e,n.id))a.generationGroupId===void 0&&W(`groupChain: run ${a._id} on the combined node "${n.id}" carries no generation group`),i.add(a.generationGroupId);let s=[];for(let a of i){let l=await HI(t,a);if(!QI(l))continue;let d=[];for(let c of l){r.includes(c.partKey)||W(`groupChain: run ${c._id} renders part "${c.partKey}", which node "${n.id}"'s pin does not declare`);let u=await t.db.get(c.contractSnapshotId);u===null&&W(`groupChain: run ${c._id} names revision ${c.contractSnapshotId}, which is gone \u2014 a deleted draft lets its run go first`),d.push({run:c,snapshot:u})}s.push({generationGroupId:a,startedAt:Math.min(...l.map(c=>c._creationTime)),members:d})}return s.sort((a,l)=>a.startedAt-l.startedAt)}o(iK,"groupRevisionRows");async function oK(t,e){let n=new Map;for(let{snapshot:r}of e.members){let i=await rb(t,r._id);i!==null&&n.set(i._id,i)}return n.size>1&&W(`groupChain: generation group ${e.generationGroupId} is held by ${n.size} family Vorg\xE4nge \u2014 one Vorgang carries the group`),[...n.values()][0]??null}o(oK,"openGroupRequest");async function sK(t,e){let n=[];for(let i of await Jy(t,e._id)){let s=await t.db.system.get("_storage",i.storageId);s===null&&W(`groupChain: return ${e._id} holds missing file ${i.storageId}`),n.push({contractSnapshotId:i.contractSnapshotId,storageId:i.storageId,filename:i.filename,...s.contentType!==void 0?{mimeType:s.contentType}:{}})}let r=n[0];return{_id:e._id,_creationTime:e._creationTime,storageId:r.storageId,filename:r.filename,...r.mimeType!==void 0?{mimeType:r.mimeType}:{},round:e._id,documents:n}}o(sK,"toGroupReturn");function YI(t){async function e(r,i,s,a){let l=(await iK(r,i,t)).find(d=>d.members[0]?.snapshot._id===s);return l===void 0&&W(`${a}: ${s} is no revision of node "${t.id}"'s generation groups \u2014 corrupt arc`),l}return o(e,"revisionRowOf"),{reads:{kind:"group",async returned(r,i,s){if(s.askedAbout===void 0){if(s.onUnpinned==="notReturned")return null;W(`returned(${s.where}): an ask of the group chain is always pinned to its lead revision`)}let a=await e(r,i,s.askedAbout,`returned(${s.where})`),l=await oK(r,a);if(l===null)return null;let d=(await qu(r,l._id)).filter(c=>c.review.status==="pending"&&c._id!==s.rejected);return d.length>1&&W(`returned(${s.where}): Vorgang ${l._id} has ${d.length} returns pending \u2014 one is checked at a time`),d[0]===void 0?null:await sK(r,d[0])},pinOf(r){return r.contractSnapshotId},returnPinOf(r){return r.signingReturnId}},revisionRowOf:e}}o(YI,"groupNodeReads");function sb(t){return t.production==="none"&&W(`documentChainKind: node "${t.id}" has production 'none' \u2014 it keeps no document`),t.production!=="resolver"?"artifact":t.resolver?.parts!==void 0?"group":"contract"}o(sb,"documentChainKind");function JI(t){switch(sb(t)){case"contract":return Vu(t).reads;case"group":return YI(t).reads;case"artifact":return NI(t).reads}}o(JI,"documentReadsFor");var aK={de:"Haben Sie die Vertragsbedingungen gelesen und verstanden?",en:"Have you read and understood the contract terms?"};function za(t){let e=t.responseStrategy;return typeof e=="string"&&e in Or?Or[e].producesResponseArtifact:!1}o(za,"returnsSignedCopy");function lK(t){return za(t)&&t.confirmContractTerms!==!1}o(lK,"asksContractTerms");function ZI(t){return lK(t)?{title:t.contractTermsQuestionText??aK,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}o(ZI,"contractTermsConfirm");var XI=new Set([...Uy,di,zi,fr,Hi]),dK={id:_n,type:"legalEntity",label:wI,required:!0,inspector:"literal-only",optionSource:"tenantTraeger"};function cK(t,e){let n=`inputs.${_n}`,r=t.inputs?.[_n];if(r!==void 0&&r.kind==="binding")return[we(t,n,`[governedDocument/traegerNotLiteral] Knoten "${t.id}": der Tr\xE4ger ist ein fester Wert des Knotens, keine Bindung \u2014 w\xE4hlen Sie ihn aus.`)];if((t.resolver?.cockpitFields??[]).includes(_n))return[we(t,"resolver.cockpitFields",`[governedDocument/traegerInCockpit] Knoten "${t.id}": der Tr\xE4ger wird am Knoten festgelegt, nicht im Vorgang.`)];let i=kI(t),s=e?.resolverPrintsTraegerAddress?.get(t.id)??new Set,a=[];for(let l of new Set([...i===null?[]:[i],...s])){let d=e?.traeger?.get(l);e?.traeger!==void 0&&d===void 0?a.push(we(t,n,`[governedDocument/unknownTraeger] Knoten "${t.id}" nennt den Tr\xE4ger "${l}", den es in diesem Mandanten nicht gibt \u2014 bekannt: ${[...e.traeger.keys()].join(", ")||"(keiner)"}.`)):d!==void 0&&!d.hasAddress&&s.has(l)&&a.push(we(t,n,`[governedDocument/traegerAddressMissing] Die Vorlage des Generators an Knoten "${t.id}" druckt die Anschrift des Tr\xE4gers (${Vy.address}), aber "${l}" hat keine \u2014 in der Konfiguration des Mandanten nachtragen (foundation.legalEntities[].address).`))}return a}o(cK,"traegerIssues");function Ha(t){if(t.production==="template"){let n=t.template?.fields;return Array.isArray(n)?n:[]}if(t.production!=="resolver")return[];let e=t.resolver?.inputSchema?.fields;return Array.isArray(e)?e.map(n=>{let{label:r}=n;return r===void 0?{...n,label:{de:n.key,en:n.key}}:(Ur(r)||W(`governedDocument "${t.id}": the stamped generator parameter "${n.key}" has no { de, en } label (${JSON.stringify(r)}) \u2014 migrations.liftResolverSchemaTexts has not run on this deployment`),{...n,label:r})}):[]}o(Ha,"generatorFields");function lb(t){let e=t.production==="template"?t.template?.cockpitFields:t.resolver?.cockpitFields;return new Set(e??[])}o(lb,"cockpitFieldSet");function uK(t){return To(t.type)?t.type:void 0}o(uK,"resolverSlotType");function fK(t){if(t.confirmBeforeIssue!==!0||t.approval!=="none")return null;let e=Ga(t);return{confirm:{title:{de:`\u201E${e.de}\u201C jetzt senden?`,en:`Send "${e.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"}}}}o(fK,"issueConfirmation");function we(t,e,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.${e}`,reason:n,severity:"error"}}o(we,"issue");function Ku(t){return jy.includes(t.production)&&jo.includes(t.approval)&&Wy.includes(t.responseStrategy)}o(Ku,"hasValidModes");async function ab(t,e){let[n,r]=await Promise.all([t.db.query("work_items").withIndex("by_applicationId_and_nodeId",c=>c.eq("context.applicationId",e.applicationId).eq("context.nodeId",e.node.id)).collect(),t.db.query("work_items").withIndex("by_legacyApplicationId_and_nodeId",c=>c.eq("applicationId",e.applicationId).eq("nodeId",e.node.id)).collect()]),i=[...n,...r];if(i.length===0)return"pending";let s=i.filter(c=>c.isOpen).flatMap(c=>c.context?.kind==="admission"?[{...c,...c.context}]:c.applicationId===void 0?[]:[c]),a=s.filter(c=>c.templateKey!==void 0&&Uy.has(c.templateKey));if(a.length>0)return a.every(c=>c.status==="blocked")?"producingHeld":"producing";let l=s.find(c=>c.templateKey===di);if(l!==void 0)return l.status==="blocked"?"deferred":"awaitingApproval";if(s.some(c=>c.templateKey===Hi))return"signatureStalled";let d=s.find(c=>c.templateKey===zi);if(d!==void 0){if(ci(e.node).issuesBy==="provider"){let u=await Vu(e.node).contractOrNull(t,e.applicationId);if(u===null&&W(`governedDocCurrentState: eSignature node "${e.node.id}" has an open ask but no contract`),await zI(t,u)==="provider")return"awaitingSignature"}return ci(e.node).producesResponseArtifact?await PI(t,{chain:JI(e.node),applicationId:e.applicationId,ask:d,onUnpinned:"notReturned",where:`governedDocCurrentState(node "${e.node.id}")`})===null?"awaitingResponse":"responseReturned":"awaitingResponse"}return s.some(c=>c.templateKey===fr)?"responseInCheck":"done"}o(ab,"governedDocCurrentState");function e$(t){return t.production!=="none"&&sb(t)!=="artifact"}o(e$,"keepsDocumentInContractDomain");function pK(t,e){let n=t.inputs?.[e.key];if(n?.kind!=="binding")return[];let r=n.address;if(!Se(r)||r.scope!=="env"||!Ln(r.key))return[];let i=Mi(r.key);if(e.type!==i.type)return[we(t,`inputs.${e.key}`,`[governedDocument/envNotCovered] Feld "${e.key}" ist ${e.type}, die Umgebungsvariable \u201E${i.label.de}\u201C (${fe(r)}) liefert ${i.type}.`)];let s=new Set((e.options??[]).map(l=>l.value)),a=(i.enumOptions??[]).filter(l=>!s.has(l.value));return a.length===0?[]:[we(t,`inputs.${e.key}`,`[governedDocument/envNotCovered] Feld "${e.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.`)]}o(pK,"envCoverageIssues");function mK(t,e){if(e.localeField===void 0)return[we(t,"template.localeField",vI(t.id,e.key))];let n=e.fields.find(i=>i.key===e.localeField),r=n===void 0?"nennt kein Feld der Vorlage":n.type!=="enum"?`ist ${n.type}, erwartet wird ein Auswahlfeld (enum)`:n.required!==!0?"ist kein Pflichtfeld \u2014 ohne Sprache gibt es keine Variante":(n.options??[]).length===0?"hat keine Optionen":(n.options??[]).some(i=>!At.includes(i.value))?`hat Optionen, die keine Sprache sind (erlaubt: ${At.join(", ")})`:null;return r===null?[]:[we(t,"template.localeField",`[governedDocument/localeField] Das Sprachfeld "${e.localeField}" der Vorlage "${e.key}" ${r}.`)]}o(mK,"localeFieldIssues");function r$(t,e,n){let r=[],i=lb(t);for(let a of Ha(t)){if(a.type==="party"||a.type==="personList")continue;if(r.push(...pK(t,a)),a.processSource!==void 0){let c=t.inputs?.[a.key],u=c?.kind==="binding"?`eine Bindung an ${Se(c.address)?fe(c.address):JSON.stringify(c.address)}`:c?.kind==="literal"?"ein fester Wert":i.has(a.key)?`ein Eintrag in ${n}.cockpitFields`:null;u!==null&&r.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${t.id}.inputs.${a.key}`,reason:`[governedDocument/processSourceConflict] "${a.label.de}" wird vom Vorgang selbst gef\xFCllt (${a.processSource}), daneben steht ${u}. Eine der beiden Quellen bliebe wirkungslos \u2014 entferne die Verdrahtung.`,severity:"error"});continue}if(a.required!==!0)continue;let l=t.inputs?.[a.key];l?.kind==="binding"||l?.kind==="literal"||i.has(a.key)||a.defaultValue!==void 0||r.push({layer:"GRAPH",kind:"contractGap",path:`nodes.${t.id}.inputs.${a.key}`,reason:`[governedDocument/unsourcedRequiredField] Pflichtfeld "${a.label.de}" des Generators ${e} hat keine Quelle \u2014 binde es an ein Formular-Export-Feld, setze einen festen Wert oder erkl\xE4re es ausdr\xFCcklich als Cockpit-Eingabe (${n}.cockpitFields).`,severity:"error"})}let s=new Set(Ha(t).map(a=>a.key));for(let a of i)s.has(a)||s.size===0||r.push(we(t,`${n}.cockpitFields.${a}`,`[governedDocument/unknownCockpitField] ${n}.cockpitFields nennt "${a}", aber der Generator ${e} kennt kein solches Feld.`));return r}o(r$,"fieldSourceIssues");var t$=new Set(["string","email","tel","number","date","boolean","enum","pricedItem"]),n$=/^[a-z][a-z0-9_]*$/;function hK(t){let e=[],n=t.template;if(n===void 0||typeof n.key!="string"||n.key.length===0||!Array.isArray(n.fields))return e.push(we(t,"template",`[governedDocument/missingTemplatePin] Knoten "${t.id}" hat production 'template', nennt aber keine Vorlage \u2014 erwartet wird { key, fields } mit dem Schl\xFCssel (configKey) einer Dokumentvorlage.`)),e;let r=new Set;for(let i of n.fields){if(typeof i.key!="string"||!n$.test(i.key)||r.has(i.key)){e.push(we(t,`template.fields.${String(i.key)}`,`[governedDocument/templateFieldKey] Feld "${String(i.key)}" der Vorlage "${n.key}" ist ${r.has(i.key)?"doppelt":"kein g\xFCltiger Schl\xFCssel"} \u2014 erlaubt sind eindeutige Kleinbuchstaben, Ziffern und _ (gedruckt als input.<schl\xFCssel>).`));continue}if(r.add(i.key),!To(i.type)){e.push(we(t,`template.fields.${i.key}`,`[governedDocument/unknownFieldType] Vorlage "${n.key}" typisiert das Feld "${i.key}" als "${String(i.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${cg.join(", ")}).`));continue}if(t$.has(i.type)||e.push(we(t,`template.fields.${i.key}`,`[governedDocument/templateFieldType] Feld "${i.key}" der Vorlage "${n.key}" hat den Typ "${i.type}" \u2014 ein Brief druckt nur ${[...t$].join(", ")}.`)),i.type==="enum"&&Array.isArray(i.options)&&i.options.some(s=>!n$.test(String(s.value)))&&e.push(we(t,`template.fields.${i.key}`,`[governedDocument/templateFieldKey] Auswahlfeld "${i.key}" der Vorlage "${n.key}" hat Optionen, die kein Platzhalter adressieren kann (${i.options.map(s=>s.value).join(", ")}) \u2014 Optionswerte sind Kleinbuchstaben, Ziffern und _ (gedruckt als input.${i.key}.<option>).`)),i.type==="enum"&&(!Array.isArray(i.options)||i.options.length===0)&&e.push(we(t,`template.fields.${i.key}`,`[governedDocument/templateFieldOptions] Auswahlfeld "${i.key}" der Vorlage "${n.key}" nennt keine Optionen \u2014 ohne sie gibt es keine Abschnitte input.${i.key}.<option>.`)),i.type==="pricedItem"){let s=n.fields.find(a=>a.key===i.priceDate);(s===void 0||s.type!=="date")&&e.push(we(t,`template.fields.${i.key}`,`[governedDocument/templateFieldPriceDate] Preisfeld "${i.key}" der Vorlage "${n.key}" nennt kein Preisdatum \u2014 priceDate muss ein Datumsfeld derselben Vorlage sein (welche Preisversion gilt); genannt: ${JSON.stringify(i.priceDate)}.`))}else i.priceDate!==void 0&&e.push(we(t,`template.fields.${i.key}`,`[governedDocument/templateFieldPriceDate] Feld "${i.key}" setzt priceDate, ist aber kein Preisfeld (pricedItem).`));i.processSource!==void 0&&!Gy.includes(i.processSource)&&e.push(we(t,`template.fields.${i.key}`,`[governedDocument/unknownProcessSource] Feld "${i.key}" nennt die unbekannte Vorgangsquelle "${String(i.processSource)}" \u2014 bekannt sind ${Gy.join(", ")}.`))}return e.push(...mK(t,n)),e.push(...r$(t,`Vorlage "${n.key}"`,"template")),e}o(hK,"templateIssues");function gK(t,e){return(e?.resolverDocumentAnchors?.get(t.id)??[]).flatMap(n=>{if(n.documentAnchors===null)return[we(t,"resolver",`[governedDocument/eSignatureAnchorMissing] Knoten "${t.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage des Generators "${n.pin}" wurde nie auf Unterschriftsanker gelesen \u2014 Vorlage neu hochladen und den Generator neu versiegeln.`)];let r=n.signerAnchors.filter(i=>!n.documentAnchors.has(i));return r.length===0?[]:[we(t,"resolver",`[governedDocument/eSignatureAnchorMissing] Knoten "${t.id}" l\xE4sst elektronisch unterschreiben, aber die Vorlage von "${n.pin}" tr\xE4gt keinen Anker f\xFCr ${r.map(i=>`/unterschrift:${i}/`).join(", ")} \u2014 der Anbieter f\xE4nde f\xFCr diese Personen kein Unterschriftsfeld.`)]})}o(gK,"eSignatureAnchorIssues");function yK(t,e){return e===void 0||e.sendable?[]:ci(t).issuesBy!=="provider"?[]:[we(t,"responseStrategy",`[signing/noActiveProvider] Knoten "${t.id}" l\xE4sst elektronisch unterschreiben, aber die Schule kann nicht senden: ${e.reason}`)]}o(yK,"eSignatureProviderIssues");var i$={role:"user-action",effect:"side-effect",processHoldTemplate:o(()=>Ko,"processHoldTemplate"),progressEvents:["producing","issued"],notificationEvents:o(t=>[{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:o(t=>{if(!Ku(t))return[];let e=ci(t),n=[],r=e.producesResponseArtifact?["awaitingResponse","responseReturned"]:["awaitingResponse"],i=e.issuesBy==="provider"?["awaitingSignature","signatureStalled",...r]:r,s=e.checksReturn?[...i,"responseInCheck"]:i;return t.production!=="none"&&(n.push({id:zy(t),kind:"internal",surface:Uo,label:t.approval==="release"?{de:"Freigabe anfordern",en:"Request approval"}:{de:"Bereitstellen",en:"Issue document"},availableIn:["producing","producingHeld"],...fK(t)??{}}),n.push({id:EI,kind:"internal",surface:Uo,label:{de:"Korrigieren",en:"Correct"},availableIn:s,superUserOnly:!0},{id:RI,kind:"internal",surface:Uo,label:{de:"Zur\xFCckziehen & neu ausstellen",en:"Rescind & re-issue"},availableIn:s,superUserOnly:!0})),n.push(e.checksReturn?{id:Pu,kind:"internal",label:t.responseLabels?.accept??e.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"documentReturned"}}:{id:e.acceptOutcomeId,kind:"advance",outcome:e.acceptOutcomeId,label:t.responseLabels?.accept??e.defaultLabels.accept,availableIn:[r[r.length-1]],external:{emphasis:"primary",event:"userTaskResolved"}},{id:e.declineOutcomeId,kind:"advance",outcome:e.declineOutcomeId,label:t.responseLabels?.decline??e.defaultLabels.decline,availableIn:i,external:{emphasis:"decline",event:"userTaskResolved"}}),e.producesResponseArtifact&&n.push({id:Nu,kind:"internal",label:{de:"\xC4nderung anfordern",en:"Request a change"},availableIn:i,external:{emphasis:"secondary",event:"documentChangeRequested"}}),e.issuesBy==="provider"&&n.push({id:Du,kind:"internal",surface:Uo,label:{de:"Erneut senden",en:"Send again"},availableIn:["signatureStalled"]},{id:Fu,kind:"internal",surface:Uo,label:{de:"Auf Papier umstellen",en:"Switch to paper"},availableIn:["signatureStalled"]}),n},"actions"),states:TI,currentState:ab,workItemTemplates:o(t=>{let e=t;return Ku(e)?Hy(e):[]},"workItemTemplates"),taskDocuments:o((t,e)=>{let n=t;if(!Ku(n)||n.production==="none")return[];let r=Hy(n).find(i=>i.key===e);return r===void 0||r.recipient!=="internal"?[]:[{kind:"artifact",key:Mu(n)}]},"taskDocuments"),inputs:o(t=>[...t.production==="resolver"?[dK]:[],...Ha(t).filter(e=>e.type!=="party"&&e.type!=="personList").flatMap(e=>{let n=uK(e);return n===void 0?[]:[{field:e,type:n}]}).map(({field:e,type:n})=>({id:e.key,type:n,label:e.label,required:e.required===!0&&!lb(t).has(e.key),...e.defaultValue!==void 0&&(typeof e.defaultValue=="string"||typeof e.defaultValue=="number"||typeof e.defaultValue=="boolean"||e.defaultValue===null||n==="pricedItem"&&ni(e.defaultValue))?{defaultValue:e.defaultValue}:{},...e.options!==void 0?{enumOptions:e.options}:{}}))],"inputs"),outputs:o(t=>t.production==="none"?[]:[{name:Na,type:"documentRef",label:{de:"Dokument",en:"Document"}}],"outputs"),refuseBlocksTarget:o((t,e)=>{if(e===zi||e===Ka||e===fr||e===Hi){let n=e===zi?"die Antwort-Aufgabe geh\xF6rt dem Empf\xE4nger":e===fr?"die Pr\xFCfung des R\xFCcklaufs entsteht erst mit dem R\xFCcklauf der Familie":e===Hi?"die Kl\xE4rung der elektronischen Unterschrift entsteht erst, wenn sie nicht zustande kommt":"die \xDCberarbeitungs-Aufgabe entsteht nur durch eine Ablehnung";return`[governedDocument/blocksTarget] 'blocks' auf "${e}" (Knoten "${t.id}") ist verboten \u2014 ${n}; zul\xE4ssige intrinsische Ziele: ${Ko}${t.approval==="release"?`, ${di}`:""}.`}return e===di&&t.approval==="none"?`[governedDocument/blocksTarget] 'blocks' auf "${di}" auf Knoten "${t.id}" \u2014 mit approval 'none' existiert dieses Template nicht; der Blocker w\xFCrde ein Phantom aufschieben.`:null},"refuseBlocksTarget"),userUploadGate:o(async(t,e)=>{if(e$(e.node))return!1;let n=await ab(t,e),r=(n==="awaitingResponse"||n==="responseReturned")&&ci(e.node).producesResponseArtifact;return e.actor==="recipient"?r:n==="producing"&&e.node.production==="upload"||r},"userUploadGate"),userUploadConfirmation:o(async(t,e)=>{let n=ZI(e.node);if(n===null||e$(e.node))return null;let r=await ab(t,e);return r==="awaitingResponse"||r==="responseReturned"?n:null},"userUploadConfirmation"),validate:o((t,e,n)=>{let r=[];if(!Ku(t))return r.push(we(t,"modes",`[governedDocument/unknownMode] Knoten "${t.id}" deklariert keine g\xFCltige Betriebsart \u2014 erforderlich: production \u2208 {${jy.join(", ")}} (ist: ${JSON.stringify(t.production)}), approval \u2208 {${jo.join(", ")}} (ist: ${JSON.stringify(t.approval)}), responseStrategy \u2208 {${Wy.join(", ")}} (ist: ${JSON.stringify(t.responseStrategy)}). Eine Betriebsart ist eine erkl\xE4rte Entscheidung, nie aus der Verdrahtung abgeleitet.`)),r;let i=Or[t.responseStrategy];t.production==="none"&&(t.approval!=="none"||t.responseStrategy!=="confirm")&&r.push(we(t,"production",`[governedDocument/modeContract] Knoten "${t.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben und nichts zu unterschreiben: approval muss 'none' sein (ist: '${t.approval}') und responseStrategy 'confirm' (ist: '${t.responseStrategy}').`));let s=t.artifacts??[];if(t.production==="none")s.length!==0&&r.push(we(t,"artifacts",`[governedDocument/slotContract] Knoten "${t.id}" hat production 'none', deklariert aber ${s.length} Artefakt-Slot(s) \u2014 ein dokumentloser Best\xE4tigungs-Knoten verwaltet keinen Slot.`));else{s.length!==1&&r.push(we(t,"artifacts",`[governedDocument/slotContract] Knoten "${t.id}" deklariert ${s.length} Artefakt-Slots \u2014 genau EINER (das verwaltete Dokument) ist erforderlich.`));for(let w of s)w.visibility!=="external"&&r.push(we(t,"artifacts",`[governedDocument/slotContract] Slot "${w.key}" auf Knoten "${t.id}" hat visibility "${w.visibility}" \u2014 das verwaltete Dokument MUSS 'external' sein, sonst kann die bewerbende Person es auf /e nie sehen.`))}let a=t.outcomes??[],l=a.map(w=>w.id),d=[i.acceptOutcomeId,i.declineOutcomeId];(a.length!==2||!d.every(w=>l.includes(w)))&&r.push(we(t,"outcomes",`[governedDocument/outcomeContract] Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') muss genau ZWEI Outcomes deklarieren \u2014 das Accept-Terminal "${i.acceptOutcomeId}" und das Decline-Terminal "${i.declineOutcomeId}" (deklariert: ${l.length>0?l.map(w=>`"${w}"`).join(", "):"keine"}). Beide sind Pflicht: der Knoten besitzt die Antwort, nicht nur die Freigabe.`));let c=t.titles,u=o(w=>{let S=c?.[w];return S===null||typeof S!="object"||!Object.values(S??{}).some(A=>typeof A=="string"&&A.length>0)},"missingTitle"),f=[];t.production!=="none"&&f.push("prepare","revise"),t.approval==="release"&&f.push("approve"),i.checksReturn&&f.push("check");let h=f.filter(u);h.length>0&&r.push(we(t,"titles",`[governedDocument/missingTitles] Knoten "${t.id}" fehlen die Aufgaben-Titel ${h.join(", ")} \u2014 der Knotentyp ist dokument-agnostisch, die Betitelung ist Pflicht-Konfiguration seiner Betriebsart.`));let g=t.assign??{};if(t.production!=="none"){let w=g.prepareDocument;(typeof w!="string"||w.length===0)&&r.push(we(t,"assign.prepareDocument",`[governedDocument/productionAssign] Knoten "${t.id}" (production '${t.production}') verdrahtet kein Produzenten-Team (assign.prepareDocument) \u2014 ohne Producer-Aufgabe g\xE4be es die Submit-Aktion ohne freischaltendes Work-Item.`))}if(t.approval==="none"&&(g.releaseApproval!==void 0&&r.push(we(t,"assign.releaseApproval",`[governedDocument/deadWiring] Knoten "${t.id}" hat approval 'none', verdrahtet aber assign.releaseApproval \u2014 tote Verdrahtung darf nicht als konfiguriert durchgehen (Betriebsart explizit \xE4ndern statt Gruppen zuweisen).`)),c?.approve!==void 0&&r.push(we(t,"titles.approve",`[governedDocument/deadWiring] Knoten "${t.id}" hat approval 'none', deklariert aber titles.approve \u2014 es gibt keine Freigabe-Aufgabe, die diesen Titel tr\xFCge.`))),i.checksReturn){let w=g.responseCheck;(typeof w!="string"||w.length===0)&&r.push(we(t,"assign.responseCheck",`[governedDocument/checkAssign] Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') verdrahtet kein Team f\xFCr die Pr\xFCfung des R\xFCcklaufs (assign.responseCheck) \u2014 ohne Team l\xE4ge jeder R\xFCcklauf bei niemandem.`)),t.production!=="resolver"&&i.issuesBy==="provider"?r.push(we(t,"responseStrategy",`[governedDocument/eSignatureNeedsResolver] Knoten "${t.id}" l\xE4sst elektronisch unterschreiben (eSignature), erzeugt das Dokument aber mit production '${t.production}' \u2014 der Anbieter bekommt eine eingefrorene Vertragsrevision mit Unterschriftsankern und deklarierten Unterzeichnern, und die entsteht nur mit production 'resolver'.`)):t.production!=="resolver"&&r.push(we(t,"responseStrategy",`[governedDocument/checkNeedsContract] Knoten "${t.id}" pr\xFCft den R\xFCcklauf (signedUploadChecked), erzeugt das Dokument aber mit production '${t.production}' \u2014 die Pr\xFCfung hakt die unterzeichnenden Personen einer eingefrorenen Vertragsrevision ab, und die entsteht nur mit production 'resolver'.`))}else{t.production==="resolver"&&r.push(we(t,"responseStrategy",`[governedDocument/contractNeedsCheckedReturn] Knoten "${t.id}" erzeugt einen Vertrag (production 'resolver'), beantwortet ihn aber mit '${t.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).`));for(let[w,S]of[["assign.responseCheck",g.responseCheck!==void 0],["titles.check",c?.check!==void 0]])S&&r.push(we(t,w,`[governedDocument/deadWiring] Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') deklariert ${w} \u2014 eine Pr\xFCfung des R\xFCcklaufs gibt es nur mit responseStrategy 'signedUploadChecked' oder 'eSignature'.`))}if(i.issuesBy==="provider"){let w=g.signingRecovery;(typeof w!="string"||w.length===0)&&r.push(we(t,"assign.signingRecovery",`[governedDocument/recoveryAssign] Knoten "${t.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.`))}else g.signingRecovery!==void 0&&r.push(we(t,"assign.signingRecovery",`[governedDocument/deadWiring] Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') deklariert assign.signingRecovery \u2014 eine Kl\xE4rung der elektronischen Unterschrift gibt es nur mit responseStrategy 'eSignature'.`));if(i.issuesBy==="provider"&&r.push(...gK(t,n),...yK(t,n?.signingProvider)),t.confirmBeforeIssue!==void 0&&typeof t.confirmBeforeIssue!="boolean"?r.push(we(t,"confirmBeforeIssue",`[governedDocument/confirmBeforeIssue] Knoten "${t.id}" setzt confirmBeforeIssue auf ${JSON.stringify(t.confirmBeforeIssue)} \u2014 erlaubt ist nur true oder false.`)):t.confirmBeforeIssue===!0&&t.approval==="release"&&r.push(we(t,"confirmBeforeIssue",`[governedDocument/deadWiring] Knoten "${t.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'.`)),t.confirmContractTerms!==void 0&&typeof t.confirmContractTerms!="boolean"&&r.push(we(t,"confirmContractTerms",`[governedDocument/confirmContractTerms] Knoten "${t.id}" setzt confirmContractTerms auf ${JSON.stringify(t.confirmContractTerms)} \u2014 erlaubt ist nur true oder false.`)),za(t))t.confirmContractTerms===!1&&t.contractTermsQuestionText!==void 0&&r.push(we(t,"contractTermsQuestionText",`[governedDocument/deadWiring] Knoten "${t.id}" schaltet die Best\xE4tigung der Vertragsbedingungen ab (confirmContractTerms: false), formuliert aber die Frage um \u2014 ohne Best\xE4tigung wird sie nie gestellt.`));else for(let[w,S]of[["confirmContractTerms",t.confirmContractTerms!==void 0],["contractTermsQuestionText",t.contractTermsQuestionText!==void 0]])S&&r.push(we(t,w,`[governedDocument/deadWiring] Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') deklariert ${w} \u2014 die Best\xE4tigung der Vertragsbedingungen geh\xF6rt zum Hochladen der unterschriebenen Fassung, das es nur mit responseStrategy 'signedUpload' oder 'signedUploadChecked' gibt.`));if(t.production==="none")for(let[w,S]of[["confirmBeforeIssue",t.confirmBeforeIssue===!0],["assign.prepareDocument",g.prepareDocument!==void 0],["titles.prepare",c?.prepare!==void 0],["titles.revise",c?.revise!==void 0],["mockAutoProduce",t.mockAutoProduce!==void 0]])S&&r.push(we(t,w,`[governedDocument/deadWiring] Knoten "${t.id}" hat production 'none', deklariert aber ${w} \u2014 ohne Produktionsphase gibt es keinen Tr\xE4ger daf\xFCr.`));for(let w of t.tasks??[])XI.has(w.key)&&r.push(we(t,`tasks.${w.key}`,`[governedDocument/keyShadowsIntrinsic] Task-Key "${w.key}" auf Knoten "${t.id}" kollidiert mit einem intrinsischen Template (${[...XI].join(", ")}) \u2014 anderen Key w\xE4hlen.`));let b=t.mockAutoProduce?.sampleKey;if(t.mockAutoProduce!==void 0&&II.has(t.production)&&r.push(we(t,"mockAutoProduce",`[governedDocument/deadWiring] Knoten "${t.id}" hat production '${t.production}', deklariert aber mockAutoProduce \u2014 der Generator und das Muster-Dokument w\xFCrden um denselben Slot konkurrieren.`)),b!==void 0&&!Ky.includes(b)&&r.push(we(t,"mockAutoProduce.sampleKey",`[governedDocument/unknownSampleKey] Knoten "${t.id}" verweist auf das Musterdokument "${b}", das es nicht gibt \u2014 bekannte Schl\xFCssel: ${Ky.join(", ")}.`)),t.production==="resolver"?r.push(...cK(t,n)):t.inputs?.[_n]!==void 0&&r.push(we(t,`inputs.${_n}`,`[governedDocument/deadWiring] Knoten "${t.id}" hat production '${t.production}', nennt aber einen Tr\xE4ger \u2014 nur ein erzeugter Vertrag hat eine Vertragspartei der Schule.`)),t.production==="resolver"){let w=t.resolver;if(w===void 0||typeof w.key!="string"||w.key.length===0||typeof w.revision!="number")r.push(we(t,"resolver",`[governedDocument/missingResolverPin] Knoten "${t.id}" hat production 'resolver', pinnt aber keinen Generator \u2014 erwartet wird { key, revision } einer versiegelten Resolver-Revision.`));else{for(let S of Ha(t)){if(!To(S.type)){r.push(we(t,`resolver.inputSchema.${S.key}`,`[governedDocument/unknownFieldType] Generator "${w.key}@${w.revision}" typisiert das Feld "${S.key}" als "${String(S.type)}" \u2014 das geh\xF6rt nicht zum Wert-Vokabular der Plattform (${cg.join(", ")}). Die gepinnte Revision stammt aus einer \xE4lteren Fassung und muss neu versiegelt werden.`));continue}if(S.type==="personList"){r.push(we(t,`resolver.inputSchema.${S.key}`,`[governedDocument/partyListUnsupported] Generator "${w.key}@${w.revision}" deklariert das Feld "${S.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.`));continue}S.type==="party"&&(lb(t).has(S.key)||r.push(we(t,`resolver.inputSchema.${S.key}`,`[governedDocument/partyFieldNeedsCockpit] Generator "${w.key}@${w.revision}" deklariert das Party-Feld "${S.key}" \u2014 eine im Vorgang ausgew\xE4hlte Person. Kein Formularfeld kann eine Partei exportieren, also ist \`cockpitFields\` die einzige m\xF6gliche Quelle; ohne den Eintrag bliebe das Feld f\xFCr immer leer.`)),S.key.endsWith("PartyId")||r.push(we(t,`resolver.inputSchema.${S.key}`,`[governedDocument/partyFieldKey] Party-Feld "${S.key}" endet nicht auf "PartyId" \u2014 aus diesem Suffix wird der Platzhalter-Pr\xE4fix im Dokument abgeleitet (emergencyContactPartyId \u2192 emergency_contact).`)))}r.push(...r$(t,`"${w.key}@${w.revision}"`,"resolver"))}}else t.resolver!==void 0&&r.push(we(t,"resolver",`[governedDocument/deadWiring] Knoten "${t.id}" hat production '${t.production}', pinnt aber einen Generator \u2014 ohne maschinelle Produktion l\xE4uft er nie.`));t.production==="template"?r.push(...hK(t)):t.template!==void 0&&r.push(we(t,"template",`[governedDocument/deadWiring] Knoten "${t.id}" hat production '${t.production}', nennt aber eine Vorlage \u2014 ohne Vorlagen-Produktion wird sie nie gef\xFCllt.`));let y=t.responseDueInDays;return y!==void 0&&!Lu(y)&&r.push(we(t,"responseDueInDays",`[governedDocument/dueInDays] Knoten "${t.id}" setzt responseDueInDays auf ${JSON.stringify(y)} \u2014 erlaubt ist eine ganze Zahl von ${Ua} bis ${ja} Tagen.`)),y===void 0&&Ha(t).some(w=>w.processSource==="responseDueInDays")&&r.push(we(t,"responseDueInDays",`[governedDocument/dueInDays] Knoten "${t.id}" druckt die Antwortfrist (processSource 'responseDueInDays'), setzt aber kein responseDueInDays \u2014 das Dokument nennte eine Frist, die es nicht gibt.`)),r},"validate")};var db="countersign",cb="countersign",o$="countersigned",s$="countersigning",a$="countersigned",l$={de:"Vertrag gegenzeichnen",en:"Countersign the contract"};function Qa(t,e,n){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.${e}`,reason:n,severity:"error"}}o(Qa,"issue");function d$(t,e){return t.nodes.filter(n=>{let r=n.contract;return n.type==="countersign"&&Se(r)&&r.scope==="node"&&r.owner===e})}o(d$,"countersignersOf");function bK(t,e,n){if(n.scope!=="node")return[];let r=t.nodes.find(s=>s.id===n.owner);if(r===void 0)return[];let i=[];return OI(r)||i.push("sourceNotCheckedContract"),d$(t,r.id).some(s=>s.id!==e)&&i.push("twice"),i}o(bK,"countersignContractRefusals");var c$={role:"user-action",effect:"side-effect",outcomes:[{id:o$,label:{de:"Gegengezeichnet",en:"Countersigned"}}],progressEvents:[s$],notificationEvents:o(()=>[{id:a$,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:o(()=>[{id:cb,kind:"internal",label:l$,surface:cr}],"actions"),workItemTemplates:o(t=>[{key:db,recipient:"internal",title:t.titles?.countersign??Go,unlocks:[cb],advancesNode:!0,...t.dueInDays!==void 0?{dueInDays:t.dueInDays}:{}}],"workItemTemplates"),validate:o((t,e)=>{let n=[],r=t.assign?.[db];(typeof r!="string"||r.length===0)&&n.push(Qa(t,"assign",`[countersign/assign] \u201E${t.label?.de??t.id}": wer gegenzeichnet, fehlt \u2014 \`assign.countersign\` nennt das Team.`)),Ur(t.titles?.countersign)||n.push(Qa(t,"titles",`[countersign/missingTitle] \u201E${t.label?.de??t.id}": der Titel der Aufgabe fehlt \u2014 \`titles.countersign\` auf Deutsch und Englisch.`)),t.dueInDays!==void 0&&(!Number.isInteger(t.dueInDays)||t.dueInDays<1)&&n.push(Qa(t,"dueInDays",`[countersign/dueInDays] \u201E${t.label?.de??t.id}": dueInDays ist eine ganze Zahl \u2265 1.`));let i=t.contract;if(!Se(i))return n;let s=bK(e,t.id,i);if(s.length===0)return n;let a=e.nodes.find(l=>i.scope==="node"&&l.id===i.owner);if(s.includes("sourceNotCheckedContract")&&n.push(Qa(t,"contract",`[countersign/sourceNotCheckedContract] \u201E${t.label?.de??t.id}" zeichnet das Dokument von \u201E${a.label?.de??a.id}" (${a.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).`)),s.includes("twice")){let l=d$(e,a.id).filter(d=>d.id!==t.id);n.push(Qa(t,"contract",`[countersign/twice] \u201E${t.label?.de??t.id}": \u201E${a.label?.de??a.id}" (${a.id}) wird schon von ${l.map(d=>`"${d.id}"`).join(", ")} gegengezeichnet \u2014 ein Vertrag hat eine Gegenzeichnung.`))}return n},"validate")};var u$={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 gn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(gn,"isRecord");var f$=["field","join","literal","address","payment","contract"],wK=new Set(["text","date","datetime","bool","aifBool","money","moneyText"]),kK=new Set(["street","streetAndNumber","hausnr","plz","ort","land","full"]);function On(t){return typeof t=="string"&&t.trim().length>0}o(On,"nonEmptyString");function Uu(t,e,n,r,i="value"){if(!gn(t)||!gn(t.from)){r.push({path:e,code:"mappingShape",message:`${e}: eine Zuordnung braucht \`from\`.`});return}let s=t.from,a=f$.filter(c=>c in s);if(a.length!==1){r.push({path:e,code:"mappingShape",message:`${e}: \`from\` nennt genau eine Quelle (${f$.join(" | ")}).`});return}let[l]=a;l==="field"&&!On(s.field)&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.field\` ist leer.`}),l==="join"&&!(Array.isArray(s.join)&&s.join.length>=2&&s.join.every(On))&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.join\` nennt mindestens zwei Formularfelder.`}),t.whenEmpty!==void 0&&(i==="condition"?r.push({path:e,code:"mappingShape",message:`${e}: \`whenEmpty\` gilt nicht f\xFCr eine Bedingung (\`unless\`, \`linkAddressToPupilIf\`).`}):l!=="field"&&l!=="join"?r.push({path:e,code:"mappingShape",message:`${e}: \`whenEmpty\` gilt nur f\xFCr eine Formularantwort (\`field\`, \`join\`).`}):typeof t.whenEmpty=="boolean"||Number.isFinite(t.whenEmpty)||On(t.whenEmpty)||r.push({path:e,code:"mappingShape",message:`${e}: \`whenEmpty\` ist ein Engage-Wert (Text, Zahl oder ja/nein).`})),l==="address"&&!(Se(s.address)&&s.address.scope==="env"&&Ln(s.address.key))&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.address\` ist eine Umgebungsvariable (\`{ scope: 'env', key: 'stage.key' }\`).`}),l==="payment"&&s.payment!=="amount"&&s.payment!=="settledAt"&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.payment\` ist amount oder settledAt.`}),l==="contract"&&!["startDate","signedAt","createdAt"].includes(String(s.contract))&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.contract\` ist startDate, signedAt oder createdAt.`}),l==="literal"&&!["string","number","boolean"].includes(typeof s.literal)&&r.push({path:e,code:"mappingShape",message:`${e}: \`from.literal\` ist Text, Zahl oder ja/nein.`}),t.format!==void 0&&!wK.has(String(t.format))&&r.push({path:e,code:"mappingShape",message:`${e}: unbekanntes Format \u201E${String(t.format)}".`}),t.lookup!==void 0&&!(On(t.lookup)&&gn(n[t.lookup]))&&r.push({path:e,code:"unknownLookup",message:`${e}: die Lookup-Tabelle \u201E${String(t.lookup)}" fehlt in \`lookups\`.`});let d=t.pick;d!==void 0&&(d==="firstWord"||d==="restWords"||d==="year"||gn(d)&&Number.isInteger(d.index)&&Number(d.index)>=0||gn(d)&&kK.has(String(d.address))||r.push({path:e,code:"mappingShape",message:`${e}: unbekannte Auswahl \`pick\`.`}))}o(Uu,"checkMapping");function fi(t,e,n,r,i){if(!gn(t)){i.push({path:e,code:"bodyShape",message:`${e}: erwartet ein Objekt Feld \u2192 Zuordnung.`});return}let s=u$[n];for(let a of s.required)a in t||i.push({path:`${e}.${a}`,code:"missingRequired",message:`${e}: Engage verlangt \u201E${a}" (${s.body}) \u2014 es fehlt eine Zuordnung.`});for(let[a,l]of Object.entries(t))Uu(l,`${e}.${a}`,r,i)}o(fi,"checkBody");function p$(t,e,n,r){if(t===void 0)return;if(!Array.isArray(t)){r.push({path:e,code:"bodyShape",message:`${e}: erwartet eine Liste.`});return}let i=new Set;t.forEach((s,a)=>{let l=`${e}[${a}]`;if(!gn(s)||!On(s.fieldId)){r.push({path:l,code:"aifShape",message:`${l}: \`fieldId\` fehlt.`});return}i.has(s.fieldId)&&r.push({path:l,code:"aifDuplicate",message:`${l}: \u201E${s.fieldId}" doppelt.`}),i.add(s.fieldId),Uu(s.value,`${l}.value`,n,r),s.unless!==void 0&&Uu(s.unless,`${l}.unless`,n,r,"condition")})}o(p$,"checkAif");function ub(t){let e=[];if(!gn(t))return[{path:"engage",code:"missing",message:"Die Engage-Zuordnung `engage` fehlt."}];let n=gn(t.lookups)?t.lookups:{};gn(t.lookups)||e.push({path:"engage.lookups",code:"bodyShape",message:"`engage.lookups` fehlt (Tabellen Name \u2192 Plexus-Wert \u2192 Engage-Id)."});for(let[r,i]of Object.entries(n))(!gn(i)||!Object.values(i).every(On))&&e.push({path:`engage.lookups.${r}`,code:"lookupShape",message:`Lookup \u201E${r}": jede Engage-Id ist ein nicht leerer Text.`});if(On(t.addressFormatId)||e.push({path:"engage.addressFormatId",code:"missing",message:"`engage.addressFormatId` fehlt (GetAddressMappingInfo)."}),fi(t.pupil,"engage.pupil","addPupil",n,e),fi(t.admission,"engage.admission","addAdmissionDetails",n,e),t.nationality!==void 0&&fi(t.nationality,"engage.nationality","addNationality",n,e),t.visa!==void 0&&fi(t.visa,"engage.visa","addVisa",n,e),t.medical!==void 0&&fi(t.medical,"engage.medical","addMedical",n,e),p$(t.pupilAif,"engage.pupilAif",n,e),!Array.isArray(t.contacts))e.push({path:"engage.contacts",code:"bodyShape",message:"`engage.contacts` fehlt (Liste der Kontakte)."});else{let r=new Set;t.contacts.forEach((i,s)=>{let a=`engage.contacts[${s}]`;if(!gn(i)||!On(i.key)||!On(i.presentIf)){e.push({path:a,code:"contactShape",message:`${a}: \`key\` und \`presentIf\` fehlen.`});return}r.has(i.key)&&e.push({path:a,code:"contactDuplicate",message:`${a}: Kontakt \u201E${i.key}" doppelt.`}),r.add(i.key),fi(i.basic,`${a}.basic`,"addContact",n,e),i.address!==void 0&&fi(i.address,`${a}.address`,"addContactAddress",n,e);for(let[l,d]of[["emails","addContactEmail"],["telephones","addContactTelephone"]]){let c=i[l];if(c!==void 0){if(!Array.isArray(c)){e.push({path:`${a}.${l}`,code:"bodyShape",message:`${a}.${l}: erwartet eine Liste.`});continue}c.forEach((u,f)=>fi(u,`${a}.${l}[${f}]`,d,n,e))}}p$(i.aif,`${a}.aif`,n,e),i.linkAddressToPupilIf!==void 0&&Uu(i.linkAddressToPupilIf,`${a}.linkAddressToPupilIf`,n,e,"condition")})}if(t.siblingsAttending!==void 0){let r=t.siblingsAttending;(!gn(r)||!On(r.repeated)||!On(r.field)||!On(r.equals))&&e.push({path:"engage.siblingsAttending",code:"bodyShape",message:"`engage.siblingsAttending` braucht repeated, field und equals."})}return e}o(ub,"engagePushConfigIssues");function*fb(t){let e=[t.pupil,t.admission,t.nationality,t.visa,t.medical];for(let n of e)for(let r of Object.values(n??{}))yield{mapping:r};for(let n of t.pupilAif??[])yield{mapping:n.value},n.unless!==void 0&&(yield{mapping:n.unless});for(let n of t.contacts){let r=[n.basic,n.address,...n.emails??[],...n.telephones??[]];for(let i of r)for(let s of Object.values(i??{}))yield{mapping:s,contactKey:n.key};for(let i of n.aif??[])yield{mapping:i.value,contactKey:n.key},i.unless!==void 0&&(yield{mapping:i.unless,contactKey:n.key});n.linkAddressToPupilIf!==void 0&&(yield{mapping:n.linkAddressToPupilIf,contactKey:n.key})}}o(fb,"mappingsOf");function m$(t){let e=new Set(t.contacts.map(n=>n.presentIf));for(let{mapping:n,contactKey:r}of fb(t))for(let i of vK(n.from))e.add(SK(i,r));return[...e]}o(m$,"configFieldKeys");function vK(t){return"field"in t?[t.field]:"join"in t?t.join:[]}o(vK,"formFieldsOf");function SK(t,e){return t.startsWith(".")?(e===void 0&&W(`[engagePush] relative field "${t}" outside a contact`),`${e}${t}`):t}o(SK,"resolveFieldKey");function h$(t,e){for(let{mapping:n}of fb(t))if(e in n.from)return!0;return!1}o(h$,"configReadsSource");function g$(t){let e=new Set;for(let{mapping:n}of fb(t))"address"in n.from&&e.add(n.from.address.key);return[...e]}o(g$,"configEnvLeaves");var y$="done",b$=["sandbox","production"];var pb="engagePush",Ume=660*1e3;function pi(t,e,n,r="error"){return{layer:"GRAPH",kind:"nodeRule",path:`nodes.${t.id}.${e}`,reason:n,severity:r}}o(pi,"issue");function mb(t,e){let n=t.inputs?.[e];return n?.kind==="literal"?n.value:void 0}o(mb,"literal");function w$(t){return ub(t.engage).length===0?t.engage:null}o(w$,"validConfig");function xK(t,e){let n=new Map(t.nodes.map(a=>[a.id,a])),r=t.nodes.filter(a=>a.type==="eventTrigger"),i=new Set,s=r.map(a=>a.id);for(;s.length>0;){let a=s.pop();if(a===e||i.has(a))continue;i.add(a);let l=n.get(a);if(l!==void 0){if(l.type==="end"){let d=l.inputs?.applicationOutcome;if(d?.kind==="literal"&&d.value==="approved")return!0;continue}for(let d of Object.values(l.next??{})){let c=d?.to;typeof c=="string"&&s.push(c)}}}return!1}o(xK,"bypassingPath");var k$={role:"system-action",effect:"side-effect",outcomes:[{id:y$,label:{de:"Angesto\xDFen",en:"Started"}}],envReads:o(t=>{let e=w$(t);return e===null?[]:g$(e)},"envReads"),inputs:o(()=>[{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:o((t,e,n)=>{let r=t.label?.de??t.id,i=[],s=mb(t,"target");b$.includes(s)||i.push(pi(t,"inputs.target",`[engagePush/invalidTarget] \u201E${r}": das Ziel ist sandbox oder production.`));let a=mb(t,"contractFields");a!==void 0&&a!=="off"&&a!=="on"&&i.push(pi(t,"inputs.contractFields",`[engagePush/contractFields] \u201E${r}": Vertragsfelder sind off oder on.`));let l=t.assign?.[pb];(typeof l!="string"||l.length===0)&&i.push(pi(t,"assign",`[engagePush/assign] \u201E${r}": wer eine stehen gebliebene \xDCbertragung pr\xFCft, fehlt \u2014 \`assign.${pb}\` nennt das Team.`));for(let b of ub(t.engage))i.push(pi(t,b.path,`[engagePush/config] \u201E${r}": ${b.message}`));let d=e.nodes.filter(b=>b.id!==t.id&&b.type==="engagePush"&&mb(b,"target")===s);d.length>0&&i.push(pi(t,"inputs.target",`[engagePush/twice] \u201E${r}": ${d.map(b=>`"${b.id}"`).join(", ")} \xFCbertr\xE4gt schon an dasselbe Ziel.`)),xK(e,t.id)&&i.push(pi(t,"next",`[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.`));let c=w$(t),u=t;for(let[b,y,w]of[["contract","contract","Vertrag"],["payment","payment","Zahlung"]])c===null||!h$(c,b)||u[y]!==void 0||i.push(pi(t,y,Tu("address/missing",{where:`\u201E${r}\u201C \u203A ${w}`},"de")));let f=u.form,h=Se(f)&&f.scope==="node"?f.owner:void 0,g=h===void 0?void 0:n?.readinessFormFieldsByFormNode?.get(h);if(c!==null&&g!==void 0){let b=new Set(g.keys()),y=m$(c).filter(w=>!b.has(w)&&!/\[\d+\]\./.test(w));y.length>0&&i.push(pi(t,"engage",`[engagePush/unmappedField] \u201E${r}": diese Felder kennt das Formular \u201E${e.nodes.find(w=>w.id===h)?.label?.de??h}" nicht \u2014 sie werden nicht \xFCbertragen: ${y.join(", ")}.`,"warning"))}return i},"validate")};var Qi={join:kT,end:vT,roleAssign:xT,eventTrigger:AT,waitlist:UT,completenessCheck:lI,form:$T,setFlag:_T,if:OT,decision:oi,review:uI,collectPayment:bI,governedDocument:i$,countersign:c$,engagePush:k$};lT(Qi);function v$(t,e){let n=t;if(n==null||!Array.isArray(n.nodes))throw new Error(`offer plan: the ${e} carries no workflow graph with nodes`);return t}o(v$,"graphOf");function S$(t){let e=new Map;for(let n of t.nodes)for(let r of lr(t,n))e.set(fe(r.address),r.nodeId);return e}o(S$,"producedOf");function x$(t){let e=new Map;for(let n of t.nodes)e.set(n.id,new Set(ji(t,n).map(r=>fe(r.address))));return e}o(x$,"readsOf");function A$(t,e){let n=v$(t,"bundle"),r=v$(e.graph,"live head");vy(r);let i=S$(n),s=S$(r),a={added:[],removed:[],moved:[]};for(let[u,f]of i){let h=s.get(u);h===void 0?a.added.push({address:u,nodeId:f}):h!==f&&a.moved.push({address:u,from:h,to:f})}for(let[u,f]of s)i.has(u)||a.removed.push({address:u,nodeId:f});let l=x$(n),d=x$(r),c=[];for(let u of new Set([...l.keys(),...d.keys()])){let f=l.get(u)??new Set,h=d.get(u)??new Set,g=[...f].filter(y=>!h.has(y)),b=[...h].filter(y=>!f.has(y));(g.length>0||b.length>0)&&c.push({nodeId:u,added:g,removed:b})}return{headRevision:e.revision,pinnedApplications:e.pinnedApplications,produced:a,reads:c}}o(A$,"planAddresses");function E$(t){let e=[...t.produced.moved.map(i=>({icon:"~",target:`address:${i.address}`,status:`Knoten ${i.from} \u2192 ${i.to}`})),...t.produced.added.map(i=>({icon:"+",target:`address:${i.address}`,status:`neu (${i.nodeId})`})),...t.produced.removed.map(i=>({icon:"-",target:`address:${i.address}`,status:`entfernt (${i.nodeId})`})),...t.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(e.length===0)return[];let{real:n,test:r}=t.pinnedApplications;return e.push({icon:"!",target:"pinned",status:`${n+r} Anmeldungen (${n} echt, ${r} Test) auf Fassung ${t.headRevision} bleiben auf ihrer Version \u2014 Umpinnen nur per Migration mit Abbildung`}),e}o(E$,"addressPlanRows");function hb(t,e){return e==null?!0:Ue(t)!==Ue(e)}o(hb,"changed");async function R$(t,e,n){if(e.index.module!==Ia.name)throw new Error(`offer: unknown module "${e.index.module}"`);return eT(t,e,n,{afterManifestPublish:o(async()=>{if(e.index.links?.unitKey||e.index.program)return Ia.scaffold(t,e.index.slugs.manifest,e.index,{dryRun:n.dryRun??!1})},"afterManifestPublish")})}o(R$,"applyOffer");async function T$(t,e,n){let i=(await t.query(R.workflow.listManifests,{client:e})).find(b=>b.offerKey===n);if(!i)throw new Error(`offer: no offer family with key "${n}" in tenant "${e}"`);let{data:s}=await t.query(R.workflow.getManifestData,{offerVersionId:i.offerVersionId}),a=s;if(!a)throw new Error("offer: offer family has no data to export");let l=await Ia.exportExtras(t,e,i.offerKey),d={manifest:n},c,u,f,h=i.workflowDefinitionId;if(h){let b=await t.query(R.workflow.getWorkflowDef,{workflowDefinitionId:h});if(!b)throw new Error("offer: workflow def not found");let y=b.publishedVersion??b.draftVersion;if(!y)throw new Error("offer: workflow has no version to export");d.workflow=b.handle.key,f={graph:y.graph,progressWiring:y.progressWiring};let w=Ia.smartformSlugsFromWorkflow(y.graph);if(w.length>0){c={},u={};for(let S of w){let T=(await t.query(R.forms.getSmartFormBySlug,{client:e,offerVersionId:i.offerVersionId,slug:S}))?.def;if(!T)throw new Error(`offer: smartform "${S}" has no definition`);c[S]=T.definition,u[S]=T.outcomeFnRef?{outcomeFnRef:T.outcomeFnRef}:{}}}}return{index:{module:"admission",tenant:e,label:i.label,...i.sortOrder!==void 0?{sortOrder:i.sortOrder}:{},slugs:d,...u?{smartforms:u}:{},...l.unitKey?{links:{unitKey:l.unitKey}}:{},program:l.spec,pinned:{}},manifest:a,...c!==void 0?{smartforms:c}:{},...f!==void 0?{workflow:f}:{}}}o(T$,"exportOffer");async function gb(t,e){let{index:n}=e,i=(await t.query(R.workflow.listManifests,{client:n.tenant})).find(g=>g.offerKey===n.slugs.manifest),s="create";if(i){let{data:g}=await t.query(R.workflow.getManifestData,{offerVersionId:i.offerVersionId});s=hb(e.manifest,g)?"change":"same"}let a={};for(let[g,b]of Object.entries(e.smartforms??{})){let y=i?await t.query(R.forms.getSmartFormBySlug,{client:n.tenant,offerVersionId:i.offerVersionId,slug:g}):null;a[g]=y?.def?hb(b,y.def.definition)?"change":"same":"create"}let l="absent",d=null;if(e.workflow!==void 0){if(l="create",i?.workflowDefinitionId){let g=await t.query(R.workflow.getWorkflowDef,{workflowDefinitionId:i.workflowDefinitionId}),b=g?.publishedVersion??g?.draftVersion,y=b?{graph:b.graph,progressWiring:b.progressWiring}:void 0;l=hb({graph:Do(e.workflow.graph),progressWiring:e.workflow.progressWiring},y&&{graph:Do(y.graph),progressWiring:y.progressWiring})?"change":"same"}if(i){let g=await t.query(R.workflow.getOfferHeadPins,{client:n.tenant,offerKey:n.slugs.manifest});g!==null&&(d=A$(e.workflow.graph,g))}}let c=n.program?.stages,u=c===void 0?[]:i?await sy(t,n.tenant,n.slugs.manifest,c):uu(null,[],c),f=await gu(t,n.tenant,i?n.slugs.manifest:null,n),h=i?await t.query(R.workflow.getOfferPublishState,{client:n.tenant,offerKey:n.slugs.manifest}):null;return{manifest:s,smartforms:a,workflow:l,addresses:d,stages:u,capacities:f,publishPending:h?.draftDiffersFromExternal??null,draftRevision:h?.draftRevision??null,externalHeadRevision:h?.externalHeadRevision??null}}o(gb,"diffOffer");import{existsSync as AK,readFileSync as I$}from"node:fs";import mi from"node:path";import{createHash as EK}from"node:crypto";var yb=mi.join("contract","resolver-setup.json"),Cr="resolver setup",Wo=o((t,e)=>_t(t,e,Cr),"record"),Pr=o((t,e)=>Ge(t,e,Cr),"text");function RK(t,e){let n=Wo(t,"Datei"),r=Wo(n.contractTemplate,"contractTemplate"),i=Wo(n.resolver,"resolver");return{dir:e,contractTemplate:{key:Pr(r.key,"contractTemplate.key"),name:Zt(r.name,"contractTemplate.name",Cr,"Vorlagennamen"),file:Pr(r.file,"contractTemplate.file"),role:Pr(r.role,"contractTemplate.role")},revenueAccounts:Xd(n.revenueAccounts,Cr),billingItems:ec(n.billingItems,Cr),resolver:{key:Pr(i.key,"resolver.key"),name:Zt(i.name,"resolver.name",Cr,"Generatornamen"),description:i.description===void 0?null:Zt(i.description,"resolver.description",Cr,"Beschreibungen"),implementation:i.source===void 0?Pr(i.implementation,"resolver.implementation"):"",source:i.source===void 0?null:Pr(i.source,"resolver.source"),feeGroups:(i.feeGroups===void 0?[]:pn(i.feeGroups,"resolver.feeGroups",Cr)).map((s,a)=>{let l=Wo(s,`resolver.feeGroups[${a}]`);return{key:Pr(l.key,"feeGroup.key"),name:Zt(l.name,"feeGroup.name",Cr,"Geb\xFChrengruppen"),billingItemKeys:bb(l.billingItemKeys,"feeGroup.billingItemKeys")}}),billingItemKeys:bb(i.billingItemKeys??[],"resolver.billingItemKeys"),grantTemplateKeys:bb(i.grantTemplateKeys??[],"resolver.grantTemplateKeys"),scenarios:TK(i.scenarios??[]),config:Wo(i.config,"resolver.config")}}}o(RK,"parseResolverSetup");function bb(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"||n.trim()==="")||new Set(t).size!==t.length)throw new Error(`generator setup: ${e} must be a list of unique keys.`);return t}o(bb,"stringList");function TK(t){if(!Array.isArray(t)||t.length>20)throw new Error("generator setup: scenarios must be a list of at most 20 reviewed examples.");return t.map(e=>{let n=Wo(e,"scenario");if(!("input"in n)||!("expected"in n))throw new Error("generator setup: each scenario needs input and reviewed expected output.");return{key:Pr(n.key,"scenario.key"),input:n.input,expected:n.expected}})}o(TK,"parseScenarios");function Gu(t){let e=mi.resolve(t);return RK(JSON.parse(I$(e,"utf8")),mi.dirname(e))}o(Gu,"readResolverSetup");function IK(t,e){let n=t;for(let r of e.split(".")){if(typeof n!="object"||n===null||!(r in n))throw new Error(`resolver setup: resolver.config.${e} existiert nicht.`);n=n[r]}return n}o(IK,"configValue");function $$(t){let e=o(()=>Pr(t.resolver.config.lehrgangsbeginn,"resolver.config.lehrgangsbeginn"),"effectiveFrom"),n=new Set(t.billingItems.map(r=>r.key));return{revenueAccounts:t.revenueAccounts,catalogItemKeys:[...new Set([...wb(t.resolver.config),...t.resolver.billingItemKeys])].filter(r=>!n.has(r)),billingItems:t.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,s=typeof i=="object"&&i!==null&&typeof i.$config=="string"?IK(t.resolver.config,i.$config):i;if(typeof s!="number"||!Number.isFinite(s))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:s,currency:r.price.currency,effectiveFrom:e(),period:r.price.period}}})}}o($$,"billingSetupPayload");function _$(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=Object.entries(t);if(e.length!==1||e[0][0]!=="$billingItem")return;let n=e[0][1];if(typeof n!="string")throw new Error(`resolver setup: $billingItem ${JSON.stringify(n)} ist kein Schl\xFCssel.`);return n}o(_$,"billingItemRef");function wb(t){if(Array.isArray(t))return t.flatMap(wb);if(typeof t!="object"||t===null)return[];let e=_$(t);return e!==void 0?[e]:Object.values(t).flatMap(wb)}o(wb,"billingItemRefs");function kb(t,e,n={}){let r=o(i=>{if(Array.isArray(i))return i.map(r);if(typeof i=="object"&&i!==null){let s=Object.entries(i);if(s.length===1&&s[0][0]==="$grantTemplate"){let l=s[0][1];if(typeof l!="string"||n[l]===void 0)throw new Error(`generator setup: grant template ${String(l)} is not declared.`);return n[l]}let a=_$(i);if(a!==void 0){if(!(a in e))throw new Error(`resolver setup: $billingItem "${a}" ist weder in billingItems deklariert noch ein Katalogartikel.`);return e[a]}return Object.fromEntries(Object.entries(i).map(([l,d])=>[l,r(d)]))}return i},"walk");return r(t)}o(kb,"renderResolverConfig");function $K(t,e){let n=Array.isArray(t.documentPlaceholderKeys)?t.documentPlaceholderKeys:[],r=new Set(e.placeholders),i=new Set(n.map(String)),s=[...r].filter(l=>!i.has(l)),a=[...i].filter(l=>!r.has(l));if(s.length>0||a.length>0)throw new Error("resolver setup: resolver.config.documentPlaceholderKeys weicht vom DOCX ab"+(s.length>0?` \u2014 fehlt: ${s.join(", ")}`:"")+(a.length>0?` \u2014 nicht im DOCX: ${a.join(", ")}`:"")+". Liste aus dem DOCX \xFCbernehmen.")}o($K,"assertPlaceholderParity");function _K(t,e){return t.filter(n=>n.key===e.key&&n.status==="sealed"&&(e.sourceHash===void 0?n.implementationKey===e.implementationKey&&n.implementationChecksum===e.deployedChecksum:n.sourceHash===e.sourceHash&&Ue([...n.billingItemDefinitionIds??[]].sort())===Ue([...e.billingItemDefinitionIds??[]].sort())&&Ue([...n.grantTemplateIds??[]].sort())===Ue([...e.grantTemplateIds??[]].sort()))&&Ue(n.feeGroups??[])===Ue(e.feeGroups??[])&&n.contractTemplateId===e.contractTemplateId&&n.pinnedDocumentSha256===e.docSha256&&Ue(n.config)===Ue(e.config)).sort((n,r)=>r.revision-n.revision)[0]}o(_K,"matchingSealedRevision");function OK(t,e){if(t===void 0)return"erste Revision";let n=[];return t.status!=="sealed"&&n.push(`r${t.revision} ist ${t.status}`),e.sourceHash!==void 0?(Ue(t.feeGroups??[])!==Ue(e.feeGroups??[])&&n.push("Geb\xFChrengruppen"),t.sourceHash!==e.sourceHash&&n.push("Quelltext"),(Ue(t.billingItemDefinitionIds)!==Ue(e.billingItemDefinitionIds)||Ue(t.grantTemplateIds)!==Ue(e.grantTemplateIds))&&n.push("Artikel-/Erm\xE4\xDFigungsmanifest")):(t.implementationKey!==e.implementationKey||t.implementationChecksum!==e.deployedChecksum)&&n.push("Datenbank-Quellstand"),t.contractTemplateId!==e.contractTemplateId&&n.push("Vorlage"),t.pinnedDocumentSha256!==e.docSha256&&n.push("DOCX"),Ue(t.config)!==Ue(e.config)&&n.push("Config"),`weicht von r${t.revision} ab: ${n.join(", ")||"\u2014"}`}o(OK,"describeRevisionDrift");async function Ya(t,e,n){let r=await Ai(mi.join(n.dir,n.contractTemplate.file));$K(n.resolver.config,r);let i=await t.query(R.contractSetup.planBillingSetup,{client:e,...$$(n)}),s=i.rows.map(F=>({step:F.kind,target:F.key,action:F.action,detail:F.detail})),a=await t.query(R.contractSetup.contractTemplateState,{client:e,configKey:n.contractTemplate.key}),l=a===null||a.documentSha256!==r.sha256,d=!l&&a!==null&&!Jn(a.name,n.contractTemplate.name);s.push({step:"contractTemplate",target:n.contractTemplate.key,action:a===null?"create":l||d?"update":"same",detail:l?`${mi.basename(r.file)} hochladen (${r.placeholders.length} Platzhalter)`:d?`Name ${ju(a.name)} \u2192 ${ju(n.contractTemplate.name)}`:mi.basename(r.file)});let c=await t.query(R.contractGenerators.model,{client:e}),u=c.implementations.find(F=>F.key===n.resolver.implementation);if(n.resolver.source===null&&u===void 0)throw new Error(`resolver setup: Implementierung ${n.resolver.implementation} ist auf dieser Umgebung nicht in der Datenbank vorhanden (vorhanden: ${c.implementations.map(F=>F.key).join(", ")||"keine"}).`);let f=n.resolver.source===null?null:I$(mi.join(n.dir,n.resolver.source),"utf8"),h=n.resolver.grantTemplateKeys.length===0?null:await t.query(R.contractConfig.model,{client:e}),g={};for(let F of n.resolver.grantTemplateKeys){let x=h.grantTemplates.find(v=>v.configKey===F);if(x===void 0)throw new Error(`generator setup: grant template ${F} is not in this tenant's catalog.`);g[F]=x.id}let b=kb(n.resolver.config,i.billingItemIds,g),y=c.resolvers.filter(F=>F.key===n.resolver.key),w={key:n.resolver.key,implementationKey:n.resolver.implementation,deployedChecksum:u?.checksum??"",...f===null?{}:{sourceHash:EK("sha256").update(f).digest("hex"),billingItemDefinitionIds:n.resolver.billingItemKeys.map(F=>i.billingItemIds[F]??`not-created:${F}`),grantTemplateIds:Object.values(g),feeGroups:n.resolver.feeGroups.map(F=>({key:F.key,name:F.name,billingItemDefinitionIds:F.billingItemKeys.map(x=>i.billingItemIds[x]??`not-created:${x}`)}))},contractTemplateId:a?.contractTemplateId??null,docSha256:r.sha256,config:b},S=l?void 0:_K(y,w),A=[...y].sort((F,x)=>x.revision-F.revision)[0],T=y.find(F=>F.status==="draft");s.push(S!==void 0?{step:"resolver",target:`${S.key}@${S.revision}`,action:"same",detail:A!==void 0&&A.revision>S.revision?`versiegelt, entspricht der Datei \u2014 neuere r${A.revision} weicht ab und wird NICHT gepinnt`:"versiegelt, entspricht der Datei"}:{step:"resolver",target:`${n.resolver.key}@${T?.revision??(A?.revision??0)+1}`,action:"create",detail:T!==void 0?`vorhandenen Entwurf r${T.revision} mit der Datei \xFCberschreiben und versiegeln`:`neue Revision versiegeln (${OK(A,w)})`});let N=S!==void 0&&!CK(S,n.resolver);return N&&s.push({step:"resolverName",target:`${S.key}@${S.revision}`,action:"update",detail:`Name ${ju(S.name)} \u2192 ${ju(n.resolver.name)}`}),{rows:s,docx:r,billingItemIds:i.billingItemIds,template:{contractTemplateId:a?.contractTemplateId??null,documentTemplateId:a?.documentTemplateId??null,upload:l,rename:d},renderedConfig:b,match:S,renamed:N,description:T?.description??A?.description??{de:"",en:""},draft:T,source:f,grantTemplateIds:g}}o(Ya,"planResolverSetup");var ju=o(t=>`\u201E${t.de}\u201C / \u201E${t.en||"\u2014"}\u201C`,"nameLine"),CK=o((t,e)=>Jn(t.name,e.name)&&(e.description===null||Jn(t.description,e.description)),"sameResolverTexts");async function O$(t,e,n){let r=await Ya(t,e,n);if(r.rows.every(h=>h.action==="same"))return{rows:r.rows,pin:{key:r.match.key,revision:r.match.revision}};if(n.resolver.scenarios.length===0&&r.match===void 0)throw new Error("generator setup: a new revision requires reviewed scenarios. Add explicit input and expected output; use generator scenarios test to inspect results.");let i=await t.mutation(R.contractSetup.applyBillingSetup,{client:e,...$$(n)}),s=r.template.contractTemplateId;if(r.template.upload||r.template.rename){let h=r.template.upload?await ho(t,e,r.docx,{name:n.contractTemplate.name,role:n.contractTemplate.role}):r.template.documentTemplateId;s=(await t.mutation(R.contractSetup.ensureContractTemplate,{client:e,configKey:n.contractTemplate.key,name:n.contractTemplate.name,documentTemplateId:h})).contractTemplateId}let a=i.rows.map(h=>({step:h.kind,target:h.key,action:h.action,detail:h.detail})),l=r.rows.filter(h=>h.step==="contractTemplate"||h.step==="resolver"||h.step==="resolverName");if(r.match!==void 0&&!r.template.upload)return r.renamed&&await t.mutation(R.contractGenerators.rename,{client:e,id:r.match.id,name:n.resolver.name,description:n.resolver.description??r.match.description}),{rows:[...a,...l],pin:{key:r.match.key,revision:r.match.revision}};let d=kb(n.resolver.config,i.billingItemIds,r.grantTemplateIds),c=r.draft?.id;if(r.source===null&&r.draft!==void 0&&r.draft.implementationKey!==n.resolver.implementation)throw new Error(`resolver setup: ${n.resolver.key}@${r.draft.revision} ist ein Entwurf mit Implementierung ${r.draft.implementationKey}; erst \`resolver delete-draft ${n.resolver.key}@${r.draft.revision}\`.`);c===void 0&&(c=(await t.mutation(R.contractGenerators.createDraft,{client:e,key:n.resolver.key,name:n.resolver.name,...n.resolver.description===null?{}:{description:n.resolver.description},...r.source===null?{implementationKey:n.resolver.implementation}:{},contractTemplateId:s,config:d})).id),await t.mutation(R.contractGenerators.updateDraft,{client:e,id:c,config:d,contractTemplateId:s}),await t.mutation(R.contractGenerators.rename,{client:e,id:c,name:n.resolver.name,description:n.resolver.description??r.description});let u=await t.query(R.contractGeneratorAuthoring.source,{client:e,id:c});if(r.source!==null){let h=await t.action(R.contractGeneratorAuthoringActions.saveSource,{client:e,id:c,expectedSourceRevision:u.sourceRevision,source:r.source,billingItemDefinitionIds:n.resolver.billingItemKeys.map(g=>i.billingItemIds[g]),grantTemplateIds:Object.values(r.grantTemplateIds),feeGroups:n.resolver.feeGroups.map(g=>({key:g.key,name:g.name,billingItemDefinitionIds:g.billingItemKeys.map(b=>i.billingItemIds[b])}))});if(h.diagnostics.length>0)throw new Error(h.diagnostics.join(`
|
|
212
|
+
`));u=await t.query(R.contractGeneratorAuthoring.source,{client:e,id:c})}if(u.artifact===null)throw new Error("generator setup: save source before publishing.");await t.mutation(R.contractGeneratorAuthoring.approveScenarios,{client:e,id:c,expectedSourceRevision:u.sourceRevision,artifactHash:u.artifact.artifactHash,scenarios:kb({scenarios:n.resolver.scenarios},i.billingItemIds,r.grantTemplateIds).scenarios}),await t.mutation(R.contractGenerators.seal,{client:e,id:c});let f=await Ya(t,e,n);if(f.match===void 0)throw new Error(`resolver setup: die gerade versiegelte Revision entspricht der Datei nicht \u2014 ${f.rows.at(-1)?.detail}.`);return{rows:[...a,...l],pin:{key:f.match.key,revision:f.match.revision}}}o(O$,"applyResolverSetup");async function Wu(t,e,n){let r=mi.join(n.dir,yb);if(!AK(r)||n.workflow===void 0)return[];let i=Gu(r),s=(n.workflow.graph.nodes??[]).filter(l=>l.resolver?.key===i.resolver.key);if(s.length===0)return[];let a=await Ya(t,e,i);if(a.match===void 0)throw new Error(`offer: ${yb} hat auf dieser Umgebung keine passende versiegelte Revision (${a.rows.at(-1)?.detail}). Erst \`plexus-cli resolver setup apply --file ${r}\`.`);return s.map(l=>{let d=l.resolver.revision;return l.resolver={...l.resolver,revision:a.match.revision},{target:`resolver:${l.id}`,detail:`${i.resolver.key}@${a.match.revision} (aus ${yb}`+(d===a.match.revision?")":`; im Bundle nominell @${String(d)})`)}})}o(Wu,"pinSetupRevisions");var se=o((t,e)=>({de:t,en:e}),"lt"),C$={key:"bearbeitung",label:se("In Bearbeitung","In progress"),scope:"node"},PK={key:"pruefung",label:se("In Pr\xFCfung","In review"),scope:"node"},NK={key:"freigabe",label:se("Freigabe","Release"),scope:"node"},P$={key:"auswahl",label:se("Auswahl","Selection"),scope:"node"},vb={key:"warteliste",label:se("Warteliste","Waitlist"),scope:"global",track:"parked",waitlist:!0},DK={key:"vertrag",label:se("Vertrag","Contract"),scope:"node"},Sb={key:"unterlagen",label:se("Unterlagen nachreichen","Outstanding documents"),scope:"node"},FK={key:"eingeschrieben",label:se("Eingeschrieben","Enrolled"),scope:"global",defaultCollapsed:!0},N$={key:"abgesagt",label:se("Abgesagt","Declined"),scope:"global",track:"exit",defaultCollapsed:!0},LK={key:"abgelehnt",label:se("Abgelehnt","Rejected"),scope:"global",track:"exit",defaultCollapsed:!0},pt=o((t,e,n,r,i=null,s=null)=>({chipLabel:t,tone:e,nextAction:i,affordance:s,title:n,body:r}),"ex"),MK={started:{label:se("In Bearbeitung","In progress"),tone:"neutral",phase:C$,external:pt(se("Entwurf","Draft"),"neutral",se("Bewerbung fortsetzen","Continue application"),se("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."),se("Bewerbung fortsetzen","Continue application"),"continue-form")},submitted:{label:se("Eingereicht","Submitted"),tone:"blue",phase:C$,external:pt(se("Eingereicht","Submitted"),"blue",se("Ihre Bewerbung ist eingereicht","Your application has been submitted"),se("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."))},reviewing:{label:se("Eingereicht","Submitted"),tone:"blue",phase:PK,external:pt(se("Eingereicht","Submitted"),"blue",se("Ihre Bewerbung wird gepr\xFCft","Your application is being reviewed"),se("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."))},released:{label:se("Freigegeben","Released"),tone:"green",phase:NK,external:pt(se("Freigegeben","Released"),"green",se("Ihre Bewerbung wurde freigegeben","Your application has been released"),se("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."))},opened:{label:se("Auswahl offen","Selection open"),tone:"neutral",phase:P$,external:pt(se("In Auswahl","In selection"),"neutral",se("Ihre Bewerbung ist in der Auswahl","Your application is in selection"),se("Wir treffen derzeit die Auswahlentscheidung und informieren Sie, sobald sie vorliegt.","We are currently making the selection decision and will inform you as soon as it is made."))},accepted:{label:se("Angenommen","Accepted"),tone:"green",phase:P$,external:pt(se("Angenommen","Accepted"),"green",se("Ihre Bewerbung wurde angenommen","Your application has been accepted"),se("Wir freuen uns, Ihnen einen Platz anbieten zu k\xF6nnen.","We are pleased to offer you a place."))},waitlisted:{label:se("Warteliste","Waitlisted"),tone:"amber",phase:vb,external:pt(se("Warteliste","Waiting list"),"amber",se("Sie stehen auf der Warteliste","You are on the waiting list"),se("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."))},rejected:{label:se("Abgelehnt","Rejected"),tone:"red",phase:LK,external:pt(se("Abgelehnt","Rejected"),"red",se("Leider k\xF6nnen wir Ihnen keinen Platz anbieten","Unfortunately we cannot offer you a place"),se("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."))},promoted:{label:se("Nachger\xFCckt","Promoted"),tone:"green",phase:vb,external:pt(se("Nachger\xFCckt","Moved up"),"green",se("Sie sind nachger\xFCckt","You have moved up"),se("Es ist ein Platz frei geworden \u2014 Ihre Bewerbung l\xE4uft weiter.","A place has become available \u2014 your application continues."))},closed:{label:se("Warteliste geschlossen","Waitlist closed"),tone:"red",phase:vb,external:pt(se("Warteliste geschlossen","Waiting list closed"),"red",se("Die Warteliste wurde geschlossen","The waiting list has been closed"),se("Leider ist kein Platz mehr frei geworden.","Unfortunately no place has become available."))},contractIssued:{label:se("Vertrag erstellt","Contract issued"),tone:"blue",phase:DK,external:pt(se("Vertrag bereit","Contract ready"),"blue",se("Ihr Vertrag steht bereit","Your contract is ready"),se("Bitte pr\xFCfen und unterzeichnen Sie Ihren Vertrag.","Please review and sign your contract."),se("Vertrag unterzeichnen","Sign the contract"),"sign-contract")},interviewing:{label:se("Interview-Stage","Interview stage"),tone:"blue",phase:{key:"interview",label:se("Interview","Interview"),scope:"node"},external:pt(se("Gespr\xE4ch","Interview"),"blue",se("Wir laden Sie zum Gespr\xE4ch ein","We invite you to an interview"),se("Wir stimmen einen Gespr\xE4chstermin mit Ihnen ab.","We will arrange an interview date with you."))},awaitingPayment:{label:se("Zahlung ausstehend","Awaiting payment"),tone:"amber",phase:{key:"zahlung",label:se("Zahlung","Payment"),scope:"node"},external:pt(se("Zahlung offen","Payment due"),"amber",se("Bitte begleichen Sie die Anmeldegeb\xFChr","Please pay the application fee"),se("Ihre Bewerbung l\xE4uft weiter, sobald die Zahlung bei uns eingegangen ist.","Your application continues as soon as we have received the payment."))},awaitingDocuments:{label:se("Unterlagen nachreichen","Outstanding documents"),tone:"amber",phase:Sb,external:pt(se("Unterlagen fehlen","Documents missing"),"amber",se("Bitte reichen Sie die fehlenden Unterlagen nach","Please submit the missing documents"),se("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."))},documentsComplete:{label:se("Unterlagen vollst\xE4ndig","Documents complete"),tone:"green",phase:Sb,external:pt(se("Unterlagen vollst\xE4ndig","Documents complete"),"green",se("Ihre Unterlagen sind vollst\xE4ndig","Your documents are complete"),se("Alle angeforderten Unterlagen liegen uns vor. Vielen Dank.","We have received all the requested documents. Thank you."))},closedWithoutDocuments:{label:se("Ohne Nachreichung abgeschlossen","Closed without documents"),tone:"neutral",phase:Sb,external:pt(se("Abgeschlossen","Closed"),"neutral",se("Die Nachreichung ist abgeschlossen","The document request is closed"),se("Wir haben die Anforderung der Unterlagen abgeschlossen. Ihre Bewerbung l\xE4uft weiter.","We have closed the document request. Your application continues."))},withdrawn:{label:se("Zur\xFCckgezogen","Withdrawn"),tone:"red",phase:N$,external:pt(se("Zur\xFCckgezogen","Withdrawn"),"red",se("Sie haben Ihre Bewerbung zur\xFCckgezogen","You have withdrawn your application"),se("Ihre Bewerbung wird nicht weitergef\xFChrt.","Your application will not be continued."))},countersigning:{label:se("Gegenzeichnung","Countersignature"),tone:"teal",phase:{key:"gegenzeichnung",label:se("Gegenzeichnung","Countersignature"),scope:"node"},external:pt(se("Vertrag unterschrieben","Contract signed"),"blue",se("Die Schule zeichnet Ihren Vertrag gegen","The school is countersigning your contract"),se("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."))},enrolled:{label:se("Eingeschrieben","Enrolled"),tone:"green",terminal:{lifecycleStatus:"completed",outcome:"approved"},phase:FK,external:pt(se("Eingeschrieben","Enrolled"),"green",se("Sie sind eingeschrieben!","You are enrolled!"),se("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:se("Abgesagt","Declined"),tone:"red",terminal:{lifecycleStatus:"completed",outcome:"rejected"},phase:N$,external:pt(se("Abgesagt","Declined"),"red",se("Die Bewerbung wurde beendet","The application has ended"),se("Ihre Bewerbung wurde nicht fortgef\xFChrt.","Your application was not continued."))}};function qK(t){if(t.label===void 0)return;let e=t.label;if(typeof e!="object"||e===null||typeof e.de!="string"||typeof e.en!="string")throw new Error(`node "${t.id}": label ${JSON.stringify(t.label)} is not a { de, en } text`);return{de:e.de,en:e.en}}o(qK,"nodeText");function Ja(t,e){let n=[],r=[],i=[],s={},a=[],l=e.progressEvents??[],d=qK(t);for(let c of l){let u=`${t.id}.${c}`,f=MK[c],h=t.type==="decision"&&c==="released"&&d!==void 0,g=h?d:f?f.label:{de:c,en:""},b=f?f.tone:"neutral";f||a.push(`node "${t.id}" (${t.type}) emits progress-event "${c}" with no default \u2014 using event name + neutral tone`);let y={id:u,label:g,tone:b};f&&(y.external=f.external),f?.terminal&&(y.terminal=!0),n.push(y),r.push({match:{nodeId:t.id},event:c,bus:"process",state:u});let w=f?f.phase:{key:c,label:{de:c,en:""},scope:"node"},S=BK(w,t.id),A=i.find(T=>T.id===S);if(A)A.states=[...A.states,u],f?.optional||delete A.optional;else{let T={id:S,label:h?g:w.label,tone:b,states:[u]};f?.optional&&(T.optional=!0),w.track&&(T.track=w.track),w.defaultCollapsed&&(T.defaultCollapsed=!0),w.waitlist&&(T.waitlist=!0),i.push(T)}f?.terminal&&(s[u]=f.terminal)}return{states:n,mappings:r,columns:i,terminalSemantics:s,warnings:a}}o(Ja,"deriveProgressEntriesForNode");function zu(t){return Object.entries(t).filter(([,e])=>e.outcome==="approved").map(([e])=>e)}o(zu,"seatedTerminalStates");function BK(t,e){return t.scope==="global"?`col.${t.key}`:`${e}.${t.key}`}o(BK,"columnIdFor");function D$(t,e){let n=o(i=>(i.states??[]).some(s=>e.terminalStateIds.has(s)),"isTerminal"),r=o(i=>{let s=e.columnNodeId(i);return(s!==void 0?e.nodeOrder.get(s):void 0)??Number.POSITIVE_INFINITY},"topoOf");return t.map((i,s)=>({c:i,idx:s,term:n(i)?1:0,topo:r(i)})).sort((i,s)=>i.term-s.term||i.topo-s.topo||i.idx-s.idx).map(i=>i.c)}o(D$,"orderProcessColumns");var F$=o(t=>t,"asEffectId"),pr=o(t=>t,"asOutcomeId"),zo=o(t=>t,"asSectionId"),Bt=o(t=>t,"asFieldKey");var yn=o((t,e)=>({de:t,en:e}),"lt"),Ab=Ao("start",[]),Hu=Ao("form",[Ab]),xb=Ao("end",[Ab,Hu]);function VK(t){let e=[Ja({id:Hu,type:"form",label:yn("Formular","Form")},Qi.form),Ja({id:xb,type:"end",label:yn("Ende","End")},Qi.end)],n=[],r=[],i=[],s={};for(let c of e){n.push(...c.states),i.push(...c.mappings),s={...s,...c.terminalSemantics};for(let u of c.columns){let f=r.find(h=>h.id===u.id);f?f.states=[...new Set([...f.states,...u.states])]:r.push(u)}}let a=zu(s),l={id:`layout.${t}.starter`,buses:[{key:"process",states:n,terminalSemantics:s,holdsSeat:a,commitsSeat:a,boards:[{id:"prozess",label:yn("Prozess","Process"),audience:"both",columns:r}]}]},d={layoutId:l.id,mappings:i};return{layout:l,wiring:d}}o(VK,"buildStarterProgress");function L$(t){let{slug:e,title:n,tenant:r,unit:i,responsible:s}=t,a=e,l=`${e}-form`,d=`${e}-flow`,c={id:d,label:n,version:"1.0",versionNote:"Scaffold \xB7 single-form linear offer",category:"process",nodes:[{id:Ab,type:"eventTrigger",label:yn("Start","Start"),sublabel:yn("Eingang externer Bewerber-Aktion","Incoming external applicant action"),outcomes:[{id:"bewerbungOffen",label:yn("Bewerbungsfenster offen","Application window open")}],next:{bewerbungOffen:{to:Hu}}},{id:Hu,type:"form",label:n,sublabel:yn("Bewerbungsformular","Application form"),inputs:{smartForm:{kind:"literal",value:l}},outcomes:[{id:"standard",label:yn("Standard","Standard")}],next:{standard:{to:xb}}},{id:xb,type:"end",label:yn("Ende \xB7 Angenommen","End \xB7 Accepted"),inputs:{terminalStatus:{kind:"literal",value:"active"},applicationOutcome:{kind:"literal",value:"approved"},dataDecision:{kind:"literal",value:"commit"},terminationKind:{kind:"literal",value:"process_ends"}}}]};c.assignmentRules=mR([{slot:"responsible",rules:[{when:Ki,assign:{kind:"creator"}},{when:null,assign:{kind:"person",configKey:s}}]}],Xc(c));let{layout:u,wiring:f}=VK(d),h={id:zo("section.applicant"),label:yn("Antragsteller","Applicant"),fields:[{key:Bt("applicant.vorname"),label:yn("Vorname","First name"),kind:"control",type:"string",required:!0,bucket:"applicant"},{key:Bt("applicant.nachname"),label:yn("Nachname","Last name"),kind:"control",type:"string",required:!0,bucket:"applicant"}]},g=[{id:pr("standard"),label:yn("Standard","Standard"),when:"true",output:{fields:[{path:Bt("applicant.vorname")},{path:Bt("applicant.nachname")}],includeForm:!0}}],b={id:l,label:n,sections:[h],effects:[],outcomeIds:[pr("standard")],outcomes:g},y={id:a,label:n,version:1,applicantMode:"both",signatureLevel:"FES",bewerbungsfenster:{start:"2026-01-01",end:"2026-12-31"},capacity:20,leistungen:[],roleInstances:[],progressLayoutId:u.id,progressLayout:u};return{index:{module:"admission",tenant:r,label:n,slugs:{manifest:a,workflow:a},smartforms:{[l]:{outcomeFnRef:"admission.generic"}},...i?{links:{unitKey:i}}:{}},manifest:y,smartforms:{[l]:b},workflow:{graph:c,progressWiring:f}}}o(L$,"buildSkeletonBundle");function Qu(t){return t.filter(e=>(e.severity??"error")==="error")}o(Qu,"blockingIssues");var M$={approved:"enrolled",rejected:"declined",withdrawn:"declined",expired:"declined"},Yi=Object.keys(M$);function Yu(t){return Object.hasOwn(M$,t)}o(Yu,"isEndNodeOutcome");var Ji=["commit","discard"],ige=D.union(...Ji.map(t=>D.literal(t)));function Ju(t){return typeof t=="string"&&Ji.includes(t)}o(Ju,"isApplicationDataDecision");function Zu(t,e){let n=t.buses.find(r=>r.key===e);return n||W(`[progress] layout '${t.id}' has no bus '${e}'`),n}o(Zu,"progressBus");function Za(t,e){return t.states.some(n=>n.id===e)}o(Za,"isBusState");function q$(t,e){return!!t.terminalSemantics&&Object.prototype.hasOwnProperty.call(t.terminalSemantics,e)}o(q$,"hasTerminalSemantics");function KK(t,e){return(t.boards??[]).find(n=>n.audience===e||n.audience==="both")??null}o(KK,"boardForAudience");function B$(t){return KK(Zu(t,"process"),"internal")}o(B$,"internalProcessBoard");function Xu(t,e,n){let r=null;for(let i of t.mappings)if(i.event===n)if("nodeId"in i.match){if(i.match.nodeId===e.id)return{bus:i.bus,state:i.state}}else i.match.nodeType===e.type&&(r=i);return r?{bus:r.bus,state:r.state}:null}o(Xu,"resolveProgressEvent");function V$(t){let e=je(t);return typeof e.inputs=="function"?e.inputs(t):[]}o(V$,"inputSlots");function UK(t,e){return V$(t).find(n=>n.id===e)}o(UK,"findInputSlot");function jK(t,e){let n=UK(t,e);if(!n)return{source:"missing",spec:{id:e,label:{de:e,en:e},type:"string"},unknownSlot:!0};let r=t.inputs?.[e]??{kind:"unset"};return r.kind==="binding"&&Se(r.address)?{source:"binding",spec:n,address:r.address}:r.kind==="literal"?{source:"literal",spec:n,value:r.value}:n.defaultValue!==void 0?{source:"default",spec:n,value:n.defaultValue}:n.required?{source:"missing",spec:n}:{source:"optional",spec:n}}o(jK,"resolveInput");function K$(t){return V$(t).filter(e=>jK(t,e.id).source==="missing")}o(K$,"missingRequiredInputs");var GK=["personRef","formRef","documentRef","docRef"];function WK(t){let e=je(t);return typeof e.inputs!="function"?[]:e.inputs(t).map(n=>({id:n.id,type:n.type}))}o(WK,"listInputs");function U$(t){let e=[];for(let n of t.nodes)for(let r of WK(n))!GK.includes(r.type)||n.inputs?.[r.id]?.kind!=="literal"||e.push({layer:"GRAPH",kind:"modelError",path:`node.${n.id}.param.${r.id}`,reason:`${n.label.de}: Literal f\xFCr referenztypisierten Slot "${r.id}" ist verboten \u2014 der Slot wird an eine Adresse gebunden`,severity:"error"});return e}o(U$,"findParamValueRefSlotErrors");function j$(t){let e=[];for(let n of t.nodes)for(let r of K$(n))e.push({layer:"GRAPH",kind:"contractGap",path:`node.${n.id}.input.${r.id}`,reason:`${n.label.de}: Pflicht-Slot "${r.label.de}" nicht gesetzt`,severity:"error"});return e}o(j$,"findMissingRequiredInputs");function ef(t){let e=t.processStore;return e===void 0?[]:(Array.isArray(e)||W("graph.processStore must be an array \u2014 the graph validator refuses anything else"),e)}o(ef,"processStoreKeys");function W$(t){let e=[];for(let n of t.tasks??[]){let r=n.result;if(!(r===void 0||!Lo(r)))for(let i of bu(r))e.push({key:i.key,nodeId:t.id,taskKey:n.key,template:n,result:r,valueType:i.valueType,...i.field!==void 0?{fieldKey:i.field.key}:{}})}return e}o(W$,"storeWritersOn");function z$(t){let e=new Map;for(let n of t.nodes)for(let r of W$(n)){let i=e.get(r.key)??[];i.push(r),e.set(r.key,i)}return e}o(z$,"processStoreWriters");function zK(t,e,n){for(let r of t.nodes){let i=W$(r).find(s=>s.taskKey===e&&s.key===n);if(i!==void 0)return i}return null}o(zK,"writerAt");function G$(t,e,n){(e.scope!=="task"||e.path!==void 0)&&W(`[process] ${n}: ${fe(e)} is no task value`);let r=zK(t,e.owner,e.key);return r===null&&W(`[address/ownerNotWriter] ${n}: task "${e.owner}" writes no "${e.key}" \u2014 publish refuses that`),{key:e.key,nodeId:r.nodeId,taskKey:r.taskKey,...r.fieldKey!==void 0?{fieldKey:r.fieldKey}:{}}}o(G$,"sourceOfAddress");function Eb(t,e){(e.scope!=="task"&&e.scope!=="derived"||e.path!==void 0)&&W(`[process] ${fe(e)} is no store address`);let n=ef(t).find(s=>s.key===e.key);n===void 0&&W(`[address/unknownKey] ${fe(e)}: "${e.key}" is not declared in processStore`);let r={key:n.key,type:n.type,label:n.label,audience:n.audience};if(e.scope==="task")return dy(n)&&W(`[address/unknownKey] ${fe(e)}: "${e.key}" is a derived price \u2014 read it as $derived`),{...r,sources:[G$(t,e,fe(e))]};dy(n)||W(`[address/unknownKey] ${fe(e)}: "${e.key}" is a written value \u2014 read it as $task`);let i=cy(t,n.derive).map(s=>G$(t,s.address,fe(e)));return{...r,sources:i,derive:n.derive}}o(Eb,"processLeafOf");var H$=new Set(["enum","pricedItem","number","boolean","reduction"]),Q$=new Set(["pricedItem","pricedGroup"]),Y$=new Set(["number","boolean","enum"]),Ce={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 Ne(t,e){return{layer:"GRAPH",kind:"contractGap",path:t,reason:e,severity:"error"}}o(Ne,"err");function J$(t,e={}){let n=[],r=ef(t),i=new Map(r.map(d=>[d.key,d])),s=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)){n.push(Ne(u,`${Ce.invalidKey} Vorgangs-Schl\xFCssel ${JSON.stringify(c.key)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`));continue}s.has(c.key)&&n.push(Ne(u,`${Ce.invalidKey} Vorgangs-Schl\xFCssel "${c.key}" ist doppelt deklariert.`)),s.add(c.key),(c.derive!==void 0?!Q$.has(c.type):!H$.has(c.type))&&n.push(Ne(u,c.derive!==void 0?`${Ce.derive} Vorgangs-Schl\xFCssel "${c.key}" ist abgeleitet, hat aber den Typ "${c.type}" \u2014 abgeleitet wird nur ein Preis: ${[...Q$].join(", ")}.`:`${Ce.invalidKey} Vorgangs-Schl\xFCssel "${c.key}" hat den Typ "${c.type}" \u2014 der Vorgang speichert nur Ergebnisse mit Wert: ${[...H$].join(", ")}${c.type==="pricedGroup"?" (ein Paket wird abgeleitet: derive)":""}.`)),(!c.label?.de?.trim()||!c.label?.en?.trim())&&n.push(Ne(u,`${Ce.invalidKey} Vorgangs-Schl\xFCssel "${c.key}" braucht ein Label in beiden Sprachen.`)),c.audience!=="internal"&&c.audience!=="printable"&&n.push(Ne(u,`${Ce.invalidKey} Vorgangs-Schl\xFCssel "${c.key}": audience muss 'internal' oder 'printable' sein.`))}let a=z$(t);for(let d of t.nodes)for(let c of d.tasks??[]){let u=c.result;u?.kind==="pricedItem"&&u.writes===void 0&&n.push(Ne(`node.${d.id}.tasks.${c.key}.result.writes`,`${Ce.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.`))}for(let[d,c]of a){let u=i.get(d);for(let f of c){let h=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){n.push(Ne(h,`${Ce.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).`));continue}if(f.valueType!==u.type){let g=f.fieldKey===void 0?`Aufgabe "${f.taskKey}"`:`Feld "${f.fieldKey}" der Aufgabe "${f.taskKey}"`;n.push(Ne(h,`${Ce.writerTypeMismatch} ${g} liefert ${f.valueType}, der Vorgangs-Schl\xFCssel "${d}" ist aber als ${u.type} deklariert.`))}}c.length>1&&n.push(Ne(`processStore.${d}`,`${Ce.secondWriter} Vorgangs-Schl\xFCssel "${d}" wird ${c.length}-mal geschrieben (${c.map(f=>`${f.nodeId}/${f.taskKey}${f.fieldKey===void 0?"":`.${f.fieldKey}`}`).join(", ")}) \u2014 genau ein Schreiber je Schl\xFCssel.`))}for(let d of r){if(d.derive!==void 0){a.has(d.key)&&n.push(Ne(`processStore.${d.key}`,`${Ce.derivedHasWriter} Vorgangs-Schl\xFCssel "${d.key}" wird abgeleitet (derive) \u2014 keine Aufgabe darf ihn schreiben (${a.get(d.key).map(c=>`${c.nodeId}/${c.taskKey}`).join(", ")}).`));continue}a.has(d.key)||n.push(Ne(`processStore.${d.key}`,`${Ce.noWriter} Vorgangs-Schl\xFCssel "${d.key}" ist deklariert, aber keine Aufgabe schreibt ihn ('result.writes').`))}n.push(...HK(t,r,a,e));let l=new Map;for(let d of t.nodes){let c=je(d),u=typeof c.inputs=="function"?c.inputs(d):[];for(let f of u){let h=d.inputs?.[f.id];if(h?.kind!=="binding")continue;let g=QK(t,h.address);if(g===null)continue;let b=`node.${d.id}.input.${f.id}`,y=fe(h.address);for(let S of g.sources){let A=l.get(S.key)??new Set;A.add(d.id),l.set(S.key,A)}if(g.audience==="internal"&&n.push(Ne(b,`${Ce.internalInDocument} ${d.label.de}: "${f.id}" liest den internen Vorgangs-Schl\xFCssel "${g.key}" \u2014 ein Dokument dieses Knotens geht an die Familie; nur 'printable'-Schl\xFCssel d\xFCrfen hinein.`)),g.derive!==void 0)continue;let w=YK(a,g.sources[0].key,g.sources[0].taskKey);if(w.template.when!==void 0&&f.required===!0&&f.defaultValue===void 0&&n.push(Ne(b,`${Ce.absentWithoutDefault} ${d.label.de}: "${f.id}" ist Pflicht und an ${y} gebunden, aber die schreibende Aufgabe entsteht nur unter einer Bedingung (when: ${Z$(w.template.when)}) \u2014 ohne Vorgabewert bliebe das Feld dann f\xFCr immer leer.`)),w.result.kind==="pricedItem"&&f.defaultValue!==void 0){let S=f.defaultValue;(!ni(S)||S.itemKey!==w.result.item||S.grantKeys.length>0)&&n.push(Ne(b,`${Ce.defaultItemMismatch} ${d.label.de}: der Vorgabewert von "${f.id}" muss der Artikel der schreibenden Aufgabe ohne Erm\xE4\xDFigung sein ({ itemKey: '${w.result.item??"?"}', grantKeys: [] }) \u2014 sonst rechnete die Familie ohne Antrag einen anderen Artikel als mit.`))}}}for(let[d,c]of l){let u=a.get(d)[0],f=u.template.blocks,h=f===void 0?void 0:f.node??u.nodeId,g=h!==void 0&&c.has(h)&&(()=>{let y=t.nodes.find(w=>w.id===h);return y!==void 0&&je(y).processHoldTemplate?.(y)===f.templateKey})(),b=`node.${u.nodeId}.tasks.${u.taskKey}.blocks`;if(!g){let y=[...c][0],w=t.nodes.find(A=>A.id===y),S=je(w).processHoldTemplate?.(w)??"?";n.push(Ne(b,`${Ce.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: { ${y===u.nodeId?"":`node: '${y}', `}templateKey: '${S}' }, sonst arbeitet er, bevor der Wert existiert.`));continue}for(let y of c)y===h||Iu(t,h,y)||n.push(Ne(b,`${Ce.writerMustBlock} "${y}" liest "${d}", liegt aber nicht hinter dem zur\xFCckgehaltenen Knoten "${h}" \u2014 auf einem Weg an ihm vorbei l\xE4se er den Wert, bevor er feststeht.`))}return n}o(J$,"processBindingIssues");function HK(t,e,n,r){let i=[],s=new Map(e.map(u=>[u.key,u])),a=ku(t),l=new Set;for(let[u,f]of a.entries()){let h=`pricingRules[${u}]`;if((typeof f.key!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(f.key)||l.has(f.key))&&i.push(Ne(h,`${Ce.ruleSet} Regelgruppe ${JSON.stringify(f.key)} \u2014 ein eindeutiger Schl\xFCssel aus Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`)),l.add(f.key),(!f.label?.de?.trim()||!f.label?.en?.trim())&&i.push(Ne(h,`${Ce.ruleSet} Regelgruppe "${f.key}" braucht ein Label in beiden Sprachen.`)),!Array.isArray(f.rows)||f.rows.length===0){i.push(Ne(h,`${Ce.ruleSet} Regelgruppe "${f.key}" hat keine Zeilen.`));continue}for(let[g,b]of f.rows.entries()){let y=`${h}.rows[${g}]`;(!Array.isArray(b.grants)||b.grants.length===0||b.grants.some(S=>typeof S!="string"||S.length===0))&&i.push(Ne(y,`${Ce.ruleSet} Regelgruppe "${f.key}", Zeile ${g+1}: nennt keine Rabattvorlage \u2014 eine Zeile ohne Rabatt ist die fehlende Zeile.`));let w=$a(b.when);if(w!==null){i.push(Ne(y,`${Ce.ruleCondition} Regelgruppe "${f.key}", Zeile ${g+1}: Bedingung ${JSON.stringify(b.when)} \u2014 ${w}.`));continue}for(let{identifier:S,address:A}of gy(b.when)){if(A===null)continue;let T=JK(A,s,n);if(T==="ruleSource")i.push(Ne(y,`${Ce.ruleSource} Regelgruppe "${f.key}", Zeile ${g+1}: liest ${S} \u2014 eine Bedingung liest nur Werte, die eine Aufgabe schreibt ($task.<aufgabe>.<schl\xFCssel>), vom Typ ${[...Y$].join(", ")}.`));else if(T==="ruleReadsAbsent"){let N=n.get(A.key).find(F=>F.taskKey===A.owner);i.push(Ne(y,`${Ce.ruleReadsAbsent} Regelgruppe "${f.key}" liest ${S}, dessen Aufgabe entfallen kann (${N.template.when!==void 0?`when: ${Z$(N.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.`))}}}}for(let u of e){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(Ne(f,`${Ce.absentValue} Vorgangs-Schl\xFCssel "${u.key}" (${u.type}): absentValue ${JSON.stringify(u.absentValue)} passt nicht zum Typ.`));continue}let g=n.get(u.key)?.[0];g!==void 0&&!X$(g)&&i.push(Ne(f,`${Ce.absentValue} Vorgangs-Schl\xFCssel "${u.key}": seine Aufgabe ist immer geschuldet und \xFCberlebt ihren Knoten \u2014 ein absentValue w\xFCrde nie gelesen.`))}let d=[];for(let u of e){let f=u.derive;if(f===void 0)continue;let h=`processStore.${u.key}.derive`,g=u.type==="pricedGroup"?"group":"item",b=[f.item,f.group,f.byStage].filter(F=>F!==void 0).length,y=uy(f),w=f.byStage??[];(b!==1||y.length===0||y.length!==Math.max(w.length,1)||y.some(F=>F.kind!==g))&&i.push(Ne(h,`${Ce.derive} "${u.key}" (${u.type}) leitet ${g==="group"?"ein Paket ab: genau 'group' oder 'byStage' mit je einem 'group'":"einen Artikel ab: genau 'item' oder 'byStage' mit je einem 'item'"}.`));let S=new Set;for(let[F,x]of w.entries()){if(!Array.isArray(x.stages)||x.stages.length===0){i.push(Ne(`${h}.byStage[${F}]`,`${Ce.derive} "${u.key}": die Zeile ${F+1} nennt keine Stufe.`));continue}for(let v of x.stages)S.has(v)&&i.push(Ne(`${h}.byStage[${F}]`,`${Ce.derive} "${u.key}": die Stufe "${v}" steht in mehr als einer Zeile \u2014 welcher Preis gilt, w\xE4re geraten.`)),S.add(v)}let A=new Set;for(let F of f.rules??[]){let x=a.find(v=>v.key===F);if(x===void 0){i.push(Ne(h,`${Ce.derive} "${u.key}" nennt die Regelgruppe "${F}", die der Workflow nicht deklariert (bekannt: ${a.map(v=>v.key).join(", ")||"keine"}).`));continue}for(let v of x.rows??[])for(let P of v.grants??[])A.add(P)}let T=f.reduction;Se(T)&&(ZK(T,s)||i.push(Ne(h,`${Ce.derive} "${u.key}": Reduktion ${fe(T)} ist kein von einer Aufgabe geschriebener Wert vom Typ reduction ($task.<aufgabe>.<schl\xFCssel>).`)));for(let F of y)d.push({key:u.key,target:F,grants:A}),(F.kind==="item"?r.billingItemKeys?.has(F.key):r.groupArticleKeys?.has(F.key))===!1?i.push(Ne(h,`${Ce.derivePriceUnknown} "${u.key}": ${F.kind==="item"?"der Artikel":"das Paket"} "${F.key}" ist nicht im Katalog des Mandanten.`)):r.offerProgram===null?i.push(Ne(h,`${Ce.derivePriceOfferWithoutProgram} "${u.key}": das Angebot ist keinem Programm zugeordnet, also geh\xF6rt ${F.kind==="item"?"kein Artikel":"kein Paket"} zu ihm; dem Angebot ein Programm geben.`)):r.offerProgram!==void 0&&((F.kind==="item"?r.offerProgram.billingItemKeys:r.offerProgram.groupKeys).has(F.key)||i.push(Ne(h,`${Ce.derivePriceNotInProgram} "${u.key}": ${F.kind==="item"?"der Artikel":"das Paket"} "${F.key}" ist dem Programm \u201E${r.offerProgram.nameDe}\u201C des Angebots nicht zugeordnet${F.kind==="group"?" oder wird nicht angeboten":""} (unter Finanzen \u2192 Artikel zuordnen).`)));let N=r.offerProgram?.stageKeys;if(f.byStage!==void 0&&N!==void 0){let F=[...S].filter(v=>!N.all.has(v));F.length>0&&i.push(Ne(h,`${Ce.deriveStageUnknown} "${u.key}": ${F.map(v=>`"${v}"`).join(", ")} ist keine Stufe des Programms \u201E${r.offerProgram.nameDe}\u201C (Stufen: ${[...N.all].join(", ")||"keine"}).`));let x=[...N.active].filter(v=>!S.has(v));x.length>0&&i.push(Ne(h,`${Ce.deriveStageUncovered} "${u.key}": f\xFCr ${x.map(v=>`"${v}"`).join(", ")} nennt byStage keinen ${g==="group"?"Paket":"Artikel"} \u2014 diese Stufe h\xE4tte keinen Preis.`))}}for(let u of n.values())for(let f of u){if(f.result.kind!=="reduction"||f.result.prices===void 0||f.result.writes===void 0)continue;let h=`node.${f.nodeId}.tasks.${f.taskKey}.result.prices`,b=s.get(f.result.prices)?.derive?.reduction;Se(b)&&b.scope==="task"&&b.owner===f.taskKey&&b.key===f.result.writes||i.push(Ne(h,`${Ce.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.`))}let c=r.grantTemplates;if(c!==void 0){let u=new Set(a.flatMap(f=>(f.rows??[]).flatMap(h=>h.grants??[])));for(let f of u){let h=c.get(f);if(h===void 0){i.push(Ne("pricingRules",`${Ce.ruleGrantUnknown} Eine Regelgruppe vergibt "${f}", aber keine Rabattvorlage des Mandanten tr\xE4gt diesen Schl\xFCssel.`));continue}d.some(({target:b,grants:y})=>{if(!y.has(f))return!1;if(b.kind==="item")return h.itemKeys.includes(b.key);let w=r.groupArticleKeys?.get(b.key);return h.itemKeys.some(S=>w?.has(S))})||i.push(Ne("pricingRules",`${Ce.ruleGrantUnused} Die Rabattvorlage "${f}" (gebunden an Artikel "${h.itemKeys.join(", ")}") wird vergeben, aber kein abgeleiteter Preis, der ihre Regelgruppe liest, enth\xE4lt ihr Ziel \u2014 sie wirkte nirgends.`))}}return i}o(HK,"derivedPriceIssues");function QK(t,e){if(!Se(e)||e.scope!=="task"&&e.scope!=="derived"||e.path!==void 0)return null;let n=ef(t).find(s=>s.key===e.key);if(n===void 0||e.scope==="derived"!=(n.derive!==void 0))return null;if(e.scope==="task")return dr(t,e.owner,e.key)===null?null:Eb(t,e);let r=aT(t,n.derive),i=o(s=>s.scope==="task"&&s.path===void 0&&dr(t,s.owner,s.key)!==null,"resolvable");return r!==null&&r.every(s=>i(s.address))?Eb(t,e):null}o(QK,"draftLeafOf");function YK(t,e,n){let r=t.get(e)?.find(i=>i.taskKey===n);return r===void 0&&W(`[process] the leaf of "${e}" names task "${n}", which does not write it`),r}o(YK,"writerOf");function Z$(t){return Se(t)?fe(t):JSON.stringify(t)}o(Z$,"shown");function JK(t,e,n){let r=t.scope==="task"&&t.path===void 0?e.get(t.key):void 0;if(t.scope==="task"&&t.path===void 0&&r===void 0)return null;if(t.scope!=="task"||r===void 0||r.derive!==void 0||!Y$.has(r.type))return"ruleSource";let i=n.get(r.key)?.find(s=>s.taskKey===t.owner);return i!==void 0&&X$(i)&&r.absentValue===void 0?"ruleReadsAbsent":null}o(JK,"ruleSourceRefusal");function ZK(t,e){let n=t.scope==="task"&&t.path===void 0?e.get(t.key):void 0;return n!==void 0&&n.type==="reduction"&&n.derive===void 0}o(ZK,"isReductionValue");function X$(t){return t.template.when!==void 0||t.template.blocks?.node===void 0}o(X$,"writerMayBeNotOwed");function Rb(t){let e=je(t);return t.outcomes&&t.outcomes.length>0?[...t.outcomes]:e.outcomes&&e.outcomes.length>0?[...e.outcomes]:null}o(Rb,"nodeOutcomes");var e_=[{key:"tenantSlug",type:"string"}];var t_="subject";var ht={key:"schoolName",label:"Name der Schule"},n_={de:"Zu Ihren Bewerbungen",en:"View your applications"},mt={key:"portalLink",label:"Link zum Bewerberportal",required:!0,link:!0,actionLabel:n_},Tb={key:mt.key,label:mt.label,link:!0,actionLabel:n_},r_={key:"authorName",label:"Name der schreibenden Person"},Xa={key:"applicationLink",label:"Link zur Bewerbung",required:!0,link:!0,actionLabel:{de:"Bewerbung \xF6ffnen",en:"Open application"}},tf={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"}},i_={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"}},Ho={key:"gueltigkeit",label:"G\xFCltigkeitsdauer des Links",previewValue:{de:"24 Stunden",en:"24 hours"}};function Me(t){return{key:t_,label:"Betreff",default:t}}o(Me,"subjectSlot");var el=D.object({de:D.string(),en:D.string()}),Tt={tenantSlug:D.string(),applicationId:D.id("applications")},XK=D.object({tenantSlug:D.string()}),Jge={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:XK,channels:["email"],portalVisible:!0,placeholders:[ht,mt],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:
|
|
213
|
+
|
|
214
|
+
{{portalLink}}`,en:`Thank you for registering with {{schoolName}}. You can view and continue your applications at any time using the link below:
|
|
215
|
+
|
|
216
|
+
{{portalLink}}`}}]},eU=D.object({tenantSlug:D.string(),confirmPath:D.string()}),Zge={id:"applicant.applicationStarted",category:"login",label:"Bewerbung begonnen",occasion:{de:"Sobald eine Familie eine Bewerbung mit einer neuen E-Mail-Adresse beginnt",en:"As soon as a family starts an application with a new e-mail address"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:eU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[i_,Ho],slots:[Me({de:"Ihre Bewerbung \u2014 bitte E-Mail-Adresse best\xE4tigen",en:"Your application \u2014 please confirm your email address"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`Sie haben soeben eine Bewerbung bei uns begonnen. Bitte best\xE4tigen Sie einmal Ihre E-Mail-Adresse \u2014 ohne diesen Klick k\xF6nnen Sie die Bewerbung sp\xE4ter nicht absenden:
|
|
217
|
+
|
|
218
|
+
{{bestaetigungsLink}}
|
|
219
|
+
|
|
220
|
+
Sie k\xF6nnen in Ruhe weiter ausf\xFCllen; das Fenster, in dem Sie gerade arbeiten, bleibt dabei offen. Der Link gilt {{gueltigkeit}}.
|
|
221
|
+
|
|
222
|
+
M\xF6chten Sie sp\xE4ter auf einem anderen Ger\xE4t weitermachen? \xD6ffnen Sie dort die Bewerbungsseite und geben Sie diese E-Mail-Adresse ein \u2014 Sie bekommen dann einen Anmeldelink. Ein Passwort brauchen Sie nicht.
|
|
223
|
+
|
|
224
|
+
Wenn Sie keine Bewerbung begonnen haben, k\xF6nnen Sie diese E-Mail ignorieren; ohne Best\xE4tigung passiert nichts weiter.`,en:`You have just started an application with us. Please confirm your email address once \u2014 without this step you will not be able to submit your application later:
|
|
225
|
+
|
|
226
|
+
{{bestaetigungsLink}}
|
|
227
|
+
|
|
228
|
+
You can carry on filling in the form in your own time; the window you are working in stays open. The link is valid for {{gueltigkeit}}.
|
|
229
|
+
|
|
230
|
+
Would you like to continue later on another device? Open the application page there and enter this email address \u2014 you will then receive a sign-in link. You do not need a password.
|
|
231
|
+
|
|
232
|
+
If you did not start an application, you can ignore this email; nothing further happens without confirmation.`}}]},tU=D.object({tenantSlug:D.string(),callbackPath:D.string()}),Xge={id:"applicant.applicationParked",category:"login",label:"Bewerbung wartet",occasion:{de:"Wenn eine Bewerbung mit einer Adresse begonnen wird, zu der es schon ein Konto gibt",en:"When an application is started with an address that already has an account"},audience:"external",frame:"letter",timeline:"hidden",paramsValidator:tU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[tf,Ho],slots:[Me({de:"Eine Bewerbung wartet auf Sie",en:"An application is waiting for you"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`mit Ihrer E-Mail-Adresse wurde eine Bewerbung begonnen. Sie haben bei uns bereits ein Konto \u2014 melden Sie sich hier an, dann liegt die begonnene Bewerbung darin bereit:
|
|
233
|
+
|
|
234
|
+
{{anmeldeLink}}
|
|
235
|
+
|
|
236
|
+
Ein Passwort brauchen Sie nicht. Der Link gilt {{gueltigkeit}}.
|
|
237
|
+
|
|
238
|
+
Haben Sie selbst keine Bewerbung begonnen, ignorieren Sie diese E-Mail \u2014 die begonnene Bewerbung wird dann nicht in Ihr Konto \xFCbernommen.`,en:`An application has been started using your email address. You already have an account with us \u2014 sign in here and the application will be waiting in your account:
|
|
239
|
+
|
|
240
|
+
{{anmeldeLink}}
|
|
241
|
+
|
|
242
|
+
You do not need a password. The link is valid for {{gueltigkeit}}.
|
|
243
|
+
|
|
244
|
+
If you did not start an application yourself, please ignore this email \u2014 the application will then not be added to your account.`}}]},nU=D.object({tenantSlug:D.string()}),eye={id:"applicant.applicationSubmitted",category:"admission",label:"Eingangsbest\xE4tigung",occasion:{de:"Sobald eine Familie ihre Bewerbung zum ersten Mal abgesendet hat",en:"As soon as a family has submitted its application for the first time"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:nU,channels:["email"],portalVisible:!0,placeholders:[ht,mt],slots:[Me({de:"Ihre Bewerbung ist bei uns eingegangen",en:"We have received your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`wir haben Ihre Bewerbung bei {{schoolName}} erhalten \u2014 vielen Dank. Sie h\xF6ren von uns, sobald es einen neuen Stand gibt.
|
|
245
|
+
|
|
246
|
+
Den aktuellen Stand sehen Sie jederzeit hier:
|
|
247
|
+
|
|
248
|
+
{{portalLink}}`,en:`We have received your application to {{schoolName}} \u2014 thank you. We will be in touch as soon as there is any news.
|
|
249
|
+
|
|
250
|
+
You can check the current status at any time here:
|
|
251
|
+
|
|
252
|
+
{{portalLink}}`}}]},rU=D.object(Tt),iU={key:"taskCount",label:"Anzahl der offenen Aufgaben"},tye={id:"applicant.tasksOpen",category:"tasks",label:"Offene Aufgaben",occasion:{de:"Sobald eine Bewerbung etwas offen hat, das die Familie erledigen muss",en:"As soon as an application has something waiting for the family to do"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:rU,channels:["email"],portalVisible:!0,placeholders:[ht,iU,mt],slots:[Me({de:"Zu Ihrer Bewerbung ist noch etwas offen",en:"Something is still outstanding on your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"f\xFCr Ihre Bewerbung bei {{schoolName}} wartet noch etwas auf Sie.",en:"There is still something waiting for you on your application to {{schoolName}}."}},{key:"taskListLead",label:"\xDCberschrift der Aufgabenliste",multiline:!0,default:{de:"Das ist noch zu tun:",en:"Still to do:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Erledigen k\xF6nnen Sie das in Ihrem Portal:
|
|
253
|
+
|
|
254
|
+
{{portalLink}}`,en:`You can take care of this in your applicant portal:
|
|
255
|
+
|
|
256
|
+
{{portalLink}}`}}]},nf=D.object({...Tt,workItemId:D.id("work_items"),dueAt:D.number()}),tl={key:"taskTitle",label:"Titel der Aufgabe"},nl={key:"dueDate",label:"F\xE4lligkeitstag",subjectSafe:!0},rl={key:"applicantName",label:"Name aus der Bewerbung"},nye={id:"applicant.taskDueSoon",category:"tasks",label:"Frist l\xE4uft bald ab",occasion:{de:`${Oy} Tage bevor die Frist einer Aufgabe der Familie abl\xE4uft`,en:`${Oy} days before the deadline of a family task runs out`},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:nf,channels:["email"],portalVisible:!0,placeholders:[ht,tl,nl,rl,mt],slots:[Me({de:"Erinnerung: Eine Frist zu Ihrer Bewerbung l\xE4uft bald ab",en:"Reminder: a deadline for your application is coming up"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"f\xFCr die Bewerbung von {{applicantName}} bei {{schoolName}} ist noch eine Aufgabe offen: \u201E{{taskTitle}}\u201C. Bitte erledigen Sie sie bis zum {{dueDate}}.",en:"There is still a task open on {{applicantName}}\u2019s application to {{schoolName}}: \u201C{{taskTitle}}\u201D. Please complete it by {{dueDate}}."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Das geht in Ihrem Portal:
|
|
257
|
+
|
|
258
|
+
{{portalLink}}`,en:`You can do this in your applicant portal:
|
|
259
|
+
|
|
260
|
+
{{portalLink}}`}}]},rye={id:"applicant.taskOverdue",category:"tasks",label:"Frist \xFCberschritten",occasion:{de:"Am Tag nach dem Ablauf der Frist einer Aufgabe, die die Familie noch nicht erledigt hat",en:"The day after the deadline of a family task passed without it being done"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:nf,channels:["email"],portalVisible:!0,placeholders:[ht,tl,nl,rl,mt],slots:[Me({de:"Eine Frist zu Ihrer Bewerbung ist \xFCberschritten",en:"A deadline for your application has passed"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"die Frist f\xFCr \u201E{{taskTitle}}\u201C in der Bewerbung von {{applicantName}} bei {{schoolName}} ist am {{dueDate}} abgelaufen.",en:"The deadline for \u201C{{taskTitle}}\u201D on {{applicantName}}\u2019s application to {{schoolName}} passed on {{dueDate}}."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Bitte erledigen Sie die Aufgabe so bald wie m\xF6glich in Ihrem Portal:
|
|
261
|
+
|
|
262
|
+
{{portalLink}}`,en:`Please complete the task as soon as possible in your applicant portal:
|
|
263
|
+
|
|
264
|
+
{{portalLink}}`}}]},oU=D.object({...Tt,waitingWorkItemId:D.id("work_items")}),sU={key:"requestedFields",label:"Angeforderte Angaben"},iye={id:"applicant.requestCancelled",category:"tasks",label:"Nachforderung entf\xE4llt",occasion:{de:"Wenn die Schule eine Nachforderung zur\xFCcknimmt oder anders entscheidet, bevor die Familie geantwortet hat",en:"When the school takes back a request for documents, or decides otherwise, before the family has answered"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:oU,channels:["email"],portalVisible:!0,placeholders:[ht,rl,sU,mt],slots:[Me({de:"Eine Nachforderung zu Ihrer Bewerbung entf\xE4llt",en:"A request on your application has been withdrawn"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"f\xFCr die Bewerbung von {{applicantName}} bei {{schoolName}} ben\xF6tigen wir die angeforderten Angaben nicht mehr: {{requestedFields}}. Sie m\xFCssen dazu nichts mehr einreichen.",en:"For {{applicantName}}\u2019s application to {{schoolName}} we no longer need the details we asked for: {{requestedFields}}. You do not need to hand in anything for this."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Den Stand Ihrer Bewerbung sehen Sie in Ihrem Portal:
|
|
265
|
+
|
|
266
|
+
{{portalLink}}`,en:`You can see where your application stands in your applicant portal:
|
|
267
|
+
|
|
268
|
+
{{portalLink}}`}}]},oye={id:"staff.taskOverdue",category:"staffDeadlines",label:"Frist der Familie \xFCberschritten",occasion:{de:"Am Tag nach dem Ablauf der Frist einer Aufgabe der Familie, die noch offen ist",en:"The day after the deadline of a family task passed while it is still open"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:nf,channels:["email"],portalVisible:!1,placeholders:[tl,nl,rl,Xa],slots:[Me({de:"Frist \xFCberschritten: Eine Aufgabe der Familie ist noch offen",en:"Deadline passed: a family task is still open"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"die Frist f\xFCr \u201E{{taskTitle}}\u201C in der Bewerbung von {{applicantName}} ist am {{dueDate}} abgelaufen. Die Familie hat die Aufgabe noch nicht erledigt und wurde darauf hingewiesen.",en:"The deadline for \u201C{{taskTitle}}\u201D on {{applicantName}}\u2019s application passed on {{dueDate}}. The family has not yet completed the task and has been notified."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Die Bewerbung finden Sie hier:
|
|
269
|
+
|
|
270
|
+
{{applicationLink}}`,en:`You can find the application here:
|
|
271
|
+
|
|
272
|
+
{{applicationLink}}`}}]},sye={id:"staff.unassignedTaskOverdue",category:"staffDeadlines",label:"Frist einer unzugewiesenen Aufgabe \xFCberschritten",occasion:{de:"Am Tag nach dem Ablauf der Frist einer internen Aufgabe, die noch offen ist und niemandem zugewiesen",en:"The day after the deadline of an internal task passed while it is still open and assigned to nobody"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:nf,channels:["email"],portalVisible:!1,placeholders:[tl,nl,rl,Xa],slots:[Me({de:"Frist \xFCberschritten: Eine Aufgabe ist niemandem zugewiesen",en:"Deadline passed: a task is assigned to nobody"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"die Frist f\xFCr \u201E{{taskTitle}}\u201C in der Bewerbung von {{applicantName}} ist am {{dueDate}} abgelaufen. Die Aufgabe ist noch offen und niemandem zugewiesen.",en:"The deadline for \u201C{{taskTitle}}\u201D on {{applicantName}}\u2019s application passed on {{dueDate}}. The task is still open and assigned to nobody."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Bitte weisen Sie die Aufgabe in der Bewerbung einer Person zu:
|
|
273
|
+
|
|
274
|
+
{{applicationLink}}`,en:`Please assign the task to a person in the application:
|
|
275
|
+
|
|
276
|
+
{{applicationLink}}`}}]},aU=D.object({tenantSlug:D.string(),recipientUserId:D.id("users"),workItemId:D.id("work_items"),taskTitle:D.string()});var o_={key:"taskLink",label:"Link zur Aufgabe",required:!0,link:!0,actionLabel:{de:"Aufgabe \xF6ffnen",en:"Open task"}},s_={...tl,subjectSafe:!0},aye={id:"staff.taskAssigned",category:"staffTasks",label:"Aufgabe zugewiesen",occasion:{de:"Sobald einer Person eine Aufgabe zugewiesen wird (nicht bei Selbstzuweisung)",en:"When a task is assigned to a person (not when they take it themselves)"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:aU,channels:["email"],portalVisible:!1,placeholders:[s_,o_],slots:[Me({de:"Neue Aufgabe: {{taskTitle}}",en:"New task: {{taskTitle}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"Ihnen wurde diese Aufgabe zugewiesen:",en:"This task has been assigned to you:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Direkt zur Aufgabe:
|
|
277
|
+
|
|
278
|
+
{{taskLink}}`,en:`Go straight to the task:
|
|
279
|
+
|
|
280
|
+
{{taskLink}}`}}]},lU=D.object({tenantSlug:D.string(),recipientUserId:D.id("users"),workItemId:D.id("work_items"),teamId:D.id("permission_groups"),taskTitle:D.string(),teamLabel:D.string()}),dU={key:"teamLabel",label:"Team",subjectSafe:!0},lye={id:"staff.teamTaskQueued",category:"staffTasks",label:"Aufgabe f\xFCr ein Team",occasion:{de:"Sobald eine Aufgabe ohne Bearbeiter in der Queue eines Teams landet \u2014 an jedes Mitglied",en:"When a task lands in a team's queue with nobody holding it \u2014 to every member"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:lU,channels:["email"],portalVisible:!1,placeholders:[s_,dU,o_],slots:[Me({de:"Neue Aufgabe f\xFCr {{teamLabel}}: {{taskTitle}}",en:"New task for {{teamLabel}}: {{taskTitle}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"Diese Aufgabe liegt jetzt in der Queue Ihres Teams {{teamLabel}}:",en:"This task is now in the queue of your team {{teamLabel}}:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Direkt zur Aufgabe:
|
|
281
|
+
|
|
282
|
+
{{taskLink}}`,en:`Go straight to the task:
|
|
283
|
+
|
|
284
|
+
{{taskLink}}`}}]},dye=D.object({tenantSlug:D.string(),instanceId:D.id("smart_form_instances")});var cU=D.object(Tt),cye={id:"admission.approved",category:"admission",label:"Zusage",occasion:{de:"Sobald eine Bewerbung mit \u201EZusage\u201C entschieden ist",en:"As soon as an application has been decided \u201Capproved\u201D"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:cU,channels:["email"],portalVisible:!0,placeholders:[ht,mt],slots:[Me({de:"Zusage f\xFCr Ihre Bewerbung",en:"Offer of a place \u2014 your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"wir freuen uns, Ihnen einen Platz bei {{schoolName}} anbieten zu k\xF6nnen.",en:"We are delighted to offer you a place at {{schoolName}}."}},{key:"next",label:"Wie es weitergeht",multiline:!0,default:{de:"\xDCber die n\xE4chsten Schritte informieren wir Sie rechtzeitig.",en:"We will let you know about the next steps in good time."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Ihre Bewerbung finden Sie hier:
|
|
285
|
+
|
|
286
|
+
{{portalLink}}`,en:`You can find your application here:
|
|
287
|
+
|
|
288
|
+
{{portalLink}}`}}]},Ib=D.object({...Tt,bookingId:D.id("appointment_bookings")}),rf={key:"appointmentTitle",label:"Anlass des Termins"},of={key:"appointmentWhen",label:"Datum und Uhrzeit des Termins",required:!0},sf={key:"appointmentLocation",label:"Ort des Termins",required:!0},uye={id:"admission.appointmentBooked",category:"admission",label:"Termin vereinbart",occasion:{de:"Sobald die Schule f\xFCr eine Bewerbung einen Termin eingetragen hat (Ergebnis der Aufgabe \u201ETermin vereinbaren\u201C)",en:"As soon as the school has booked an appointment for an application (result of a \u201Cschedule appointment\u201D task)"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:Ib,channels:["email"],portalVisible:!0,placeholders:[ht,rf,of,sf,mt],slots:[Me({de:"Ihr Termin bei uns",en:"Your appointment with us"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"wir haben f\xFCr Ihre Bewerbung bei {{schoolName}} einen Termin vereinbart:",en:"We have arranged an appointment for your application to {{schoolName}}:"}},{key:"details",label:"Termin",multiline:!0,default:{de:`{{appointmentTitle}}
|
|
289
|
+
{{appointmentWhen}}
|
|
290
|
+
Ort: {{appointmentLocation}}`,en:`{{appointmentTitle}}
|
|
291
|
+
{{appointmentWhen}}
|
|
292
|
+
Location: {{appointmentLocation}}`}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Mit der angeh\xE4ngten Kalenderdatei k\xF6nnen Sie den Termin in Ihren Kalender \xFCbernehmen. Ihre Bewerbung finden Sie hier:
|
|
293
|
+
|
|
294
|
+
{{portalLink}}`,en:`You can add the appointment to your calendar using the attached calendar file. You can find your application here:
|
|
295
|
+
|
|
296
|
+
{{portalLink}}`}}]},fye={id:"admission.appointmentRescheduled",category:"admission",label:"Termin verschoben",occasion:{de:"Sobald die Schule einen vereinbarten Termin verschiebt (neues Datum, neue Uhrzeit, Dauer oder neuer Ort)",en:"When the school moves a booked appointment (new date, time, duration or place)"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:Ib,channels:["email"],portalVisible:!0,placeholders:[ht,rf,of,sf,mt],slots:[Me({de:"Ihr Termin bei uns wurde verschoben",en:"Your appointment with us has been moved"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"wir mussten den Termin f\xFCr Ihre Bewerbung bei {{schoolName}} verschieben. Er findet jetzt so statt:",en:"We had to move the appointment for your application to {{schoolName}}. It now takes place as follows:"}},{key:"details",label:"Termin",multiline:!0,default:{de:`{{appointmentTitle}}
|
|
297
|
+
{{appointmentWhen}}
|
|
298
|
+
Ort: {{appointmentLocation}}`,en:`{{appointmentTitle}}
|
|
299
|
+
{{appointmentWhen}}
|
|
300
|
+
Location: {{appointmentLocation}}`}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Mit der angeh\xE4ngten Kalenderdatei aktualisieren Sie den Eintrag in Ihrem Kalender. Ihre Bewerbung finden Sie hier:
|
|
301
|
+
|
|
302
|
+
{{portalLink}}`,en:`The attached calendar file updates the entry in your calendar. You can find your application here:
|
|
303
|
+
|
|
304
|
+
{{portalLink}}`}}]},pye={id:"admission.appointmentCancelled",category:"admission",label:"Termin abgesagt",occasion:{de:"Sobald ein vereinbarter Termin abgesagt wird \u2014 von der Schule, oder als Best\xE4tigung der Absage durch die Familie",en:"When a booked appointment is cancelled \u2014 by the school, or confirming the family's own cancellation"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:Ib,channels:["email"],portalVisible:!0,placeholders:[ht,rf,of,sf,mt],bodyVariants:[["intro","details","outro"],["familyIntro","details","outro"]],slots:[Me({de:"Ihr Termin bei uns wurde abgesagt",en:"Your appointment with us has been cancelled"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"wir m\xFCssen den folgenden Termin f\xFCr Ihre Bewerbung bei {{schoolName}} leider absagen:",en:"Unfortunately we have to cancel the following appointment for your application to {{schoolName}}:"}},{key:"familyIntro",label:"Einleitung (Absage durch die Familie)",multiline:!0,default:{de:"wie mit Ihnen besprochen, haben wir den folgenden Termin f\xFCr Ihre Bewerbung bei {{schoolName}} abgesagt:",en:"As agreed with you, we have cancelled the following appointment for your application to {{schoolName}}:"}},{key:"details",label:"Termin",multiline:!0,default:{de:`{{appointmentTitle}}
|
|
305
|
+
{{appointmentWhen}}
|
|
306
|
+
Ort: {{appointmentLocation}}`,en:`{{appointmentTitle}}
|
|
307
|
+
{{appointmentWhen}}
|
|
308
|
+
Location: {{appointmentLocation}}`}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Mit der angeh\xE4ngten Kalenderdatei entfernen Sie den Eintrag aus Ihrem Kalender. Ihre Bewerbung finden Sie hier:
|
|
309
|
+
|
|
310
|
+
{{portalLink}}`,en:`The attached calendar file removes the entry from your calendar. You can find your application here:
|
|
311
|
+
|
|
312
|
+
{{portalLink}}`}}]},uU=["invite","update","cancel"],fU=D.object({...Tt,appointmentId:D.id("appointments"),kind:D.union(...uU.map(t=>D.literal(t))),appointmentTitle:D.string()}),pU={...rf,subjectSafe:!0},mU={key:"appointmentChange",label:"Art der Nachricht",subjectSafe:!0},mye={id:"staff.appointmentHosted",category:"staffAppointments",label:"Kalendereinladung an den Gastgeber",occasion:{de:"Sobald ein Termin gebucht, verschoben oder abgesagt wird \u2014 an die Gastgeberin oder den Gastgeber (bei einem Team: die Teamzust\xE4ndige der Bewerbung)",en:"When an appointment is booked, moved or cancelled \u2014 to its host (for a team: the application's team owner)"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:fU,channels:["email"],portalVisible:!1,placeholders:[mU,pU,of,sf,Xa],bodyVariants:[["intro","details","outro"],["updatedIntro","details","outro"],["cancelledIntro","details","cancelledOutro"]],slots:[Me({de:"{{appointmentChange}}: Termin \u201E{{appointmentTitle}}\u201C",en:"{{appointmentChange}}: appointment \u201C{{appointmentTitle}}\u201D"}),{key:"intro",label:"Einleitung (Einladung)",multiline:!0,default:{de:"Sie sind f\xFCr diesen Termin als Gastgeberin bzw. Gastgeber eingetragen:",en:"You are down as the host of this appointment:"}},{key:"updatedIntro",label:"Einleitung (ge\xE4ndert)",multiline:!0,default:{de:"Ein Termin, den Sie ausrichten, hat sich ge\xE4ndert:",en:"An appointment you are hosting has changed:"}},{key:"cancelledIntro",label:"Einleitung (abgesagt)",multiline:!0,default:{de:"Dieser Termin findet f\xFCr Sie nicht statt:",en:"This appointment no longer takes place for you:"}},{key:"details",label:"Termin",multiline:!0,default:{de:`{{appointmentTitle}}
|
|
313
|
+
{{appointmentWhen}}
|
|
314
|
+
Ort: {{appointmentLocation}}`,en:`{{appointmentTitle}}
|
|
315
|
+
{{appointmentWhen}}
|
|
316
|
+
Location: {{appointmentLocation}}`}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Mit der angeh\xE4ngten Kalenderdatei \xFCbernehmen Sie den Termin in Ihren Kalender. Zur Bewerbung:
|
|
317
|
+
|
|
318
|
+
{{applicationLink}}`,en:`The attached calendar file puts the appointment in your calendar. The application:
|
|
319
|
+
|
|
320
|
+
{{applicationLink}}`}},{key:"cancelledOutro",label:"Abschluss (abgesagt)",multiline:!0,default:{de:`Die angeh\xE4ngte Kalenderdatei nimmt den Termin aus Ihrem Kalender. Zur Bewerbung:
|
|
321
|
+
|
|
322
|
+
{{applicationLink}}`,en:`The attached calendar file removes the appointment from your calendar. The application:
|
|
323
|
+
|
|
324
|
+
{{applicationLink}}`}}]},hU=D.object({...Tt,comment:D.optional(D.string())}),gU={key:"comment",label:"Begr\xFCndung der Entscheidung"},hye={id:"admission.rejected",category:"admission",label:"Absage",occasion:{de:"Sobald eine Bewerbung mit \u201EAbsage\u201C entschieden ist",en:"As soon as an application has been decided \u201Crejected\u201D"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:hU,channels:["email"],portalVisible:!0,placeholders:[ht,gU,Tb],slots:[Me({de:"Absage zu Ihrer Bewerbung",en:"Your application \u2014 we are unable to offer a place"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"leider k\xF6nnen wir Ihnen keinen Platz bei {{schoolName}} anbieten.",en:"Unfortunately, we are unable to offer you a place at {{schoolName}}."}},{key:"reason",label:"Begr\xFCndung",multiline:!0,default:{de:"{{comment}}",en:"{{comment}}"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:"F\xFCr Ihr Interesse danken wir Ihnen.",en:"Thank you for your interest."}}]},yU=D.object(Tt),gye={id:"admission.waitlisted",category:"admission",label:"Warteliste",occasion:{de:"Sobald eine Bewerbung auf die Warteliste gesetzt wird",en:"As soon as an application is placed on the waiting list"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:yU,channels:["email"],portalVisible:!0,placeholders:[ht,Tb],slots:[Me({de:"Ihre Bewerbung steht auf der Warteliste",en:"Your application is on the waiting list"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"zurzeit k\xF6nnen wir Ihnen keinen Platz bei {{schoolName}} zusagen. Ihre Bewerbung steht auf der Warteliste.",en:"At the moment we are unable to offer you a place at {{schoolName}}. Your application has been placed on the waiting list."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:"Sobald ein Platz frei wird, melden wir uns bei Ihnen.",en:"We will be in touch as soon as a place becomes available."}}]},bU=D.object(Tt),yye={id:"admission.waitlistPromoted",category:"admission",label:"Nachger\xFCckt",occasion:{de:"Sobald eine Bewerbung von der Warteliste nachr\xFCckt",en:"As soon as an application moves up off the waiting list"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:bU,channels:["email"],portalVisible:!0,placeholders:[ht,mt],slots:[Me({de:"Ein Platz ist frei geworden",en:"A place has become available"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"ein Platz bei {{schoolName}} ist frei geworden \u2014 Ihre Bewerbung ist nachger\xFCckt.",en:"A place has become available at {{schoolName}} \u2014 your application has moved up from the waiting list."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Alles Weitere finden Sie hier:
|
|
325
|
+
|
|
326
|
+
{{portalLink}}`,en:`You can find all further details here:
|
|
327
|
+
|
|
328
|
+
{{portalLink}}`}}]},wU=D.object({...Tt,documentTitle:el,dueInDays:D.optional(D.number())}),$b={key:"documentTitle",label:"Name des Dokuments",subjectSafe:!0},kU={key:"dueInDays",label:"Antwortfrist in Tagen"},bye={id:"admission.documentIssued",category:"admission",label:"Dokument bereitgestellt",occasion:{de:"Sobald ein Dokument \u2014 Platzangebot, Vertrag \u2014 f\xFCr die Familie bereitliegt",en:"As soon as a document \u2014 offer letter, contract \u2014 is ready for the family"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:wU,channels:["email"],portalVisible:!0,placeholders:[ht,$b,kU,mt],slots:[Me({de:"{{documentTitle}} liegt f\xFCr Sie bereit",en:"{{documentTitle}} is ready for you"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"{{documentTitle}} von {{schoolName}} wartet auf Ihre Antwort.",en:"{{documentTitle}} from {{schoolName}} is waiting for your response."}},{key:"deadline",label:"Frist",multiline:!0,default:{de:"Bitte antworten Sie innerhalb von {{dueInDays}} Tagen.",en:"Please respond within {{dueInDays}} days."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Ansehen und beantworten k\xF6nnen Sie es hier:
|
|
329
|
+
|
|
330
|
+
{{portalLink}}`,en:`You can view it and respond here:
|
|
331
|
+
|
|
332
|
+
{{portalLink}}`}}]},vU=D.object({...Tt,documentTitle:el,reason:D.string()}),SU={key:"reason",label:"Begr\xFCndung der Schule",required:!0},wye={id:"admission.documentReturnHandedBack",category:"admission",label:"R\xFCcklauf zur\xFCckgegeben",occasion:{de:"Sobald die Schule ein unterschrieben zur\xFCckgesendetes Dokument mit Begr\xFCndung an die Familie zur\xFCckgibt",en:"As soon as the school hands a returned signed document back to the family with a reason"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:vU,channels:["email"],portalVisible:!0,placeholders:[ht,$b,SU,mt],slots:[Me({de:"{{documentTitle}}: bitte noch einmal unterschreiben",en:"{{documentTitle}}: please sign again"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"vielen Dank f\xFCr Ihren R\xFCcklauf. {{schoolName}} kann {{documentTitle}} in dieser Form leider noch nicht annehmen:",en:"Thank you for returning it. Unfortunately {{schoolName}} cannot accept {{documentTitle}} as it is yet:"}},{key:"reason",label:"Begr\xFCndung",multiline:!0,default:{de:"{{reason}}",en:"{{reason}}"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Bitte laden Sie das unterschriebene Dokument hier erneut hoch:
|
|
333
|
+
|
|
334
|
+
{{portalLink}}`,en:`Please upload the signed document again here:
|
|
335
|
+
|
|
336
|
+
{{portalLink}}`}}]},xU=D.object({...Tt,documentTitle:el}),kye={id:"admission.contractCountersigned",category:"admission",label:"Vertrag gegengezeichnet",occasion:{de:"Sobald die Schule den von der Familie unterschriebenen Vertrag gegengezeichnet hat",en:"As soon as the school has countersigned the contract the family signed"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:xU,channels:["email"],portalVisible:!0,placeholders:[ht,$b,mt],slots:[Me({de:"{{documentTitle}} gegengezeichnet",en:"{{documentTitle}} countersigned"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"{{schoolName}} hat das Dokument \u201E{{documentTitle}}\u201C gegengezeichnet. Damit ist der Vertrag geschlossen.",en:"{{schoolName}} has countersigned the document \u201C{{documentTitle}}\u201D. The contract is now concluded."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Das gegengezeichnete Exemplar finden Sie hier:
|
|
337
|
+
|
|
338
|
+
{{portalLink}}`,en:`You will find the countersigned copy here:
|
|
339
|
+
|
|
340
|
+
{{portalLink}}`}}]},AU=D.object({...Tt,sectionLabel:el}),EU={key:"sectionLabel",label:"Freigeschalteter Abschnitt",subjectSafe:!0},vye={id:"admission.sectionUnlocked",category:"admission",label:"Abschnitt freigeschaltet",occasion:{de:"Sobald ein Prozess einen weiteren Abschnitt des Formulars zum Ausf\xFCllen freischaltet",en:"As soon as a process unlocks a further section of the form to fill in"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:AU,channels:["email"],portalVisible:!0,placeholders:[ht,EU,mt],slots:[Me({de:"Sie k\xF6nnen jetzt die {{sectionLabel}} ausf\xFCllen",en:"You can now fill in {{sectionLabel}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"Sie k\xF6nnen jetzt die {{sectionLabel}} zu Ihrer Bewerbung bei {{schoolName}} ausf\xFCllen.",en:"You can now fill in {{sectionLabel}} for your application to {{schoolName}}."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Zum Formular geht es hier:
|
|
341
|
+
|
|
342
|
+
{{portalLink}}`,en:`You can get to the form here:
|
|
343
|
+
|
|
344
|
+
{{portalLink}}`}}]},RU=D.object({...Tt,fieldLabels:el,dueAt:D.number()}),TU={key:"fieldLabels",label:"Fehlende Unterlagen",subjectSafe:!0},Sye={id:"admission.documentsRequested",category:"admission",label:"Unterlagen angefordert",occasion:{de:"Sobald eine Vollst\xE4ndigkeitspr\xFCfung fehlende Unterlagen mit Frist bei der Familie anfordert",en:"As soon as a completeness check asks the family for missing documents by a deadline"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:RU,channels:["email"],portalVisible:!0,placeholders:[ht,TU,nl,mt],slots:[Me({de:"Bitte reichen Sie Unterlagen bis {{dueDate}} nach",en:"Please submit outstanding documents by {{dueDate}}"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`f\xFCr Ihre Anmeldung bei {{schoolName}} fehlen noch folgende Unterlagen: {{fieldLabels}}.
|
|
345
|
+
|
|
346
|
+
Bitte reichen Sie diese bis zum {{dueDate}} nach.`,en:`The following documents are still missing for your application to {{schoolName}}: {{fieldLabels}}.
|
|
347
|
+
|
|
348
|
+
Please submit them by {{dueDate}}.`}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Hochladen k\xF6nnen Sie sie hier:
|
|
349
|
+
|
|
350
|
+
{{portalLink}}`,en:`You can upload them here:
|
|
351
|
+
|
|
352
|
+
{{portalLink}}`}}]},IU=D.object({...Tt,amount:D.float64()}),$U={key:"amount",label:"Betrag",subjectSafe:!0},xye={id:"admission.paymentRequested",category:"admission",label:"Zahlung angefordert",occasion:{de:"Sobald ein Prozess eine Zahlung anfordert",en:"As soon as a process asks for a payment"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:IU,channels:["email"],portalVisible:!0,placeholders:[ht,$U,mt],slots:[Me({de:"Offene Zahlung zu Ihrer Bewerbung",en:"Payment due for your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"f\xFCr Ihre Bewerbung bei {{schoolName}} ist ein Betrag von {{amount}} f\xE4llig.",en:"A payment of {{amount}} is due for your application to {{schoolName}}."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Bezahlen k\xF6nnen Sie hier:
|
|
353
|
+
|
|
354
|
+
{{portalLink}}`,en:`You can pay here:
|
|
355
|
+
|
|
356
|
+
{{portalLink}}`}}]},_U=D.object(Tt),Aye={id:"admission.enrolled",category:"admission",label:"Aufgenommen",occasion:{de:"Sobald das Aufnahmeverfahren mit einer Aufnahme abgeschlossen ist",en:"As soon as the admission process has ended in an enrolment"},audience:"external",frame:"letter",timeline:"correspondence",paramsValidator:_U,channels:["email"],portalVisible:!0,placeholders:[ht,Tb],slots:[Me({de:"Herzlich willkommen an unserer Schule",en:"A warm welcome to our school"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"herzlich willkommen bei {{schoolName}}! Der Vertrag ist geschlossen, und wir freuen uns sehr, Ihr Kind bald bei uns begr\xFC\xDFen zu d\xFCrfen.",en:"A very warm welcome to {{schoolName}}! The contract is now in place, and we are very much looking forward to welcoming your child soon."}},{key:"next",label:"Wie es weitergeht",multiline:!0,default:{de:"Wie es weitergeht, teilen wir Ihnen rechtzeitig mit.",en:"We will let you know in good time what happens next."}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:"Wir freuen uns auf die gemeinsame Zeit.",en:"We look forward to the time ahead together."}}]},_b=D.object({...Tt,commentId:D.id("comments")}),Eye={id:"chat.externalStaffMessage",category:"schoolMessages",label:"Neue Nachricht der Schule",occasion:{de:"Sobald die Schule einer Familie in den Nachrichten einer Bewerbung schreibt",en:"As soon as the school writes to a family in an application's messages"},audience:"external",frame:"letter",timeline:"hidden",paramsValidator:_b,channels:["email"],portalVisible:!0,placeholders:[mt],bodyVariants:[["intro","outro"],["removedIntro"]],slots:[Me({de:"Neue Nachricht zu Ihrer Bewerbung",en:"New message about your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"zu Ihrer Bewerbung gibt es eine neue Nachricht:",en:"There is a new message about your application:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`\xDCber den folgenden Link k\xF6nnen Sie antworten:
|
|
357
|
+
|
|
358
|
+
{{portalLink}}`,en:`You can reply using the link below:
|
|
359
|
+
|
|
360
|
+
{{portalLink}}`}},{key:"removedIntro",label:"Einleitung, wenn die Nachricht gel\xF6scht wurde",multiline:!0,default:{de:`zu Ihrer Bewerbung gab es eine neue Nachricht. Die Nachricht wurde inzwischen entfernt. \xDCber den folgenden Link erreichen Sie Ihre Bewerbung:
|
|
361
|
+
|
|
362
|
+
{{portalLink}}`,en:`There was a new message about your application. The message has since been removed. You can reach your application using the link below:
|
|
363
|
+
|
|
364
|
+
{{portalLink}}`}}]},Rye={id:"chat.externalApplicantMessage",category:"familyMessages",label:"Neue Nachricht einer Familie",occasion:{de:"Sobald eine Familie in den Nachrichten einer Bewerbung antwortet",en:"As soon as a family replies in an application's messages"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:_b,channels:["email"],portalVisible:!1,placeholders:[r_,Xa],bodyVariants:[["intro","outro"],["removedIntro"]],slots:[Me({de:"Neue Nachricht zu einer Bewerbung",en:"New message about an application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"{{authorName}} hat eine neue Nachricht zu einer Bewerbung geschrieben, f\xFCr die Sie zust\xE4ndig sind:",en:"{{authorName}} has written a new message about an application you are responsible for:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Die Bewerbung finden Sie hier:
|
|
365
|
+
|
|
366
|
+
{{applicationLink}}`,en:`You can find the application here:
|
|
367
|
+
|
|
368
|
+
{{applicationLink}}`}},{key:"removedIntro",label:"Einleitung, wenn die Nachricht gel\xF6scht wurde",multiline:!0,default:{de:`zu einer Bewerbung, f\xFCr die Sie zust\xE4ndig sind, gab es eine neue Nachricht. Die Nachricht wurde inzwischen entfernt.
|
|
369
|
+
|
|
370
|
+
{{applicationLink}}`,en:`There was a new message about an application you are responsible for. The message has since been removed.
|
|
371
|
+
|
|
372
|
+
{{applicationLink}}`}}]},Tye={id:"chat.mention",category:"mentions",label:"Erw\xE4hnung in einer Bewerbung",occasion:{de:"Sobald jemand ein Teammitglied in einer Nachricht mit @ erw\xE4hnt",en:"As soon as someone @-mentions a team member in a message"},audience:"internal",frame:"notice",timeline:"hidden",paramsValidator:_b,channels:["email"],portalVisible:!1,placeholders:[r_,Xa],bodyVariants:[["intro","outro"],["removedIntro"]],slots:[Me({de:"Sie wurden in einer Bewerbung erw\xE4hnt",en:"You were mentioned in an application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:"{{authorName}} hat Sie in einer Nachricht zu einer Bewerbung erw\xE4hnt:",en:"{{authorName}} mentioned you in a message about an application:"}},{key:"outro",label:"Abschluss",multiline:!0,default:{de:`Die Bewerbung finden Sie hier:
|
|
373
|
+
|
|
374
|
+
{{applicationLink}}`,en:`You can find the application here:
|
|
375
|
+
|
|
376
|
+
{{applicationLink}}`}},{key:"removedIntro",label:"Einleitung, wenn die Nachricht gel\xF6scht wurde",multiline:!0,default:{de:`Sie wurden in einer Nachricht zu einer Bewerbung erw\xE4hnt. Die Nachricht wurde inzwischen entfernt.
|
|
377
|
+
|
|
378
|
+
{{applicationLink}}`,en:`You were mentioned in a message about an application. The message has since been removed.
|
|
379
|
+
|
|
380
|
+
{{applicationLink}}`}}]},OU=D.object({tenantSlug:D.string(),purpose:D.union(D.literal("apply"),D.literal("reentry")),callbackPath:D.string()}),Iye={id:"applicant.magicLink",category:"login",label:"Anmeldelink",occasion:{de:"Wenn eine Familie sich ohne Passwort anmelden m\xF6chte",en:"When a family signs in without a password"},audience:"external",frame:"letter",timeline:"hidden",paramsValidator:OU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[tf,Ho],slots:[Me({de:"Ihr Anmeldelink",en:"Your sign-in link"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`hier ist Ihr Anmeldelink. Damit kommen Sie ohne Passwort zu Ihren Bewerbungen:
|
|
381
|
+
|
|
382
|
+
{{anmeldeLink}}
|
|
383
|
+
|
|
384
|
+
Der Link gilt {{gueltigkeit}}. Wenn Sie das nicht angefordert haben, k\xF6nnen Sie diese E-Mail ignorieren.`,en:`Here is your sign-in link. It takes you to your applications without a password:
|
|
385
|
+
|
|
386
|
+
{{anmeldeLink}}
|
|
387
|
+
|
|
388
|
+
The link is valid for {{gueltigkeit}}. If you did not request it, you can ignore this email.`}}]},CU=D.object(Tt),$ye={id:"applicant.accessSent",category:"login",label:"Zugang zur Bewerbung",occasion:{de:"Wenn die Schule einer Familie den Zugang zu ihrer Bewerbung schickt",en:"When the school sends a family the access to its application"},audience:"external",frame:"letter",timeline:"hidden",paramsValidator:CU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[tf,Ho],slots:[Me({de:"Ihr Zugang zur Bewerbung",en:"Access to your application"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`wir schicken Ihnen den Zugang zu Ihrer Bewerbung. Mit diesem Link melden Sie sich ohne Passwort an:
|
|
389
|
+
|
|
390
|
+
{{anmeldeLink}}
|
|
391
|
+
|
|
392
|
+
Der Link gilt {{gueltigkeit}}. Bitte leiten Sie diese E-Mail nicht weiter \u2014 wer den Link \xF6ffnet, ist in Ihrem Konto angemeldet.`,en:`We are sending you access to your application. Use this link to sign in without a password:
|
|
393
|
+
|
|
394
|
+
{{anmeldeLink}}
|
|
395
|
+
|
|
396
|
+
The link is valid for {{gueltigkeit}}. Please do not forward this email \u2014 anyone who opens the link will be signed in to your account.`}}]},PU=D.object({tenantSlug:D.string(),callbackPath:D.string()}),_ye={id:"applicant.verifyEmail",category:"login",label:"E-Mail-Adresse best\xE4tigen",occasion:{de:"Bevor eine Familie zum ersten Mal etwas absenden kann",en:"Before a family can submit anything for the first time"},audience:"external",frame:"letter",timeline:"hidden",paramsValidator:PU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[i_,Ho],slots:[Me({de:"Bitte best\xE4tigen Sie Ihre E-Mail-Adresse",en:"Please confirm your email address"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`bitte best\xE4tigen Sie kurz Ihre E-Mail-Adresse \u2014 ein Klick gen\xFCgt:
|
|
397
|
+
|
|
398
|
+
{{bestaetigungsLink}}
|
|
399
|
+
|
|
400
|
+
Danach k\xF6nnen Sie Ihre Bewerbung absenden. Der Link gilt {{gueltigkeit}}. Wenn Sie das nicht angefordert haben, k\xF6nnen Sie diese E-Mail ignorieren.`,en:`Please take a moment to confirm your email address \u2014 one click is all it takes:
|
|
401
|
+
|
|
402
|
+
{{bestaetigungsLink}}
|
|
403
|
+
|
|
404
|
+
You can then submit your application. The link is valid for {{gueltigkeit}}. If you did not request this, you can ignore this email.`}}]},NU=D.object({callbackPath:D.string()}),Oye={id:"account.loginLink",category:"login",label:"Anmeldelink (Anmeldeseite)",occasion:{de:"Wenn jemand auf der Anmeldeseite einen Anmeldelink anfordert",en:"When someone asks for a sign-in link on the login page"},audience:"internal",frame:"letter",timeline:"hidden",paramsValidator:NU,channels:["email"],maxAttempts:4,portalVisible:!1,placeholders:[tf,Ho],slots:[Me({de:"Ihr Anmeldelink f\xFCr Plexus",en:"Your sign-in link for Plexus"}),{key:"intro",label:"Einleitung",multiline:!0,default:{de:`hier ist Ihr Anmeldelink. Damit melden Sie sich ohne Passwort bei Plexus an:
|
|
405
|
+
|
|
406
|
+
{{anmeldeLink}}
|
|
407
|
+
|
|
408
|
+
Der Link gilt {{gueltigkeit}} und funktioniert einmal. Wenn Sie ihn nicht angefordert haben, k\xF6nnen Sie diese E-Mail ignorieren \u2014 Ihr Konto bleibt, wie es ist.`,en:`Here is your sign-in link. Use it to sign in to Plexus without a password:
|
|
409
|
+
|
|
410
|
+
{{anmeldeLink}}
|
|
411
|
+
|
|
412
|
+
The link is valid for {{gueltigkeit}} and works once. If you did not request it, you can ignore this email \u2014 your account stays as it is.`}}]},Cye=D.object({});function Ob(t,e){return e===void 0?!0:e==="localizedText"||t==="localizedText"?t===e:zc(t,e)}o(Ob,"letterArgCompatible");function Cb(t){return t==="localizedText"?"Text in jeder Sprache (localizedText)":`${mn(t)} (${t})`}o(Cb,"letterArgTypeLabel");function a_(t){let e=new Map,n=o((r,i)=>{let s=e.get(r);s===void 0?e.set(r,[i]):s.push(i)},"add");for(let r of t.args)n(r.key,{source:`Ereignis "${t.id}"`,type:r.type,always:r.required===!0});for(let r of e_)n(r.key,{source:"Kontext des Versands",type:r.type,always:!0});return e}o(a_,"eventArgSources");function l_(t,e){let n=t.type===void 0?[...e]:e.filter(r=>Ob(r.type,t.type));if(n.length>1)return{status:"ambiguous",matches:n};if(n.length===1){let r=n[0];return!t.required||r.always?{status:"resolved",source:r}:{status:"sometimes",source:r}}return t.required?{status:"missing",rejected:[...e]}:{status:"unused"}}o(l_,"resolveLetterParam");var zye=D.union(D.literal("approved"),D.literal("rejected")),af=new Set(["task","approval"]);function DU(t,e){switch(t){case"task":return e?.gatesNode===!0&&W("expandComposedTask: gatesNode is approval-only \u2014 a 'task' template never gates its node (use blocks to hold a gating sibling back)"),{kind:"task",recipient:"internal",gatesNode:!1};case"approval":return{kind:"approval",recipient:"internal",isApproval:!0,gatesNode:e?.gatesNode??!0};default:W(`expandComposedTask: unknown composed-task kind ${JSON.stringify(t)} \u2014 authorable: ${[...af].join(", ")}`)}}o(DU,"expandComposedTask");for(let t of["task","approval"]){let e=DU(t);e.kind==="approval"!=(e.isApproval===!0)&&W(`composed-task kind "${t}": isApproval must be present iff kind === 'approval'`)}function lf(t,e){let s=new Map;for(let d of t)s.set(d,0);let a=new Map,l=[];for(let d of t){if((s.get(d)??0)!==0)continue;let c=[{id:d,edges:e(d),idx:0}];for(s.set(d,1),a.set(d,null);c.length>0;){let u=c[c.length-1];if(u.idx>=u.edges.length){s.set(u.id,2),c.pop();continue}let{target:f,edge:h}=u.edges[u.idx];u.idx++;let g=s.get(f)??0;if(g===1){let b=[f],y=u.id;for(;y&&y!==f;)b.push(y),y=a.get(y)??null;b.reverse(),l.push({edge:h,source:u.id,target:f,cycle:b})}else g===0&&(s.set(f,1),a.set(f,u.id),c.push({id:f,edges:e(f),idx:0}))}}return l}o(lf,"detectBackEdges");var Pb="team:",FU=/^[a-z0-9][a-z0-9-]*$/;function LU(t){if(!t.startsWith(Pb))return null;let e=t.slice(Pb.length);return e.length>0?e:null}o(LU,"teamKeyOfMember");function df(t){return`${Pb}${t}`}o(df,"teamMember");function Qo(t){let e=t.channels;return e===void 0?[]:(Array.isArray(e)||W("graph.channels must be an array"),e)}o(Qo,"readAuthoredChannels");function d_(t){return[...na(t)].sort()}o(d_,"derivedChannelTeamKeys");function c_(t,e){let n=t.toLowerCase().replace(/ä/g,"ae").replace(/ö/g,"oe").replace(/ü/g,"ue").replace(/ß/g,"ss").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"channel";if(!e.has(n))return n;for(let r=2;;r++){let i=`${n}-${r}`;if(!e.has(i))return i}}o(c_,"mintChannelKey");function u_(t,e){let n=t.channels;if(n===void 0)return[];if(!Array.isArray(n))return[{path:"channels",reason:"[channels/shape] graph.channels muss eine Liste sein."}];let r=[],i=na(t),s=new Set,a=new Map;return n.forEach((l,d)=>{let c=`channels[${d}]`,u=l;if(u===null||typeof u!="object"||typeof u.key!="string"||wt(u.label)==="not-localized"||!Array.isArray(u.members)||!u.members.every(S=>typeof S=="string")){r.push({path:c,reason:"[channels/shape] Ein Kanal braucht key, label ({ de, en }) und members (Liste von Texten)."});return}let f=`Kanal "${u.key}"`;FU.test(u.key)||r.push({path:`${c}.key`,reason:`[channels/invalidKey] ${f}: Schl\xFCssel nur aus Kleinbuchstaben, Ziffern und Bindestrich.`}),s.has(u.key)&&r.push({path:`${c}.key`,reason:`[channels/duplicateKey] ${f}: Schl\xFCssel ist doppelt vergeben.`}),s.add(u.key);let h=wt(u.label);if(h!=="not-localized"&&h.length===2?r.push({path:`${c}.label`,reason:`[channels/emptyLabel] ${f}: Bezeichnung fehlt.`}):h!=="not-localized"&&h.length>0&&r.push({path:`${c}.label`,reason:`[i18n/missingTranslation] ${f}: Bezeichnung fehlt in: ${h.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`}),u.members.length===0){r.push({path:`${c}.members`,reason:`[channels/emptyMembers] ${f}: mindestens ein Team.`});return}let g=[];for(let S of u.members){let A=LU(S);if(A===null){r.push({path:`${c}.members`,reason:`[channels/invalidMember] ${f}: "${S}" ist kein "team:<schl\xFCssel>".`});continue}if(g.includes(A)){r.push({path:`${c}.members`,reason:`[channels/duplicateMember] ${f}: Team "${A}" ist doppelt genannt.`});continue}e!==void 0&&!e.has(A)&&r.push({path:`${c}.members`,reason:`[channels/unknownTeam] ${f}: Team "${A}" gibt es in diesem Mandanten nicht (oder es ist die Bewerbergruppe).`}),g.push(A)}if(g.length===0)return;let b=[...g].sort().join("+"),[y]=g;g.length===1&&y!==void 0&&i.has(y)&&r.push({path:`${c}.members`,reason:`[channels/duplicatesDerived] ${f}: Team "${y}" ist am Prozess beteiligt und hat seinen Kanal schon automatisch.`});let w=a.get(b);w!==void 0?r.push({path:`${c}.members`,reason:`[channels/duplicateMembership] ${f}: dieselben Teams wie Kanal "${w}" \u2014 zwei Tabs w\xE4ren derselbe Chat.`}):a.set(b,u.key)}),r}o(u_,"channelIssues");function Yo(t){let e=[],n=[];function r(y,w){try{return Ft(y)}catch(S){e.push({path:w,src:y,reason:S instanceof Error?S.message:String(S)});return}}o(r,"tryParse");function i(y,w){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${w}.visibleIf`):void 0,requiredIf:y.requiredIf?r(y.requiredIf,`${w}.requiredIf`):void 0,disabledIf:y.disabledIf?r(y.disabledIf,`${w}.disabledIf`):void 0,defaultValue:y.defaultValue?r(y.defaultValue,`${w}.defaultValue`):void 0}}o(i,"compileField");function s(y,w){return{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${w}.visibleIf`):void 0,fields:y.fields.map((S,A)=>i(S,`${w}.fields[${A}]`))}}o(s,"compileGroup");function a(y,w){return{...y,itemTemplate:y.itemTemplate.map((S,A)=>i(S,`${w}.itemTemplate[${A}]`)),effects:y.effects?.map((S,A)=>d(S,`${w}.effects[${A}]`)),itemVisibleIf:y.itemVisibleIf?r(y.itemVisibleIf,`${w}.itemVisibleIf`):void 0}}o(a,"compileRepeated");function l(y,w){let S=[];return y.fields.forEach((A,T)=>{if(A.externalFlag){n.push({key:A.key,label:A.label,defaultValue:A.defaultValue?r(A.defaultValue,`${w}.fields[${T}].defaultValue`):void 0});return}S.push(i(A,`${w}.fields[${T}]`))}),{...y,visibleIf:y.visibleIf?r(y.visibleIf,`${w}.visibleIf`):void 0,fields:S,groups:y.groups?.map((A,T)=>s(A,`${w}.groups[${T}]`)),computed:y.computed?.map((A,T)=>{let N=r(A.expression,`${w}.computed[${T}].expression`);return{key:A.key,expression:N??{kind:"null"}}}),subsections:y.subsections?.map((A,T)=>l(A,`${w}.subsections[${T}]`)),repeated:y.repeated?.map((A,T)=>a(A,`${w}.repeated[${T}]`)),validators:y.validators}}o(l,"compileSection");function d(y,w){return{...y,when:y.when?r(y.when,`${w}.when`):void 0}}o(d,"compileEffect");function c(y,w){let S=r(y.when,`${w}.when`);return S?{...y,when:S}:null}o(c,"compileOutcome");let u=t.sections.map((y,w)=>l(y,`sections[${w}]`)),f=(t.effects??[]).map((y,w)=>d(y,`effects[${w}]`)),h=[],g=t.outcomes??[];for(let y=0;y<g.length;y++){let w=g[y],S=c(w,`outcomes[${y}]`);S&&h.push(S)}return{compiled:{...t,sections:u,effects:f,outcomes:h,flags:n},errors:e}}o(Yo,"compileForm");var Te=o((t,e)=>({de:t,en:e}),"lt"),Nb={konfession:[{value:"roemisch_katholisch",label:Te("R\xF6misch-katholisch","Roman Catholic")},{value:"evangelisch",label:Te("Evangelisch","Protestant")},{value:"orthodox",label:Te("Orthodox","Orthodox")},{value:"juedisch",label:Te("J\xFCdisch","Jewish")},{value:"muslimisch",label:Te("Muslimisch","Muslim")},{value:"sonstige",label:Te("Sonstige","Other")},{value:"keine",label:Te("Keine","None")}],geschlecht:[{value:"female",label:Te("weiblich","Female")},{value:"male",label:Te("m\xE4nnlich","Male")},{value:"diverse",label:Te("divers","Diverse")}],staatsangehoerigkeit:[{value:"deutschland",label:Te("Deutschland","Germany")},{value:"tuerkei",label:Te("T\xFCrkei","Turkey")},{value:"polen",label:Te("Polen","Poland")},{value:"syrien",label:Te("Syrien","Syria")},{value:"ukraine",label:Te("Ukraine","Ukraine")},{value:"ohne_angabe",label:Te("Ohne Angabe","Not specified")}],foerderbereich:[{value:"lrs",label:Te("LRS (Lese-Rechtschreib-Schw\xE4che)","Dyslexia")},{value:"dyskalkulie",label:Te("Dyskalkulie","Dyscalculia")},{value:"adhs",label:Te("ADHS","ADHD")},{value:"sprache",label:Te("Sprachf\xF6rderung","Language support")},{value:"sozial_emotional",label:Te("Sozial-emotional","Social-emotional")},{value:"inklusion",label:Te("Inklusion (k\xF6rperlich)","Physical inclusion support")},{value:"hochbegabung",label:Te("Hochbegabung","Giftedness")}],religionsunterricht:[{value:"roemisch_katholisch",label:Te("Katholisch","Catholic")},{value:"evangelisch",label:Te("Evangelisch","Protestant")},{value:"juedisch",label:Te("J\xFCdisch","Jewish")},{value:"ethik",label:Te("Ethik","Ethics")},{value:"abmeldung",label:Te("Abmeldung","Opt out")}],beziehung:[{value:"mutter",label:Te("Mutter","Mother")},{value:"vater",label:Te("Vater","Father")},{value:"grosselternteil",label:Te("Gro\xDFeltern","Grandparents")},{value:"tante_onkel",label:Te("Tante / Onkel","Aunt / Uncle")},{value:"geschwister",label:Te("Geschwister","Sibling")},{value:"pflegeeltern",label:Te("Pflegeeltern","Foster parents")},{value:"sonstige",label:Te("Sonstige","Other")}],klassenstufe:[{value:"1",label:Te("Klasse 1","Grade 1")},{value:"2",label:Te("Klasse 2","Grade 2")},{value:"3",label:Te("Klasse 3","Grade 3")},{value:"4",label:Te("Klasse 4","Grade 4")},{value:"5",label:Te("Klasse 5","Grade 5")},{value:"6",label:Te("Klasse 6","Grade 6")},{value:"kita",label:Te("Kita / Vorschule","Daycare / Preschool")},{value:"andere",label:Te("Andere Einrichtung","Other institution")}]};function f_(t){return Nb[t]}o(f_,"getEnumOptions");function MU(t,e){return t.enumOptionLabels?.[e]??{de:e,en:e}}o(MU,"inlineEnumOptionLabel");function p_(t){return t.enumRef?f_(t.enumRef).map(e=>({value:e.value,label:t.enumOptionLabels?.[e.value]??e.label})):(t.enumOptions??[]).map(e=>({value:e,label:MU(t,e)}))}o(p_,"resolveEnumOptions");var qU=new Set(["decision","review","governedDocument"]);function h_(t){return qU.has(t.type)&&!(t.type==="governedDocument"&&t.production==="none")}o(h_,"isReadinessGatedNode");function BU(t){let e=new Map,n=KU(t),r=o((i,s)=>{let a=Db(s),l=[...i.fields,...(i.groups??[]).flatMap(d=>d.fields)];for(let d of l)d.externalFlag!==!0&&e.set(d.key,{kind:"entered",key:d.key,label:d.label,qualifier:VU(d.bucket,n,a),section:a,type:d.type,options:m_(d),repeated:!1});for(let d of i.repeated??[])for(let c of d.itemTemplate){let u=`${d.key}.${c.key}`;e.set(u,{kind:"entered",key:u,label:c.label,qualifier:Db(d),section:a,type:c.type,options:m_(c),repeated:!0})}for(let d of i.computed??[]){let c=dt(Ft(d.expression));e.set(d.key,{kind:"computed",key:d.key,label:d.label??{de:d.key,en:d.key},qualifier:a,deps:c})}for(let d of i.subsections??[])r(d,s)},"visit");for(let i of t.sections)r(i,i);return e}o(BU,"formFieldCatalog");function m_(t){return t.type==="enum"?p_(t):null}o(m_,"enumOptionsOf");function VU(t,e,n){return t===void 0?n:e.get(t)??n}o(VU,"fieldQualifier");function KU(t){let e=new Map,n=o((r,i)=>{i===void 0||e.has(r)||e.set(r,Db(i))},"add");for(let r of y_(t))r.kind==="person"?n(r.bucket,r.display):r.kind==="organization"&&n(r.id.replace(/^o\./,""),r.display);return e}o(KU,"bucketWordings");function g_(t){return t.flatMap(e=>[e,...g_(e.subsections??[])])}o(g_,"allSections");function y_(t){return[...t.effects,...g_(t.sections).flatMap(e=>(e.repeated??[]).flatMap(n=>n.effects??[]))]}o(y_,"allEffects");function Db(t){return{label:t.label}}o(Db,"wordingOf");function b_(t){return Eu(t).flatMap(({slot:e,address:n})=>{let r=fT(n);return r===null||Fa.includes(r.path)?[]:[{slotId:e,owner:r.owner,fieldKey:r.path}]})}o(b_,"admissionBindingLeaves");function UU(t,e){let n=t.get(e);if(n===void 0)return null;let r=[],i=new Set,s=o(a=>{if(!i.has(a.key)&&(i.add(a.key),r.push({fieldKey:a.key,kind:a.kind}),a.kind==="computed"))for(let l of a.deps){let d=t.get(l);d!==void 0&&s(d)}},"walk");return s(n),r}o(UU,"expandKey");function jU(t){let e=new Set;for(let n of y_(t))if(!(n.kind!=="person"||n.contractParty===void 0)&&n.when!==void 0)for(let r of dt(Ft(n.when)))e.add(r);return[...e]}o(jU,"contractPartyConditionKeys");function GU(t){return Yo(t).compiled.flags.map(e=>({key:e.key,name:e.label}))}o(GU,"formExternalFlags");function w_(t){return{readinessFormFieldsByFormNode:new Map([...t].map(([e,n])=>[e,BU(n)])),readinessPartyConditionKeysByFormNode:new Map([...t].map(([e,n])=>[e,new Set(jU(n))])),formFlagKeysByFormNode:new Map([...t].map(([e,n])=>[e,new Set(GU(n).map(r=>r.key))]))}}o(w_,"readinessUniverse");function Fb(t,e){let n=new Set;for(let r of e)for(let i of UU(t,r)??[])i.kind==="entered"&&n.add(i.fieldKey);return n}o(Fb,"enteredFieldsBehind");var WU=new Set(["label","sublabel","title","description","body","chipLabel","nextAction","confirmLabel","placeholder","helpText","subject","heading","hint","reason"]);function zU(t){return WU.has(t)?!0:v_(t)?!1:/(Label|Title|Body|Description|Text|Hint|Heading|Placeholder)$/.test(t)}o(zU,"isTextKey");function v_(t){return/^localized[A-Z]/.test(t)}o(v_,"isLegacyTwinKey");var HU=new Set(["titles","responseLabels","outputLabels","enumOptionLabels"]),QU=new Set(["inputs","resolver","library"]);function cf(t,e){let n=[];return Lb(t,e,n),n}o(cf,"findUnlocalizedTexts");function Lb(t,e,n){if(Array.isArray(t)){t.forEach((i,s)=>Lb(i,`${e}[${JU(i,s)}]`,n));return}if(t===null||typeof t!="object")return;let r=t;for(let[i,s]of Object.entries(r)){let a=`${e}.${i}`;if(!QU.has(i)){if(v_(i)){n.push({path:a,missing:"legacy-twin"});continue}if(zU(i)){YU(s,a,n);continue}if(HU.has(i)&&s!==null&&typeof s=="object"){for(let[l,d]of Object.entries(s))d!==void 0&&S_(d,`${a}.${l}`,n);continue}Lb(s,a,n)}}}o(Lb,"walk");function YU(t,e,n){t!=null&&S_(t,e,n)}o(YU,"checkText");function S_(t,e,n){let r=wt(t);(r==="not-localized"||r.length>0)&&n.push({path:e,missing:r})}o(S_,"report");function JU(t,e){if(t!==null&&typeof t=="object"){let n=t;if(typeof n.id=="string")return n.id;if(typeof n.key=="string")return n.key}return String(e)}o(JU,"keyOf");function k_(t){return t==="not-localized"?"ist kein zweisprachiger Text ({ de, en })":t==="legacy-twin"?'ist ein Zwilling der alten Form \u2014 der Text geh\xF6rt in das Feld ohne \u201Elocalized"':`fehlt in: ${t.join(", ")}`}o(k_,"describe");function Mb({path:t,missing:e}){return e==="legacy-twin"?`[i18n/legacyTwin] ${t} ${k_(e)}.`:`[i18n/missingTranslation] ${t} ${k_(e)} \u2014 jeder angezeigte Text braucht Deutsch und Englisch; die Sprache folgt dem Konto des Lesenden.`}o(Mb,"unlocalizedTextReason");var ZU={engagePush:["engage"]};function XU(t){let e=ZU[t.type];return e===void 0?t:Object.fromEntries(Object.entries(t).filter(([n])=>!e.includes(n)))}o(XU,"withoutMachineData");function x_(t,e){return[...cf(t.nodes.map(XU),"nodes"),...e===void 0?[]:cf(e,`layout.${e.id}`)].map(r=>({layer:"GRAPH",kind:"i18n",path:r.path,reason:Mb(r),severity:"error"}))}o(x_,"checkLocalizedTexts");var Jo=5,Zo=480;function mr(t){return typeof t=="string"&&t.trim().length>0}o(mr,"isNonEmptyString");function R_(t,e,n){return Object.keys(t).filter(r=>!e.includes(r)).map(r=>({field:`result.${r}`,code:qe.unknownField,message:`Unbekanntes Feld '${r}' im ${n}; erlaubt sind: ${e.join(", ")}.`}))}o(R_,"unknownFieldIssues");function e1(t){let e=[],n=t.title;(n===void 0||typeof n!="object"||n===null||!mr(n.de)||!mr(n.en))&&e.push({field:"result.title",code:qe.appointmentMissingTitle,message:"Ein Termin-Ergebnis braucht einen neutralen Titel in beiden Sprachen ({ de, en }) \u2014 er steht in der Mail und in der Kalenderdatei der Familie, deshalb nie ein Familienname."});let r=t.durationMinutes;return(typeof r!="number"||!Number.isInteger(r)||r<Jo||r>Zo)&&e.push({field:"result.durationMinutes",code:qe.appointmentInvalidDuration,message:`'durationMinutes' muss eine ganze Zahl von ${Jo} bis ${Zo} sein, erhalten ${JSON.stringify(r)}.`}),e.push(...R_(t,["kind","title","durationMinutes"],"Termin-Ergebnis")),e}o(e1,"appointmentIssues");function A_(t){if(typeof t!="object"||t===null)return!1;let e=t;return mr(e.de)&&mr(e.en)}o(A_,"isBilingual");var E_=["key","type","label","writes","options","min","suggest","evidence","evidenceFrom"];function t1(t){let e=o((i,s)=>({field:i,code:qe.recordFields,message:s}),"issue");if(!Array.isArray(t)||t.length===0)return[e("result.fields","Eine Erfassung braucht mindestens ein Feld ('result.fields').")];let n=[],r=new Set;for(let[i,s]of t.entries()){let a=`result.fields[${i}]`;if(typeof s!="object"||s===null||Array.isArray(s)){n.push(e(a,"Ein Feld der Erfassung muss ein Objekt sein."));continue}let l=s,d=l.key;typeof d!="string"||!/^[a-z][a-zA-Z0-9_]*$/.test(d)?n.push(e(`${a}.key`,`Feld-Schl\xFCssel ${JSON.stringify(d)} \u2014 erlaubt sind Buchstaben, Ziffern und _, beginnend mit einem Kleinbuchstaben.`)):r.has(d)?n.push(e(`${a}.key`,`Feld-Schl\xFCssel "${d}" ist doppelt.`)):r.add(d);let c=typeof d=="string"?`"${d}"`:`Nr. ${i+1}`;if(ly(l.type)||n.push(e(`${a}.type`,`Feld ${c}: Typ ${JSON.stringify(l.type)} \u2014 erlaubt: ${ay.join(", ")}.`)),A_(l.label)||n.push(e(`${a}.label`,`Feld ${c} braucht ein Label in beiden Sprachen ({ de, en }).`)),mr(l.writes)||n.push(e(`${a}.writes`,`Feld ${c} schreibt in keinen Vorgangs-Schl\xFCssel ('writes') \u2014 ein Wert, den niemand lesen kann, geh\xF6rt nicht in eine Erfassung.`)),l.type==="enum"){let f=Array.isArray(l.options)?l.options:[],h=f.map(g=>g.key);(f.length<2||h.some(g=>typeof g!="string"||g.length===0)||new Set(h).size!==h.length||f.some(g=>!A_(g.label)))&&n.push(e(`${a}.options`,`Feld ${c} (Auswahl) braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln und Labels in beiden Sprachen.`))}else l.options!==void 0&&n.push(e(`${a}.options`,`Feld ${c}: 'options' gibt es nur bei Typ 'enum'.`));if(l.min!==void 0&&(l.type!=="number"||typeof l.min!="number"||!Number.isInteger(l.min))&&n.push(e(`${a}.min`,`Feld ${c}: 'min' gibt es nur bei Typ 'number', als ganze Zahl.`)),l.evidence!==void 0&&typeof l.evidence!="boolean"&&n.push(e(`${a}.evidence`,`Feld ${c}: 'evidence' ist true oder false.`)),l.evidenceFrom!==void 0){let f=typeof l.min=="number"?l.min:0;(l.type!=="number"||l.evidence!==!0||typeof l.evidenceFrom!="number"||!Number.isInteger(l.evidenceFrom)||l.evidenceFrom<=f)&&n.push(e(`${a}.evidenceFrom`,`Feld ${c}: 'evidenceFrom' gibt es nur bei Typ 'number' mit 'evidence', als ganze Zahl \xFCber dem Minimum (${f}) \u2014 sonst g\xE4lte der Nachweis immer.`))}if(l.suggest!==void 0){let f=l.suggest,h=typeof f=="object"&&f!==null?f.kind:void 0;h==="form"&&"address"in f&&Object.keys(f).length===2&&(!Se(f.address)||Xe(f.address))||h==="siblingRank"&&Object.keys(f).length===1&&l.type==="number"||n.push({field:`${a}.suggest`,code:qe.recordSuggest,message:`Feld ${c}: Vorschlag ${JSON.stringify(l.suggest)} \u2014 erlaubt: { kind: 'form', address: '$node.<formular>.admission.<export>' } oder { kind: 'siblingRank' } (nur bei Typ 'number'); bekannte Arten: ${rT.join(", ")}.`})}let u=Object.keys(l).filter(f=>!E_.includes(f));u.length>0&&n.push(e(a,`Feld ${c}: unbekannte Angabe ${u.map(f=>`'${f}'`).join(", ")}; erlaubt: ${E_.join(", ")}.`))}return n}o(t1,"recordFieldIssues");function n1(t,e,n){let r=[],i=e.options;if(t==="choice"){let s=Array.isArray(i)?i:[],a=s.map(l=>l.key);(s.length<2||a.some(l=>typeof l!="string"||l.length===0)||new Set(a).size!==a.length)&&r.push({field:"result.options",code:qe.choiceOptions,message:`Ein Auswahl-Ergebnis braucht mindestens 2 Optionen mit eindeutigen Schl\xFCsseln, erhalten ${JSON.stringify(a)}.`})}else i!==void 0&&r.push({field:"result.options",code:qe.choiceOptions,message:`'result.options' gibt es nur bei 'choice' \u2014 ${t==="recommendation"?"eine Empfehlung hat die festen Tendenzen Positiv/Neutral/Negativ":"ein Freitext hat keine Auswahl"}.`});if(t==="pricedItem"){let s=e.item;if(!mr(s))r.push({field:"result.item",code:qe.pricedItemMissingItem,message:"Ein Preispositions-Ergebnis nennt den Artikel, den es bepreist \u2014 'result.item' (der Schl\xFCssel des Artikels, z. B. 'tuition') fehlt."});else if(n.billingItemKeys!==void 0&&!n.billingItemKeys.has(s))r.push({field:"result.item",code:qe.pricedItemUnknownItem,message:`'result.item' "${s}" \u2014 kein Artikel dieses Mandanten tr\xE4gt diesen Schl\xFCssel (bekannt: ${[...n.billingItemKeys].join(", ")||"keine"}).`});else if(n.offerProgram===null)r.push({field:"result.item",code:qe.pricedItemOfferWithoutProgram,message:`'result.item' "${s}" \u2014 das Angebot ist keinem Programm zugeordnet, also geh\xF6rt kein Artikel zu ihm; dem Angebot ein Programm geben.`});else if(n.offerProgram!==void 0&&!n.offerProgram.billingItemKeys.has(s)){let l=n.offerProgram;r.push({field:"result.item",code:qe.pricedItemNotInProgram,message:`'result.item' "${s}" \u2014 der Artikel ist dem Programm \u201E${l.nameDe}\u201C des Angebots nicht zugeordnet (zugeordnet: ${[...l.billingItemKeys].join(", ")||"keine"}); unter Finanzen \u2192 Artikel zuordnen, direkt oder \xFCber ein Paket.`})}let a=e.label;(typeof a!="object"||a===null||!mr(a.de)||!mr(a.en))&&r.push({field:"result.label",code:qe.labelMissing,message:"Ein Preispositions-Ergebnis braucht einen Namen f\xFCr seinen Wert in beiden Sprachen ('result.label', z. B. { de: 'Schulgeld mit Erm\xE4\xDFigung', en: 'Tuition after reduction' }) \u2014 so hei\xDFt er im Workflow und in der Verdrahtung."})}else e.item!==void 0&&r.push({field:"result.item",code:qe.itemOnNonPricedItem,message:`'result.item' gibt es nur bei 'pricedItem' \u2014 ein ${t}-Ergebnis bepreist keinen Artikel.`});if(t==="record"?(r.push(...t1(e.fields)),e.writes!==void 0&&r.push({field:"result.writes",code:qe.writesOnProse,message:"Eine Erfassung schreibt je Feld ('fields[].writes'), nie als Ganzes ('result.writes')."}),e.label!==void 0&&r.push({field:"result.label",code:qe.unknownField,message:"Eine Erfassung benennt ihre Werte je Feld ('fields[].label'), nicht als Ganzes ('result.label')."})):e.fields!==void 0&&r.push({field:"result.fields",code:qe.fieldsOnNonRecord,message:`'result.fields' gibt es nur bei 'record' \u2014 ein ${t}-Ergebnis hat keine Felder.`}),t==="reduction"?(mr(e.writes)||r.push({field:"result.writes",code:qe.reductionPrices,message:"Eine Reduktion schreibt ihren Betrag in einen Vorgangs-Schl\xFCssel vom Typ reduction ('result.writes') \u2014 sonst l\xE4se ihn kein Preis."}),mr(e.prices)||r.push({field:"result.prices",code:qe.reductionPrices,message:"Eine Reduktion nennt den abgeleiteten Preis, den sie senkt ('result.prices') \u2014 gegen seine Untergrenze wird der Betrag bei der Eingabe gepr\xFCft."})):e.prices!==void 0&&r.push({field:"result.prices",code:qe.pricesOnNonReduction,message:`'result.prices' gibt es nur bei 'reduction' \u2014 ein ${t}-Ergebnis senkt keinen Preis.`}),e.writes!==void 0&&(t==="freetext"||t==="recommendation")&&r.push({field:"result.writes",code:qe.writesOnProse,message:`'result.writes' gibt es nur bei Ergebnissen mit Wert (Auswahl, Preisposition) \u2014 ein ${t}-Ergebnis bleibt im Chat und schreibt nichts in den Vorgang.`}),t==="freetext"&&e.textRequired!==void 0&&r.push({field:"result.textRequired",code:qe.textRequiredOnFreetext,message:"'textRequired' auf einem Freitext-Ergebnis \u2014 der Text eines Freitexts ist immer Pflicht; die Angabe entfernen."}),e.chat===void 0)r.push({field:"result.chat",code:qe.chatMissing,message:"Ein Aufgaben-Ergebnis steht nur im Chat \u2014 'result.chat' fehlt: 'all', 'team:<Gruppe>' oder einen Kanal des Workflows angeben."});else{let s=e.chat,a=typeof s=="string"?wu(s):null;s==="external"||a===null?r.push({field:"result.chat",code:qe.chatExternal,message:`'result.chat' ${JSON.stringify(s)} \u2014 ein Aufgaben-Ergebnis bleibt intern: erlaubt sind 'all', 'team:<Gruppe>' oder ein Kanal des Workflows, nie 'external'.`}):a.kind==="channel"&&!n.channelKeys.has(a.channelKey)?r.push({field:"result.chat",code:qe.chatUnknownChannel,message:`'result.chat' "${a.channelKey}" ist weder 'all' noch 'team:<Gruppe>' noch ein Kanal des Workflows (bekannt: ${[...n.channelKeys].join(", ")||"keine"}).`}):a.kind==="team"&&n.teamKeys!==void 0&&!n.teamKeys.has(a.groupKey)&&r.push({field:"result.chat",code:qe.chatUnknownChannel,message:`'result.chat' "team:${a.groupKey}" \u2014 keine Mitarbeitenden-Gruppe dieses Mandanten hei\xDFt so.`})}return e.files!==void 0&&(e.files!==!0||!Ui({kind:t,writes:e.writes}))&&r.push({field:"result.files",code:qe.filesOnKind,message:e.files!==!0?`'result.files' ist nur 'true' \u2014 ohne Dateien entf\xE4llt das Feld (erhalten ${JSON.stringify(e.files)}).`:`'result.files' gibt es nur bei Freitext, Empfehlung oder einer Auswahl ohne 'writes' \u2014 ein ${t}-Ergebnis${e.writes!==void 0?" mit Wert":""} nimmt keine Dateien (eine Erfassung belegt je Feld mit 'evidence').`}),r.push(...R_(e,["kind","options","textRequired","chat","item","label","writes","fields","prices","files"],"Aufgaben-Ergebnis")),r}o(n1,"recordedIssues");function T_(t,e,n={channelKeys:new Set}){if(e===void 0)return[];if(t!=="task")return[{field:"result",code:qe.onApproval,message:`'result' gilt nur f\xFCr die Art 'task' \u2014 eine '${t}' wird durch ihr Votum abgeschlossen, nicht durch ein Ergebnis.`}];if(typeof e!="object"||e===null||Array.isArray(e))return[{field:"result",code:qe.unknownKind,message:`'result' muss ein Objekt mit 'kind' sein; bekannte Arten: ${yu.join(", ")}.`}];let r=e;return nT(r.kind)?r.kind==="appointment"?e1(r):n1(r.kind,r,n):[{field:"result.kind",code:qe.unknownKind,message:`Unbekannte Ergebnisart ${JSON.stringify(r.kind)}; bekannte Arten: ${yu.join(", ")}.`}]}o(T_,"taskResultIssues");var I_=60;function Nr(t,e){return{layer:"GRAPH",kind:"nodeRule",path:t,reason:e,severity:"error"}}o(Nr,"error");function r1(t,e){return{layer:"GRAPH",kind:"nodeRule",path:t,reason:e,severity:"warning"}}o(r1,"warning");function $_(t){return Array.isArray(t.tasks)?t.tasks:[]}o($_,"tasksOf");function O_(t,e){return(Array.isArray(t.optionalActions)?t.optionalActions:[]).filter(r=>r.action==="spawnTasks"&&Array.isArray(r.tasks)&&r.tasks.includes(e))}o(O_,"spawnActionsOf");function __(t,e){return O_(t,e).map(n=>String(n.key)).sort()}o(__,"bindingsOf");function C_(t,e){let n=[],r=$_(t),i=new Map;for(let s of r){if(s.appointment===void 0)continue;let a=typeof s.key=="string"?s.key:"?",l=`nodes.${t.id}.tasks.${a}`,d=`Terminaufgabe "${a}" (Knoten "${t.id}")`,c=s.appointment,f=typeof c=="object"&&c!==null&&Object.keys(c).every(T=>T==="of"||T==="dueDaysAfterEnd")&&typeof c.of=="string"?c.of:void 0,h=f===void 0?void 0:r.find(T=>T.key===f),g=h?.result;if(f===void 0||h===void 0||g?.kind!=="appointment")n.push(Nr(`${l}.appointment.of`,`[workItems/appointmentOfUnknown] ${d} braucht 'appointment: { of, dueDaysAfterEnd }', und 'of' nennt eine Aufgabe desselben Knotens, die mit einem Termin abschlie\xDFt (result.kind 'appointment'); erhalten ${JSON.stringify(s.appointment)}.`));else{i.set(f,(i.get(f)??0)+1);let T=h.blocks,N=[...["when","optional"].filter(F=>h[F]!==void 0),...typeof T?.node=="string"&&T.node!==t.id?["blocks"]:[]];N.length>0&&n.push(Nr(`nodes.${t.id}.tasks.${f}.${N[0]}`,`[workItems/appointmentTaskShape] "${f}" bucht den Termin f\xFCr ${d} und tr\xE4gt ${N.map(F=>F==="blocks"?"ein knoten\xFCbergreifendes 'blocks'":`'${F}'`).join(", ")} \u2014 fiele sie ohne Buchung weg oder \xFCberlebte sie ihren Knoten, wartete die Terminaufgabe f\xFCr immer bzw. f\xE4nde die Buchung keine Terminaufgabe mehr.`));for(let F of O_(t,f))F.repeatable!==!0&&n.push(Nr(`nodes.${t.id}.optionalActions.${String(F.key)}.repeatable`,`[workItems/appointmentActionRepeatable] Die optionale Aktion "${String(F.key)}" legt "${f}" an, die den Termin f\xFCr ${d} bucht, und ist nicht 'repeatable: true'. Eine Absage beendet die Runde; ohne zweite Runde lie\xDFe sich die Aktion nie wieder ausl\xF6sen, und eine Entscheidung, die auf sie wartet (requiresOneOf), bliebe h\xE4ngen.`));__(t,a).join(",")!==__(t,f).join(",")&&n.push(Nr(`${l}.appointment.of`,`[workItems/appointmentTaskBinding] ${d} geh\xF6rt zu anderen optionalen Aktionen als "${f}", die ihren Termin bucht \u2014 beide Zeilen sind eine Runde: entweder beide in derselben Aktion (spawnTasks) oder beide in keiner.`))}let b=c?.dueDaysAfterEnd;(typeof b!="number"||!Number.isInteger(b)||b<0||b>I_)&&n.push(Nr(`${l}.appointment.dueDaysAfterEnd`,`[workItems/appointmentTaskDue] ${d}: 'dueDaysAfterEnd' ist eine ganze Zahl von 0 bis ${I_} \u2014 die Tage nach dem Terminende, bis die Aufgabe f\xE4llig ist; erhalten ${JSON.stringify(b)}.`)),s.params?.dueInDays!==void 0&&n.push(Nr(`${l}.params.dueInDays`,`[workItems/appointmentTaskDue] ${d} tr\xE4gt 'params.dueInDays' neben 'appointment.dueDaysAfterEnd' \u2014 eine Terminaufgabe ist ab dem Terminende f\xE4llig, nie ab ihrer Anlage.`));let y=s.result,w=[...s.kind!=="task"?["'kind: approval'"]:[],...s.assign?.userId!==void 0?["'assign.userId'"]:[],...y===void 0||!ri(y.kind)?["kein erfasstes Ergebnis (Feedback)"]:[],...["when","optional","familyRequest","reads","locksEvidence"].filter(T=>s[T]!==void 0).map(T=>`'${T}'`),...typeof s.blocks?.node=="string"&&s.blocks.node!==t.id?["ein knoten\xFCbergreifendes 'blocks'"]:[]];w.length>0&&n.push(Nr(`${l}.appointment`,`[workItems/appointmentTaskShape] ${d}: ${w.join(", ")} \u2014 eine Terminaufgabe ist eine Aufgabe, die mit ihrem Feedback (Freitext, Empfehlung, Auswahl) abschlie\xDFt, und sie entsteht, weil der Termin entsteht: ohne Bedingung, nicht optional, keine Nachforderung, ohne Belege (nichts l\xE4sst sie ungebunden neu entstehen) und an ihrem Knoten.`));let S=s.result?.chat,A=s.assign?.group;typeof S=="string"&&S.startsWith("team:")&&typeof A=="string"&&S!==`team:${A}`&&n.push(r1(`${l}.result.chat`,`[workItems/appointmentChatUnreadable] ${d} schreibt ihr Feedback in "${S}", geh\xF6rt aber dem Team "${A}" \u2014 die Gastgeberin bzw. der Gastgeber (ein Mitglied von "${A}") kann das eigene Feedback dort wom\xF6glich nicht lesen. 'team:${A}' oder 'all' w\xE4hlen, oder das Team als Mitglied des Chats sicherstellen.`));for(let T of e)for(let N of $_(T)){let F=N.blocks;F?.templateKey!==a||(typeof F.node=="string"?F.node:T.id)!==t.id||n.push(Nr(`nodes.${T.id}.tasks.${String(N.key)}.blocks.templateKey`,`[workItems/appointmentTaskBlocked] Task "${String(N.key)}" (Knoten "${T.id}") h\xE4lt ${d} zur\xFCck \u2014 eine Terminaufgabe wartet nur auf ihren Termin (abgeleitet aus 'appointment.of'); ein 'blocks' auf sie entf\xE4llt.`))}}for(let[s,a]of i)a<2||n.push(Nr(`nodes.${t.id}.tasks.${s}`,`[workItems/appointmentOfTwice] ${a} Terminaufgaben auf Knoten "${t.id}" geh\xF6ren zum Termin von "${s}" \u2014 ein Termin hat eine Terminaufgabe.`));return n}o(C_,"appointmentTaskIssues");var dn={notOptionalAction:"[workItems/familyRequestNotOptionalAction]",notTask:"[workItems/familyRequestNotTask]",closedOtherwise:"[workItems/familyRequestClosedOtherwise]",blocks:"[workItems/familyRequestBlocks]",noDeadline:"[workItems/familyRequestNoDeadline]",fields:"[workItems/familyRequestFields]",unknownField:"[workItems/familyRequestUnknownField]",shape:"[workItems/familyRequestShape]",twicePerAction:"[workItems/familyRequestTwicePerAction]",deadlock:"[workItems/familyRequestOnlyWayButAsked]"};function cn(t,e,n){return{layer:"GRAPH",kind:"nodeRule",path:t,reason:`${e} ${n}`,severity:"error"}}o(cn,"issue");function i1(t,e,n){return t.flatMap(r=>(Array.isArray(r.tasks)?r.tasks:[]).filter(i=>{let s=i.blocks,a=typeof s?.node=="string"?s.node:r.id;return s?.templateKey===n&&a===e}).map(i=>({nodeId:r.id,key:String(i.key)})))}o(i1,"blockersOf");function P_(t){let{graph:e,node:n,task:r}=t,i=r.familyRequest;if(i===void 0)return[];let s=typeof r.key=="string"?r.key:"?",a=`nodes.${n.id}.tasks.${s}`,l=`Task "${s}" auf Knoten \u201E${We(e,n.id,"de")}\u201C (${n.id})`,d=[];if(typeof i!="object"||i===null||Array.isArray(i))return[cn(`${a}.familyRequest`,dn.shape,`${l}: 'familyRequest' muss ein Objekt { fields } oder { from } sein.`)];let c=Object.keys(i).filter(b=>b!=="fields"&&b!=="from");c.length>0&&d.push(cn(`${a}.familyRequest.${c[0]}`,dn.shape,`${l}: 'familyRequest' kennt nur 'fields' oder 'from', nicht ${c.map(b=>`'${b}'`).join(", ")} \u2014 was angefordert wird und der Text an die Familie werden beim Ausl\xF6sen gew\xE4hlt.`));let{fields:u,from:f}=i;u===void 0==(f===void 0)&&d.push(cn(`${a}.familyRequest`,dn.shape,`${l}: 'familyRequest' nennt genau eines \u2014 'fields' (die anforderbaren Felder) oder 'from' (das Formular, dessen Dateifelder alle zur Wahl stehen).`)),t.onTrigger.has(s)||d.push(cn(`${a}.familyRequest`,dn.notOptionalAction,`${l} fordert bei der Familie an, geh\xF6rt aber zu keiner optionalen Aktion (spawnTasks) \u2014 nur deren Ausl\xF6sen \xF6ffnet die Anfrage an die Familie.`)),r.kind!=="task"&&d.push(cn(`${a}.kind`,dn.notTask,`${l} fordert bei der Familie an und muss die Art 'task' haben, nicht ${JSON.stringify(r.kind)}.`));for(let b of["result","when","locksEvidence","gatesNode"])r[b]!==void 0&&d.push(cn(`${a}.${b}`,dn.closedOtherwise,`${l} wartet auf die Familie und erledigt sich mit ihrer Antwort \u2014 '${b}' passt nicht dazu.`));r.blocks!==void 0&&d.push(cn(`${a}.blocks`,dn.blocks,`${l} wartet auf die Familie und darf nichts zur\xFCckhalten ('blocks') \u2014 sie h\xE4lt ihren Knoten schon als Aufgabe einer optionalen Aktion.`));for(let b of i1(e.nodes,n.id,s))d.push(cn(`nodes.${b.nodeId}.tasks.${b.key}.blocks`,dn.blocks,`Task "${b.key}" auf Knoten "${b.nodeId}" h\xE4lt ${l} zur\xFCck \u2014 eine Nachforderung darf nie zur\xFCckgehalten werden: zur\xFCckgehalten h\xE4tte sie keine Frist und k\xF6nnte mit der Antwort der Familie nicht erledigt werden.`));let h=r.params?.dueInDays;if((typeof h!="number"||!Number.isInteger(h)||h<1)&&d.push(cn(`${a}.params.dueInDays`,dn.noDeadline,`${l} fordert bei der Familie an und braucht eine Frist in ganzen Tagen ('params.dueInDays' \u2265 1) \u2014 sie ist die Frist der Familie und Anlass der Erinnerung.`)),u===void 0)return d;if(!Array.isArray(u)||u.length===0)return d.push(cn(`${a}.familyRequest.fields`,dn.fields,`${l}: 'familyRequest.fields' muss mindestens ein Feld eines Formulars nennen \u2014 oder statt dessen 'from' das Formular, dann stehen alle seine Dateifelder zur Wahl.`)),d;let g=new Set;for(let b of u){if(!Se(b))continue;let y=fe(b);if(g.has(y)){d.push(cn(`${a}.familyRequest.fields`,dn.fields,`${l}: 'familyRequest.fields' nennt ${nt(e,b,"de")} mehrfach.`));continue}g.add(y),Xe(b)||d.push(cn(`${a}.familyRequest.fields`,dn.unknownField,`${l}: 'familyRequest.fields' nennt ${nt(e,b,"de")} \u2014 anfordern l\xE4sst sich nur ein Feld eines Formulars ($node.<formular>.admission.<feld>).`))}return d}o(P_,"familyRequestIssues");function N_(t){let e=new Set((Array.isArray(t.tasks)?t.tasks:[]).flatMap(r=>r.familyRequest!==void 0&&typeof r.key=="string"?[r.key]:[]));return(Array.isArray(t.optionalActions)?t.optionalActions:[]).flatMap((r,i)=>{if(r.action!=="spawnTasks"||!Array.isArray(r.tasks))return[];let s=r.tasks.filter(a=>typeof a=="string"&&e.has(a));return s.length<=1?[]:[cn(`nodes.${t.id}.optionalActions.${i}.tasks`,dn.twicePerAction,`Optionale Aktion \u201E${String(r.key)}\u201C auf Knoten "${t.id}" startet ${s.length} Nachforderungen (${s.join(", ")}) \u2014 ein Ausl\xF6sen fragt die Familie nach EINER Sache; h\xF6chstens eine Nachforderung je Aktion.`)]})}o(N_,"familyRequestActionIssues");function D_(t,e){let n=t.nodes,r=new Map;for(let a of n)if(!(a.type!=="completenessCheck"||!Array.isArray(a.requires)))for(let l of a.requires)Xe(l)&&r.set(fe(l),l);if(r.size===0)return[];let i=o(a=>{let l=ur(e,a);return l===void 0||l!==null&&l.kind==="entered"&&l.type==="docRef"},"isFileField"),s=o(a=>{let{fields:l,from:d}=a??{};return Array.isArray(l)?l.filter(Xe):!Se(d)||d.scope!=="node"?[]:[...r.values()].filter(c=>c.owner===d.owner&&i(c))},"offeredBy");return n.flatMap(a=>{let l=Array.isArray(a.requiresOneOf)?a.requiresOneOf:[];if(l.length!==1)return[];let c=(Array.isArray(a.optionalActions)?a.optionalActions:[]).find(f=>f.key===l[0]);return c===void 0||!Array.isArray(c.tasks)?[]:(Array.isArray(a.tasks)?a.tasks:[]).flatMap(f=>{if(f.familyRequest===void 0||!c.tasks.includes(f.key))return[];let h=s(f.familyRequest).filter(g=>r.has(fe(g)));return h.length===0?[]:[{...cn(`nodes.${a.id}.requiresOneOf`,dn.deadlock,`Auf Knoten \u201E${We(t,a.id,"de")}\u201C (${a.id}) ist die Nachforderung \u201E${String(c.key)}\u201C der einzige Weg durch 'requiresOneOf', und eine Vollst\xE4ndigkeitspr\xFCfung fragt dieselben Felder an (${h.map(g=>nt(t,g,"de")).join(", ")}). Ist deren Anfrage offen, lassen sich diese Felder nicht nachfordern \u2014 die Entscheidung bliebe gesperrt. Eine zweite Aktion in 'requiresOneOf' oder andere Felder l\xF6sen das.`),severity:"warning"}]})})}o(D_,"familyRequestDeadlockWarnings");var F_={key:!0,kind:!0,title:!0,assign:!0,gatesNode:!0,blocks:!0,completableIf:!0,result:!0,when:!0,onConditionReturn:!0,reads:!0,locksEvidence:!0,description:!0,documents:!0,familyRequest:!0,optional:!0,appointment:!0,params:!0};function o1(t){let e=je(t);return new Map((typeof e.workItemTemplates=="function"?e.workItemTemplates(t):[]).map(n=>[n.key,n]))}o(o1,"intrinsicTemplatesOf");function L_(t,e,n){if(n!==void 0&&typeof n!="string")return null;let r=n??e,i=t.nodes.find(l=>l.id===r);if(i===void 0)return null;let s=i,a=je(i);return{node:s,composedKeys:new Set((Array.isArray(s.tasks)?s.tasks:[]).map(l=>l.key).filter(l=>typeof l=="string")),intrinsicByKey:o1(i),refuse:o(l=>typeof a.refuseBlocksTarget=="function"?a.refuseBlocksTarget(i,l):null,"refuse")}}o(L_,"resolveBlocksTargetNode");function s1(t){let e=new Map;for(let r of hn(t.nodes)){let i=e.get(r.source)??[];i.push(r.target),e.set(r.source,i)}let n=new Map;return r=>{let i=n.get(r);if(i!==void 0)return i;let s=new Set,a=[...e.get(r)??[]];for(;a.length>0;){let l=a.shift();s.has(l)||(s.add(l),a.push(...e.get(l)??[]))}return n.set(r,s),s}}o(s1,"reachability");function M_(t){let e=[],n=new Map;for(let s of t.nodes){let a=s;for(let l of Array.isArray(a.tasks)?a.tasks:[]){let d=typeof l.key=="string"?l.key:void 0,c=l.blocks;if(d===void 0||typeof c?.templateKey!="string")continue;let u=typeof c.node=="string"?c.node:s.id;n.set(`${s.id}::${d}`,`${u}::${c.templateKey}`)}}let r=new Map,i=o((s,a)=>{if(r.get(s)==="done")return;if(r.get(s)==="visiting"){let d=[...a.slice(a.indexOf(s)),s],[c,u]=s.split("::");e.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${c}.tasks.${u}.blocks`,reason:`[workItems/blocksCycle] Zyklus im 'blocks'-Graphen: ${d.map(f=>`"${f.replace("::"," \xB7 ")}"`).join(" \u2192 ")} \u2014 jedes Mitglied w\xFCrde auf ein anderes warten, keines w\xFCrde je frei.`,severity:"error"});return}r.set(s,"visiting");let l=n.get(s);l!==void 0&&n.has(l)&&i(l,[...a,s]),r.set(s,"done")},"walk");for(let s of n.keys())i(s,[]);return e}o(M_,"checkBlocksCycles");function a1(t){let{requiresOneOf:e,optionalActions:n}=t;if(!Array.isArray(e)||!Array.isArray(n))return new Set;let r=new Set(e.filter(s=>typeof s=="string")),i=new Set;for(let s of n)if(!(typeof s.key!="string"||!r.has(s.key)||!Array.isArray(s.tasks)))for(let a of s.tasks)typeof a=="string"&&i.add(a);return i}o(a1,"tasksOfRequiresOneOf");function q_(t){if(typeof t!="object"||t===null)return!1;let{de:e,en:n}=t;return typeof e=="string"&&e.trim().length>0&&typeof n=="string"&&n.trim().length>0}o(q_,"isFilledBilingual");var l1=["blocks","gatesNode","locksEvidence","completableIf"];function d1(t,e){let n=[],r=`Task "${e.key}" (Knoten "${e.nodeId}")`,i=t.optional;(!(typeof i=="object"&&i!==null&&Object.keys(i).every(d=>d==="skipLabel"))||!q_(i.skipLabel))&&n.push(It(`${e.base}.optional.skipLabel`,`[workItems/optionalSkipLabel] ${r} ist optional, braucht daf\xFCr '{ skipLabel: { de, en } }' \u2014 die Worte des Knopfs, mit dem die zust\xE4ndige Person ohne Ergebnis abschlie\xDFt (\u201EKeine Einsch\xE4tzung abgeben"); erhalten ${JSON.stringify(i)}.`)),t.kind!=="task"&&n.push(It(`${e.base}.optional`,`[workItems/optionalOnApproval] ${r} ist eine Freigabe \u2014 optional ist nur eine Aufgabe; eine Freigabe schlie\xDFt mit ihrem Urteil.`));let a=t.result;(a===void 0||typeof a.kind!="string"||!Ui({kind:a.kind,writes:a.writes}))&&n.push(It(`${e.base}.optional`,`[workItems/optionalNeedsProseResult] ${r} ist optional, schlie\xDFt aber ${a===void 0?"ohne Ergebnis":`mit einem ${String(a.kind)}-Ergebnis${a.writes!==void 0?" mit Wert":""}`} \u2014 optional ist nur eine Aufgabe mit Freitext, Empfehlung oder einer Auswahl ohne 'writes': einen Wert, den ein sp\xE4terer Schritt liest, g\xE4be es dann nie.`));let l=l1.filter(d=>t[d]!==void 0);return l.length>0&&n.push(It(`${e.base}.${l[0]}`,`[workItems/optionalHolds] ${r} ist optional und tr\xE4gt ${l.map(d=>`'${d}'`).join(", ")} \u2014 auf eine optionale Aufgabe wartet nichts: sie h\xE4lt keinen Schritt zur\xFCck. Entweder optional oder zur\xFCckhaltend.`)),e.requiredByRule&&n.push(It(`${e.base}.optional`,`[workItems/optionalInRequiresOneOf] ${r} ist optional, geh\xF6rt aber zu einer Aktion, die 'requiresOneOf' verlangt \u2014 \u201EKeine Einsch\xE4tzung abgeben" w\xFCrde die Regel erf\xFCllen, ohne dass etwas geschehen ist.`)),n}o(d1,"optionalTaskIssues");function It(t,e){return{layer:"GRAPH",kind:"nodeRule",path:t,reason:e,severity:"error"}}o(It,"issue");function B_(t,e){let n=[],r=s1(t),i=new Set(Qo(t).map(a=>a.key)),s=e?.chatTeamKeys;n.push(...D_(t,e));for(let a of t.nodes){let l=a,d=LT(l);n.push(...N_(l));let c=a1(l);n.push(...C_(l,t.nodes));for(let u of Array.isArray(l.tasks)?l.tasks:[]){let f=typeof u.key=="string"?u.key:"?",h=`nodes.${a.id}.tasks.${f}`,g=u.kind,b=u.result,y=u.blocks,w=typeof y?.node=="string"&&y.node!==a.id?y.node:void 0;if(typeof y?.templateKey=="string"){let P=typeof y.node=="string"?y.node:a.id,E=t.nodes.find(te=>te.id===P),q=(Array.isArray(E?.tasks)?E.tasks:[]).find(te=>te.key===y.templateKey)?.blocks;typeof q?.node=="string"&&q.node!==P&&n.push(It(`${h}.blocks.templateKey`,`[workItems/blocksCrossNodeTask] Task "${f}" auf Knoten "${a.id}" h\xE4lt "${y.templateKey}" auf Knoten "${P}" zur\xFCck \u2014 das ist selbst eine knoten\xFCbergreifende Aufgabe, die ihren Knoten \xFCberlebt; zur\xFCckgehalten k\xF6nnte sie nach dessen Verlassen weder bearbeitet noch freigegeben werden. Nur Aufgaben, die an ihrem Knoten bleiben, und intrinsische Vorlagen sind Ziele.`))}if(w!==void 0){let P=w;t.nodes.some(E=>E.id===P)&&!r(a.id).has(P)&&n.push(It(`${h}.blocks.node`,`[workItems/blocksTargetNotAfter] Task "${f}" auf Knoten "${a.id}" blockiert Knoten "${P}", der von hier aus nicht erreichbar ist \u2014 die Aufgabe entst\xFCnde erst, wenn ihr Ziel schon hinter dem Prozess liegt. Ziel ist derselbe Knoten oder ein sp\xE4terer.`)),(b===void 0||!ri(b.kind))&&n.push(It(`${h}.blocks.node`,`[workItems/crossNodeBlocksNeedsResult] Task "${f}" auf Knoten "${a.id}" blockiert einen anderen Knoten ("${P}"), hat aber kein 'result' \u2014 eine knoten\xFCbergreifende Aufgabe \xFCberlebt ihren Knoten und wird \xFCber ihr Ergebnis abgeschlossen (Freitext, Empfehlung oder Auswahl).`)),d.has(f)&&n.push(It(`${h}.blocks.node`,`[optionalAction/crossNodeBlocks] Task "${f}" geh\xF6rt zu einer optionalen Aktion (spawnTasks) auf Knoten "${a.id}" und darf keinen anderen Knoten blockieren \u2014 ihre Zeilen sind die Runde der Aktion.`))}for(let P of T_(String(g),b,{channelKeys:i,teamKeys:s,...e?.billingItemKeys!==void 0?{billingItemKeys:e.billingItemKeys}:{},...e?.offerProgram!==void 0?{offerProgram:e.offerProgram}:{}}))n.push(It(`${h}.${P.field}`,`${P.code} ${P.message} (Task "${f}" auf Knoten "${a.id}").`));if(b!==void 0){let P=u.assign?.group;(typeof P!="string"||P.length===0)&&n.push(It(`${h}.assign.group`,`${qe.needsTeam} Task "${f}" auf Knoten "${a.id}" hat ein Ergebnis, aber kein Team ('assign.group') \u2014 eine Aufgabe mit Ergebnis geh\xF6rt immer der Warteschlange eines Teams.`))}let S=u.when,A=o((P,E,M)=>{!Se(E)||Xe(E)||n.push(It(P,`[workItems/evidenceNotFormField] ${M} auf Task "${f}" (Knoten "${a.id}") nennt ${nt(t,E,"de")} \u2014 Bedingung und Belege einer Aufgabe sind Felder eines Formulars ($node.<formular>.admission.<feld>).`))},"notFormField");S!==void 0?(A(`${h}.when`,S,"'when'"),u.onConditionReturn!=="respawn"&&u.onConditionReturn!=="stayClosed"&&n.push(It(`${h}.onConditionReturn`,`[workItems/whenNeedsOnConditionReturn] Task "${f}" (Knoten "${a.id}") hat eine Bedingung, aber kein 'onConditionReturn' ('respawn' | 'stayClosed') \u2014 was bei der R\xFCckkehr der Bedingung geschieht, muss entschieden sein.`))):u.onConditionReturn!==void 0&&n.push(It(`${h}.onConditionReturn`,`[workItems/whenNeedsOnConditionReturn] 'onConditionReturn' ohne 'when' auf Task "${f}" (Knoten "${a.id}") \u2014 ohne Bedingung kehrt nichts zur\xFCck.`));let T=u.reads;if(T!==void 0)if(!Array.isArray(T))n.push(It(`${h}.reads`,`[workItems/readsUnknownField] 'reads' auf Task "${f}" (Knoten "${a.id}") muss eine Liste von Feldadressen sein.`));else for(let[P,E]of T.entries())A(`${h}.reads.${P}`,E,"'reads'");let N=u.locksEvidence,F=o((P,E)=>n.push(It(`${h}.locksEvidence`,`[workItems/${P}] Task "${f}" (Knoten "${a.id}") ${E}`)),"lockIssue");N!==void 0&&N!==!0&&F("locksEvidenceNotTrue",`tr\xE4gt 'locksEvidence' ${JSON.stringify(N)} \u2014 nur 'true' ist erlaubt; ohne Sperre entf\xE4llt das Feld.`),N===!0&&(T===void 0&&S===void 0&&F("locksEvidenceWithoutEvidence","sperrt seine Belege, hat aber weder 'reads' noch 'when' \u2014 es gibt nichts, worauf die Entscheidung beruht."),(b===void 0||!ri(b.kind))&&F("locksEvidenceNeedsRecordedResult","sperrt seine Belege, schlie\xDFt aber nicht mit einem erfassten Ergebnis (Freitext, Empfehlung, Auswahl) \u2014 nur eine Entscheidung, die das Team wieder\xF6ffnen kann, darf Belege sperren (ein Termin bleibt gebucht)."),d.has(f)&&F("locksEvidenceOnOptionalAction","geh\xF6rt zu einer optionalen Aktion (spawnTasks) \u2014 ihre Zeilen sind die Runde der Aktion, wieder\xF6ffnen l\xE4sst sie sich nicht; Belege sperrt nur eine Knotenaufgabe.")),n.push(...P_({graph:t,node:l,task:u,onTrigger:d,specCtx:e}));let x=Object.keys(u).filter(P=>!Object.hasOwn(F_,P));x.length>0&&n.push(It(`${h}.${x[0]}`,`[workItems/unknownKey] Task "${f}" (Knoten "${a.id}") tr\xE4gt ${x.map(P=>`'${P}'`).join(", ")} \u2014 kein Feld einer Aufgabe. Erlaubt: ${Object.keys(F_).join(", ")}. (Checklisten gibt es nicht mehr: Text als 'description', mehrere Arbeitsschritte sind mehrere Aufgaben.)`));let v=u.description;v!==void 0&&!q_(v)&&n.push(It(`${h}.description`,`[workItems/descriptionInvalid] 'description' auf Task "${f}" (Knoten "${a.id}") braucht Text in beiden Sprachen ({ de, en }), erhalten ${JSON.stringify(v)}.`)),u.optional!==void 0&&n.push(...d1(u,{key:f,nodeId:a.id,base:h,requiredByRule:c.has(f)}))}}return n}o(B_,"checkNodeTasks");function V_(t){let e=t.indexOf(":"),n=e===-1?"":t.slice(0,e),r=e===-1?"":t.slice(e+1).trim();if(n==="artifact"&&r.length>0)return{kind:n,key:r};let i=xr(r);return(n==="field"||n==="document")&&i!==null?{kind:n,address:i}:ke("INVALID",`Dokument-Verweis "${t}" ist ung\xFCltig \u2014 erwartet artifact:<Slot-Schl\xFCssel>, field:$node.<Formular>.admission.<Feld> oder document:$node.<Knoten>.document.`)}o(V_,"parseTaskDocumentRef");function qb(t){return t.kind==="artifact"?`artifact:${t.key}`:`${t.kind}:${fe(t.address)}`}o(qb,"taskDocumentId");function hi(t,e){return{layer:"GRAPH",kind:"nodeRule",path:t,reason:e,severity:"error"}}o(hi,"issue");function K_(t){return Array.isArray(t.tasks)?t.tasks:[]}o(K_,"tasksOf");function c1(t){let e=new Map;for(let n of t){let{id:r,artifacts:i}=n;for(let s of Array.isArray(i)?i:[])typeof s?.key=="string"&&e.set(s.key,[...e.get(s.key)??[],{nodeId:r,slot:s}])}return e}o(c1,"artifactSlotDeclarations");function U_(t){let e=[];for(let[n,r]of c1(t.nodes))for(let i of r.slice(1))e.push(hi(`nodes.${i.nodeId}.artifacts`,`[governedDocument/slotKeyTaken] Knoten "${i.nodeId}" deklariert den Dokument-Slot \u201E${n}", den schon "${r[0].nodeId}" deklariert \u2014 jeder Slot-Schl\xFCssel geh\xF6rt genau einem Knoten.`));return e}o(U_,"checkArtifactSlotKeys");function j_(t){if(!Array.isArray(t)||t.length===0)return null;let e=[];for(let n of t){let r=typeof n=="object"&&n!==null?n:{},i=Object.keys(r).sort().join(",");if(r.kind==="artifact"&&i==="key,kind"&&typeof r.key=="string"&&r.key.length>0)e.push({kind:"artifact",key:r.key});else if((r.kind==="field"||r.kind==="document")&&i==="address,kind")e.push({kind:r.kind,address:r.address});else return null}return e}o(j_,"authoredRefs");function u1(t){return t.scope==="node"&&(t.key===Na||t.key===Mo||t.key===Su)&&t.path===void 0}o(u1,"isDocumentAddress");function G_(t){let e=[];for(let n of t.nodes)for(let r of K_(n)){if(r.documents===void 0)continue;let i=typeof r.key=="string"?r.key:"?",s=`nodes.${n.id}.tasks.${i}.documents`,a=`Task "${i}" (Knoten "${n.id}")`,l=j_(r.documents);if(l===null){e.push(hi(s,`[workItems/documentsInvalid] 'documents' auf ${a} muss eine nicht leere Liste von { kind: 'artifact', key } (eigener Slot), { kind: 'field', address } (Dateifeld eines Formulars) oder { kind: 'document', address } (Dokument eines anderen Knotens) sein, erhalten ${JSON.stringify(r.documents)}.`));continue}let d=new Set;for(let c of l){if(c.kind!=="artifact"&&!Se(c.address))continue;let u=c.kind==="artifact"?qb(c):qb({kind:c.kind,address:c.address});d.has(u)&&e.push(hi(s,`[workItems/documentsDuplicate] ${a} verweist zweimal auf ${u}.`)),d.add(u),c.kind==="artifact"&&!bT(n,c.key)&&e.push(hi(s,`[workItems/documentsUnknownArtifact] ${a} verweist auf das Dokument "${c.key}", aber der Knoten deklariert keinen solchen Slot \u2014 das Dokument eines anderen Knotens ist { kind: 'document', address: $node.<knoten>.document }.`)),c.kind==="field"&&!Xe(c.address)&&e.push(hi(s,`[workItems/documentsInvalid] ${a}: ein Feld-Dokument nennt ein Feld eines Formulars ($node.<formular>.admission.<feld>), nicht ${nt(t,c.address,"de")}.`)),c.kind==="document"&&!u1(c.address)&&e.push(hi(s,`[workItems/documentsInvalid] ${a}: ein Dokument eines anderen Knotens ist dessen ganzes Dokument ($node.<knoten>.document), nicht ${fe(c.address)}.`))}}return e}o(G_,"checkTaskDocuments");function W_(t,e){let n=[];for(let r of t.nodes)for(let i of K_(r)){let s=j_(i.documents);if(s===null)continue;let a=typeof i.key=="string"?i.key:"?",l=`nodes.${r.id}.tasks.${a}.documents`;for(let d of s){if(d.kind!=="field"||!Xe(d.address))continue;let c=ur(e,d.address);if(c==null)continue;let u=nt(t,d.address,"de"),f=ai("taskDocument",si(c));if(f==="repeated"){n.push(hi(l,`[workItems/documentsUnknownField] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Dokument der Anmeldung.`));continue}f==="notDocument"&&n.push(hi(l,`[workItems/documentsNotDocument] Task "${a}" (Knoten "${r.id}") verweist auf das Feld ${u}, das keine Datei enth\xE4lt \u2014 nur Datei-Felder (docRef) sind Dokumente.`))}}return n}o(W_,"checkTaskDocumentFields");function f1(t){let e=(t.category??"process")==="process"?"error":"warning",n=new Map;for(let a of hn(t.nodes)){let l=n.get(a.source)??[];l.push({id:a.id,target:a.target}),n.set(a.source,l)}let r=[],i=new Set,s=lf(t.nodes.map(a=>a.id),a=>(n.get(a)??[]).map(({id:l,target:d})=>({target:d,edge:l})));for(let a of s)i.has(a.edge)||(i.add(a.edge),r.push({layer:"GRAPH",kind:"cycle",path:`edge.${a.edge}`,reason:`Zyklus \xFCber Kante ${a.source} \u2192 ${a.target}`,severity:e}));return r}o(f1,"checkAcyclic");function p1(t){let e=[],n=new Set(t.nodes.map(i=>i.id)),r=(t.category??"process")==="process"?"error":"warning";for(let i of t.nodes){let s=i.next;if(s)for(let[a,l]of Object.entries(s))n.has(l.to)||e.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.next.${a}`,reason:`${i.label.de}: next.${a} verweist auf nicht-existenten Knoten '${l.to}'`,severity:"error"});if(i.type!=="end"&&!(!i.outcomes||i.outcomes.length===0))for(let a of i.outcomes)(!s||!(a.id in s))&&e.push({layer:"GRAPH",kind:"routing",path:`node.${i.id}.outcome.${a.id}`,reason:`${i.label.de}: Outcome '${a.label.de}' fehlt im next-Mapping`,severity:r})}return e}o(p1,"checkNextTargets");function m1(t){let e=[];for(let n of t.nodes){let r=n.next;if(!r)continue;let i=Rb(n),s=new Set(i?i.map(a=>a.id):[Bo]);for(let a of Object.keys(r))s.has(a)||e.push({layer:"GRAPH",kind:"unknownOutcome",path:`node.${n.id}.next.${a}`,reason:`${n.label.de}: next-Schl\xFCssel '${a}' ist kein g\xFCltiges Outcome dieses Knotens (erlaubt: ${[...s].join(", ")}) \u2014 die Kante w\xFCrde im Editor verschwinden`,severity:"error"})}return e}o(m1,"checkNextOutcomesKnown");function h1(t){let e=[],n=new Set(hn(t.nodes).map(s=>s.target)),r=t.nodes.filter(s=>!n.has(s.id));return r.length===0?e.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:"Kein Start-Knoten",severity:"error"}):r.length>1&&e.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:`Mehrere Start-Knoten (${r.map(s=>s.label.de).join(", ")})`,severity:"warning"}),t.nodes.filter(s=>s.type==="end").length===0&&e.push({layer:"GRAPH",kind:"startEnd",path:"graph",reason:"Kein End-Knoten",severity:"warning"}),e}o(h1,"checkStartEnd");function g1(t){let e=new Map;for(let r of hn(t.nodes))e.set(r.source,(e.get(r.source)??0)+1);let n=[];for(let r of t.nodes)r.type!=="end"&&(e.get(r.id)??0)===0&&n.push({layer:"GRAPH",kind:"startEnd",path:`node.${r.id}`,reason:`${r.label.de}: keine ausgehende Kante`,severity:"warning"});return n}o(g1,"checkNoOutgoingEdge");function y1(t){return t.nodes.filter(e=>!Hh(e.id)).map(e=>({layer:"GRAPH",kind:"nodeRule",path:`nodes.${e.id}.id`,reason:`[graph/nodeIdFormat] Knoten "${e.id}": eine Knoten-ID ist ein Bezeichner ohne Punkt (${nr.source}), z. B. "reviewEingereicht". Ein Bundle von vor der Umstellung neu exportieren.`,severity:"error"}))}o(y1,"checkNodeIdFormat");function b1(t){let e=new Set(t.nodes.map(r=>r.id)),n=[];for(let r of hn(t.nodes))e.has(r.source)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:`Kante ${r.id}: Quelle '${r.source}' nicht gefunden`,severity:"error"}),e.has(r.target)||n.push({layer:"GRAPH",kind:"startEnd",path:`edge.${r.id}`,reason:`Kante ${r.id}: Ziel '${r.target}' nicht gefunden`,severity:"error"});return n}o(b1,"checkEdgeEndpoints");var w1=new Set(["countersignature"]);function k1(t){let e=[],n=o((r,i)=>{e.push({layer:"GRAPH",kind:"nodeRule",path:r,reason:`[graph/retiredField] ${i}`,severity:"error"})},"retired");for(let r of t.nodes){let i=r,s=`Knoten \u201E${We(t,r.id,"de")}\u201C (${r.id})`;for(let[a,l]of Object.entries(i.next??{}))l!==null&&typeof l=="object"&&"emits"in l&&n(`nodes.${r.id}.next.${a}.emits`,`${s}: \`next.${a}.emits\` gibt es nicht mehr \u2014 ein Ausgang routet nur; ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`);for(let a of Array.isArray(i.outcomes)?i.outcomes:[])a!==null&&typeof a=="object"&&"emits"in a&&n(`nodes.${r.id}.outcomes.${String(a.id)}.emits`,`${s}: \`emits\` am Ausgang "${String(a.id)}" gibt es nicht mehr \u2014 ein Knoten liest Daten \xFCber Adressen in seinen eigenen Feldern.`);"targetFormNodeId"in i&&n(`nodes.${r.id}.targetFormNodeId`,`${s}: \`targetFormNodeId\` gibt es nicht mehr \u2014 welches Formular freigeschaltet wird, sagt die Adresse im Feld \`target\` ($node.<formular>.admission).`),"wires"in i&&n(`nodes.${r.id}.wires`,`${s}: Datenkanten (\`wires\`) gibt es nicht mehr \u2014 jedes Feld, das Daten eines anderen Knotens liest, tr\xE4gt selbst die volle Adresse ($node.\u2026, $task.\u2026, $derived.\u2026, $env.\u2026).`);for(let[a,l]of Object.entries(i.inputs??{}))l!==null&&typeof l=="object"&&l.kind==="binding"&&"path"in l&&n(`nodes.${r.id}.inputs.${a}.path`,`${s}: Der Eingang \u201E${a}\u201C ist \xFCber einen Pfad (\`path\`) gebunden \u2014 eine Bindung tr\xE4gt die volle Adresse (\`address\`) dessen, was sie liest.`);i.adoptForm===!0&&n(`nodes.${r.id}.adoptForm`,`${s}: \`adoptForm: true\` gibt es nicht mehr \u2014 \`adoptForm\` ist die Adresse des \xFCbernommenen Formulars ($node.<anlegender Formularknoten>.admission).`);for(let a of Array.isArray(i.tasks)?i.tasks:[]){let l=a?.result?.kind;typeof l=="string"&&w1.has(l)&&n(`nodes.${r.id}.tasks.${String(a.key)}.result`,`Aufgabe "${String(a.key)}" an ${s}: das Ergebnis \u201E${l}" gibt es nicht mehr \u2014 die Gegenzeichnung ist der Knotentyp \u201EUnterschrift (intern)" (countersign).`)}}return e}o(k1,"checkRetiredDataFields");function v1(t){let e=[];for(let n of t.nodes){if(n.type!=="end")continue;let r=n,i=r.inputs?.applicationOutcome;if(!i||i.kind!=="literal"||i.value==null){e.push({layer:"GRAPH",kind:"nodeRule",path:`node.${r.id}.inputs.applicationOutcome`,reason:`${r.label.de}: applicationOutcome literal-input fehlt \u2014 Engine kann den Terminal-Patch nicht ableiten`,severity:"error"});continue}Yu(String(i.value))||e.push({layer:"GRAPH",kind:"nodeRule",path:`node.${r.id}.inputs.applicationOutcome`,reason:`${r.label.de}: applicationOutcome '${String(i.value)}' ist kein Ausgang eines Endknotens (${Yi.join("|")}) \u2014 die Warteliste endet \xFCber das closed-Outcome ihres Wartelistenknotens`,severity:"error"})}return e}o(v1,"checkEndApplicationOutcome");function S1(t){let e=[];for(let n of t.nodes){if(n.type!=="end")continue;let r=n.inputs?.dataDecision;if(!r||r.kind!=="literal"||r.value==null){e.push({layer:"GRAPH",kind:"nodeRule",path:`node.${n.id}.inputs.dataDecision`,reason:`${n.label}: dataDecision fehlt \u2014 der Endknoten muss festlegen, ob die erfassten Daten \xFCbernommen (commit) oder verworfen (discard) werden`,severity:"error"});continue}Ju(r.value)||e.push({layer:"GRAPH",kind:"nodeRule",path:`node.${n.id}.inputs.dataDecision`,reason:`${n.label}: dataDecision '${String(r.value)}' ist ung\xFCltig (${Ji.join("|")})`,severity:"error"})}return e}o(S1,"checkEndDataDecision");function Xo(t,e){return e?.wiring&&e.layout?{wiring:e.wiring,layout:e.layout}:null}o(Xo,"resolveLayoutContext");function x1(t,e){let n=Xo(t,e);if(!n)return t.nodes.some(s=>(je(s)?.progressEvents?.length??0)>0)?[{layer:"GRAPH",kind:"progressState",path:"graph.progressWiring",reason:`Graph emittiert Progress-Events, aber (Layout, Wiring) konnte nicht aufgel\xF6st werden (Wiring ${e?.wiring?"vorhanden":"fehlt"}, Layout ${e?.layout?"vorhanden":"fehlt"}) \u2014 der Engine wirft beim Spiegeln zur Laufzeit. Das Manifest muss data.progressLayout und der Workflow-Entwurf progressWiring tragen.`,severity:"error"}]:[];let r=[];for(let i of t.nodes){let a=je(i)?.progressEvents;if(a)for(let l of a){let d=Xu(n.wiring,{id:i.id,type:i.type},l);if(!d){r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:`${i.type} '${i.id}': Progress-Event '${l}' ist im Wiring (Layout '${n.layout.id}') keinem (Bus, State) zugeordnet \u2014 der Engine wirft beim Spiegeln`,severity:"error"});continue}let c;try{c=Zu(n.layout,d.bus)}catch{r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:`${i.type} '${i.id}': Event '${l}' verweist auf unbekannten Bus '${d.bus}' im Layout '${n.layout.id}'`,severity:"error"});continue}Za(c,d.state)||r.push({layer:"GRAPH",kind:"progressState",path:`node.${i.id}.progressEvents.${l}`,reason:`${i.type} '${i.id}': Event '${l}' verweist auf State '${d.state}', der nicht im Bus '${d.bus}' deklariert ist`,severity:"error"})}}return r}o(x1,"checkProgressEventMappings");function A1(t,e){let n=Xo(t,e);if(!n)return[];let r=[];for(let i of n.layout.buses){if(!i.boards||i.boards.length===0)continue;let s=new Set(i.unboarded??[]),a=new Set;for(let l of i.boards)for(let d of l.columns)for(let c of d.states)a.add(c),Za(i,c)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${l.id}.column.${d.id}.${c}`,reason:`Board '${l.id}', Spalte '${d.id}' referenziert State '${c}', der nicht im Bus '${i.key}' deklariert ist`,severity:"error"});for(let l of i.states)a.has(l.id)||s.has(l.id)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${l.id}`,reason:`State '${l.id}' (${l.label.de}) erscheint in keiner Board-Spalte und nicht in 'unboarded' \u2014 nicht darstellbar`,severity:"error"})}return r}o(A1,"checkProgressBoardCoverage");function E1(t,e){let n=Xo(t,e);if(!n)return[];let r=[];for(let i of n.layout.buses)if(!(!i.boards||i.boards.length===0))for(let s of i.boards)for(let a of At){let l=new Map;for(let d of s.columns){if(!Ur(d.label))continue;let c=d.label[a],u=c.trim().toLocaleLowerCase(a),f=l.get(u);if(f===void 0){l.set(u,d.id);continue}r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.board.${s.id}.column.${d.id}.label.${a}`,reason:`Board '${s.id}' hat zwei Spalten mit dem Label '${c}' (${a}) ('${f}' und '${d.id}') \u2014 f\xFCr Lesende nicht unterscheidbar. F\xFChre die Spalten zusammen (states beider in EINE Spalte) oder vergib unterschiedliche Labels.`,severity:"error"})}}return r}o(E1,"checkProgressBoardDistinctLabels");function R1(t,e){let n=Xo(t,e);if(!n)return[];let r=[];for(let i of n.layout.buses)for(let s of i.states){let a=q$(i,s.id);s.terminal&&!a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${s.id}.terminalSemantics`,reason:`Terminal-State '${s.id}' hat keine Terminal-Semantik im Bus '${i.key}' \u2014 der Engine wirft beim Versiegeln`,severity:"error"}),!s.terminal&&a&&r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.${s.id}.terminalSemantics`,reason:`State '${s.id}' ist nicht terminal, hat aber Terminal-Semantik im Bus '${i.key}' \u2014 Inkonsistenz`,severity:"error"})}return r}o(R1,"checkProgressTerminalSemantics");function T1(t,e){let n=Xo(t,e);if(!n)return[];let r=[];for(let i of n.layout.buses){let s=new Set(i.holdsSeat??[]);for(let a of i.holdsSeat??[])Za(i,a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat.${a}`,reason:`holdsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,severity:"error"});for(let a of i.commitsSeat??[])Za(i,a)?s.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:`commitsSeat '${a}' ist nicht in holdsSeat \u2014 ein fest belegter Platz muss auch belegt sein`,severity:"error"}):r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.commitsSeat.${a}`,reason:`commitsSeat referenziert '${a}', das kein State im Bus '${i.key}' ist`,severity:"error"});for(let[a,l]of Object.entries(i.terminalSemantics??{}))l.outcome==="approved"&&(s.has(a)||r.push({layer:"GRAPH",kind:"progressState",path:`layout.${n.layout.id}.bus.${i.key}.holdsSeat`,reason:`Endzustand '${a}' schlie\xDFt den Prozess positiv ab (outcome 'approved'), steht aber nicht in holdsSeat \u2014 damit z\xE4hlt er als Absage und f\xE4llt aus dem Fortschrittsbalken. Nimm '${a}' in holdsSeat (und in commitsSeat, wenn der Platz damit wirklich belegt ist) auf.`,severity:"error"}))}return r}o(T1,"checkProgressSeatStates");var z_="Abhilfe: nach dem Formularknoten einen review-Knoten einf\xFCgen und dessen 'reviewing' auf diesen Zustand mappen";function I1(t){return t==="both"?`${z_} \u2014 die Spalte ist auch der Schritt, den die Familie sieht; den Zustand in die Spalte des Nachfolgers zu legen, n\xE4hme ihr diesen Schritt.`:`${z_}, oder den Zustand in die Spalte des Nachfolgers legen.`}o(I1,"passThroughRemedy");function $1(t,e){let n=Xo(t,e);if(!n)return[];let{layout:r,wiring:i}=n;if(!r.buses.some(w=>w.key==="process"))return[];let s=B$(r);if(!s)return[];let a=new Map(t.nodes.map(w=>[w.id,w])),l=o(w=>je(w).progressEvents??[],"eventsOf"),d=o(w=>Object.values(w.next??{}).map(S=>S.to),"routesOf"),c=o((w,S)=>{let A=a.get(w);if(!A||S.has(w))return null;if(l(A).length>0)return[A];if(H_[A.type]!==!1)return null;let T=d(A);if(T.length===0)return null;let N=[];for(let F of T){let x=c(F,new Set([...S,w]));if(!x)return null;N.push(...x)}return N},"firstProgressNodes"),u=o((w,S)=>{let A=[];for(let T of l(w)){let N=Xu(i,w,T);if(!N||N.bus!==S.bus||N.state===S.state)return null;A.push(N.state)}return[...new Set(A)].join("' / '")},"overwrites"),f=o((w,S)=>{let A=d(w);if(A.length===0)return null;let T=[];for(let N of A){let F=c(N,new Set([w.id]));if(!F)return null;for(let x of F){let v=u(x,S);if(v===null)return null;T.push(`'${x.id}' (${x.type}) mit '${v}'`)}}return[...new Set(T)]},"submitOverwrittenBy"),h=new Map;for(let w of t.nodes)for(let S of l(w)){let A=Xu(i,w,S);if(!A||A.bus!=="process")continue;let T=w.type==="form"&&S===Mc?f(w,A):null,N=T?`'${w.id}'.${S} erreicht ihn, und ${T.join(", ")} \xFCberschreibt ihn in derselben Transaktion`:null;h.set(A.state,[...h.get(A.state)??[],N])}let g=Zu(r,"process"),b=new Map;for(let[w,S]of h)S.every(A=>A!==null)&&b.set(w,[...new Set(S)].join("; "));let y=[];for(let w of s.columns){if(w.states.length===0||!w.states.every(A=>b.has(A)))continue;let S=w.states.map(A=>{let T=g.holdsSeat?.includes(A)?" (steht in holdsSeat, belegt aber nie einen Platz)":"";return`Zustand '${A}'${T}: ${b.get(A)}`});y.push({layer:"GRAPH",kind:"progressState",path:`progressLayout.process.boards.${s.id}.columns.${w.id}`,reason:`[progress/passThroughState] Spalte \u201E${w.label.de}" ('${w.id}', Board '${s.id}') bleibt immer leer \u2014 ${S.join("; ")}. ${I1(s.audience)}`,severity:"warning"})}return y}o($1,"checkProgressPassThroughColumns");function _1(t){let e=["workItems","workitems","work_items","taskTemplates"],n=[];for(let r of t.nodes){let i=r;for(let s of e){let a=i[s];a!=null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.${s}`,reason:`[workItems/misnamedTasksKey] Knoten "${r.id}" deklariert "${s}" \u2014 komponierte Aufgaben werden ausschlie\xDFlich unter "tasks" gelesen. So wie es dasteht, w\xFCrde die Aufgabenkette stillschweigend nie entstehen. Benenne den Schl\xFCssel in "tasks" um.`,severity:"error"})}}return n}o(_1,"checkMisnamedTasksKey");function O1(t,e){let n=[],r=e?.teamKeys??e?.permissionGroupKeys,i=o((s,a)=>{typeof a!="string"||a.length===0||r===void 0||r.has(a)||n.push({layer:"GRAPH",kind:"nodeRule",path:s,reason:`[workItems/unknownPermissionGroup] Berechtigungsgruppe "${a}" existiert nicht im Mandanten. Bekannte Gruppen: ${[...r].sort().join(", ")}.`,severity:"error"})},"checkGroupKey");for(let s of t.nodes){let a=s,l=Array.isArray(a.tasks)?a.tasks:[],d=new Set;for(let h of l){let g=typeof h.key=="string"?h.key:void 0;g!==void 0&&(d.has(g)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}`,reason:`[workItems/duplicateTemplateKey] Doppelter Template-Key "${g}" auf Knoten "${a.id}".`,severity:"error"}),d.add(g))}let c=new Set;for(let h of Array.isArray(a.artifacts)?a.artifacts:[])typeof h.key=="string"&&c.add(`${h.key}Uploaded`);let u=je(s);if(typeof u.exports=="function")for(let h of u.exports(s))c.add(h.key);let f=new Map((typeof u.workItemTemplates=="function"?u.workItemTemplates(s):[]).map(h=>[h.key,h]));for(let h of l){let g=typeof h.key=="string"?h.key:"?",b=typeof h.kind=="string"?h.kind:void 0;if(b===void 0||!af.has(b)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.kind`,reason:`[workItems/invalidKind] Task "${g}" auf Knoten "${a.id}" hat Art ${JSON.stringify(h.kind)}; komponierbar sind: ${[...af].join(", ")}.`,severity:"error"});continue}i(`nodes.${a.id}.tasks.${g}.assign.group`,h.assign?.group),b==="task"&&h.gatesNode!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.gatesNode`,reason:`[workItems/gatesNodeOnTask] 'gatesNode' ist nur f\xFCr die Art 'approval' zul\xE4ssig \u2014 eine Task gated ihren Knoten nie direkt. Um eine gatende Freigabe zur\xFCckzuhalten, 'blocks' verwenden (Task "${g}" auf Knoten "${a.id}").`,severity:"error"});let y=h.blocks,w=y===void 0?void 0:L_(t,a.id,y.node);if(y!==void 0&&w===null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks.node`,reason:`[workItems/blocksUnknownNode] 'blocks.node' auf Task "${g}" (Knoten "${a.id}") nennt ${JSON.stringify(y.node)} \u2014 diesen Knoten gibt es im Workflow nicht.`,severity:"error"});else if(y!==void 0&&w!==void 0&&w!==null){let A=w.node.id===a.id,T=w.node.id,N=A?d:w.composedKeys,F=A?f:w.intrinsicByKey,x=w.node.assign??{};b==="approval"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks`,reason:`[workItems/blocksOnApproval] 'blocks' ist auf der Art 'approval' verboten \u2014 nur Task-Zeilen d\xFCrfen einen Geschwister-Spawn zur\xFCckhalten (Approval "${g}" auf Knoten "${a.id}").`,severity:"error"});let v=y.templateKey,P=[...new Set([...N,...F.keys()])].filter(E=>!A||E!==g).join(", ")||"keine";if(typeof v!="string"||A&&v===g||!N.has(v)&&!F.has(v))n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks.templateKey`,reason:`[workItems/blocksUnknownTarget] 'blocks' muss ein Template auf dem Zielknoten benennen \u2014 komponiert ODER intrinsisch (nie sich selbst, nie ohne 'templateKey': die zielfreie Form geh\xF6rt der Maschine, nicht dem Autor). Ziel ${JSON.stringify(v)} auf Knoten "${T}"; zul\xE4ssige Ziele: ${P}.`,severity:"error"});else if(w.refuse(v)!==null)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks.templateKey`,reason:w.refuse(v),severity:"error"});else{let E=F.get(v);y.except!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks.except`,reason:`[workItems/blocksExceptRetired] 'blocks.except' auf Task "${g}" (Knoten "${a.id}") gibt es nicht mehr: eine blockierende Aufgabe sperrt die ganze Aktionsgruppe ihres Ziels (bei einer Entscheidung Freigeben, Warteliste, Ablehnen und das Nachr\xFCcken). 'except' entfernen.`,severity:"error"}),E!==void 0&&E.recipient!=="external"&&E.verdictResolved!==!0&&typeof x[v]!="string"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.blocks.templateKey`,reason:`[workItems/blocksUnwiredTarget] Task "${g}" auf Knoten "${a.id}" h\xE4lt "${v}" (Knoten "${T}") zur\xFCck, aber der Knoten weist "${v}" keiner Gruppe zu \u2014 ohne 'assign.${v}' entsteht diese Zeile nie: kein Team bekommt die zur\xFCckgehaltene Arbeit, niemand au\xDFer der verantwortlichen Person kann sie tun. Entweder 'assign.${v}' erg\xE4nzen oder das 'blocks' entfernen.`,severity:"error"})}}{let A=h.completableIf;if(typeof A=="string"&&A.trim().length>0){let T=A.trim().replace(/^!/,"").trim();c.has(T)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.completableIf`,reason:`[workItems/unknownExport] completableIf "${A}" verweist auf unbekannten Node-Export "${T}"; bekannt: ${[...c].join(", ")||"keine"}.`,severity:"error"})}}let S=h.params;if(S?.commentRequired!==void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.params.commentRequired`,reason:"[workItems/removedParam] 'params.commentRequired' wurde entfernt \u2014 Kommentar-Pflichten werden am Decision-Node ('commentRequired') autorisiert.",severity:"error"}),b!=="approval"){let A=[];S?.onReject!==void 0&&A.push("params.onReject"),S?.revisionGroup!==void 0&&A.push("params.revisionGroup");for(let T of A)n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.${T}`,reason:`[workItems/approvalOnlyField] '${T}' gilt nur f\xFCr die Art 'approval' (Task "${g}" ist '${b}').`,severity:"error"});continue}S?.onReject!==void 0&&S.onReject!=="spawnRevision"&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.params.onReject`,reason:`[workItems/invalidOnReject] Erwartet 'spawnRevision', erhalten ${JSON.stringify(S.onReject)}.`,severity:"error"}),S?.onReject==="spawnRevision"&&(typeof S.revisionGroup!="string"||S.revisionGroup.length===0)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${a.id}.tasks.${g}.params.revisionGroup`,reason:`[workItems/spawnRevisionNoTarget] Approval "${g}" mit 'params.onReject: spawnRevision' ohne 'params.revisionGroup' \u2014 die \xDCberarbeitung h\xE4tte keine Ziel-Gruppe.`,severity:"error"}),i(`nodes.${a.id}.tasks.${g}.params.revisionGroup`,S?.revisionGroup)}}return n.push(...M_(t)),n}o(O1,"checkWorkItemTemplates");var C1=new Set(["complete","approve","reject"]),H_={form:!0,decision:!0,review:!0,waitlist:!0,completenessCheck:!0,collectPayment:!0,eventTrigger:!0,join:!1,roleAssign:!1,setFlag:!1,if:!1,end:!1,countersign:!0,engagePush:!1,governedDocument:!0};function P1(t,e){let n=[];for(let r of t.nodes){let i=r,s=je(r),a=Array.isArray(i.tasks)?i.tasks.length:0,l=s.workItemTemplates?.(r)??[];if(a+l.length>0){let S=H_[i.type];S===void 0?n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.tasks`,reason:`[workItems/unknownParkSemantics] Knotentyp "${i.type}" hat keine bekannte Park-Semantik \u2014 NODE_TYPE_PARKS in validators.ts erg\xE4nzen.`,severity:"error"}):S||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.tasks`,reason:`[workItems/templatesOnNonParkingNode] Knoten "${i.id}" (Typ "${i.type}") parkt nie \u2014 seine Work-Item-Templates w\xFCrden im selben Dispatch gespawnt und storniert (totes Muster).`,severity:"error"})}let d=s.actions?.(r)??[];if(d.length===0&&l.length===0)continue;let c=new Map(d.map(S=>[S.id,S]));for(let S of d)C1.has(S.id)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.actions.${S.id}`,reason:`[capability/reservedActionId] Knotentyp "${i.type}" deklariert die Action "${S.id}" \u2014 reserviert f\xFCr den generischen Complete-/Verdict-Pfad (complete, approve, reject); die Spec muss eine andere Action-Id w\xE4hlen.`,severity:"error"});let u=new Set(s.states??[PT]);for(let S of d)if(S.availableIn!==void 0)for(let A of S.availableIn)u.has(A)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.actions.${S.id}.availableIn`,reason:`[capability/unknownActionState] Action "${S.id}" auf Knotentyp "${i.type}" ist f\xFCr Zustand "${A}" deklariert \u2014 der Typ kennt nur: ${[...u].join(", ")}.`,severity:"error"});let f=Rb(r),h=new Set(f?f.map(S=>S.id):[Bo]);for(let S of d){if(S.external===void 0)continue;let T=CT(S.external.event)?S.kind==="advance"?`ist als "advance" deklariert, l\xF6st den Knoten aber nicht auf (Ereignis "${S.external.event}") \u2014 solche Aktionen sind "internal"`:S.outcome!==void 0?`nennt das Outcome "${S.outcome}", l\xF6st den Knoten aber nicht auf (Ereignis "${S.external.event}") \u2014 ein Outcome w\xFCrde eine zweite, stille Routing-Vokabel behaupten`:S.label===void 0?"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)":null:S.kind!=="advance"?`ist als "${S.kind}" deklariert (externe Aktionen l\xF6sen den Knoten auf und m\xFCssen "advance" sein)`:S.outcome===void 0?"nennt kein Outcome":h.has(S.outcome)?S.label===void 0?"hat keine Beschriftung (der Empf\xE4nger bekommt einen leeren Button)":null:`verweist auf das unbekannte Outcome "${S.outcome}" (deklariert: ${[...h].join(", ")||"keine"})`;T!==null&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.actions.${S.id}.external`,reason:`[capability/externalActionNeedsOutcome] Externe Aktion "${S.id}" auf Knotentyp "${i.type}" ${T}.`,severity:"error"})}for(let S of l){let A=S.unlocks;if(A.length===0&&S.verdictResolved!==!0){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.workItemTemplates.${S.key}.unlocks`,reason:`[capability/emptyUnlocks] Intrinsisches Template "${S.key}" auf Knoten "${i.id}" schaltet keine Action frei (B5).`,severity:"error"});continue}for(let T of A)c.get(T)===void 0&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.workItemTemplates.${S.key}.unlocks`,reason:`[capability/danglingUnlock] Template "${S.key}" auf Knoten "${i.id}" schaltet unbekannte Action "${T}" frei; deklariert: ${[...c.keys()].join(", ")||"keine"}.`,severity:"error"})}let g=new Set(l.map(S=>S.key)),b=e?.teamKeys??e?.permissionGroupKeys;for(let[S,A]of Object.entries(i.assign??{}))if(S!=="decision"){if(!g.has(S)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.assign.${S}`,reason:`[capability/unknownAssignKey] assign-Key "${S}" auf Knoten "${i.id}" ist kein intrinsisches Template dieses Knotentyps; bekannt: ${[...g].join(", ")||"keine"}.`,severity:"error"});continue}typeof A=="string"&&A.length>0&&b!==void 0&&!b.has(A)&&n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.assign.${S}`,reason:`[capability/unknownPermissionGroup] Berechtigungsgruppe "${A}" existiert nicht im Mandanten. Bekannte Gruppen: ${[...b].sort().join(", ")}.`,severity:"error"})}let y=new Set;for(let S of l)if(S.recipient==="external"||typeof(i.assign??{})[S.key]=="string")for(let T of S.unlocks)y.add(T);let w=s.strictActionCoverage===!0;for(let S of d){if(y.has(S.id)||S.superUserOnly===!0)continue;let A=l.find(N=>N.unlocks.includes(S.id)),T=A!==void 0?` Fehlt die Zuweisung assign.${A.key}?`:"";n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${i.id}.actions.${S.id}`,reason:`[capability/superUserOnly] Action "${S.id}" auf Knoten "${i.id}" ist von keinem verdrahteten Work-Item freigeschaltet \u2014 nur die verantwortliche Person (Super-User) kann sie ausf\xFChren.${T}`,severity:w?"error":"warning"})}}return n}o(P1,"checkNodeCapabilityWiring");function N1(t){let e=new Set(cT()),n=[];for(let r of t.nodes)e.has(r.type)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.type`,reason:`[graph/unknownNodeType] Knoten "${r.id}" hat den unbekannten Typ "${String(r.type)}". Registrierte Typen: ${[...e].join(", ")}.`,severity:"error"});return n}o(N1,"checkKnownNodeTypes");function D1(t,e){let n=[],r=e?.teamKeys??e?.permissionGroupKeys,i=o((l,d)=>{n.push({layer:"GRAPH",kind:"nodeRule",path:l,reason:d,severity:"error"})},"push"),s=o((l,d)=>{typeof d!="string"||d.length===0||r===void 0||r.has(d)||i(l,`[optionalAction/unknownPermissionGroup] Berechtigungsgruppe "${d}" existiert nicht im Mandanten. Bekannte Gruppen: ${[...r].sort().join(", ")}.`)},"checkGroupKey"),a=o(l=>typeof l=="object"&&l!==null&&Object.values(l).some(d=>typeof d=="string"&&d.trim().length>0),"hasText");for(let l of t.nodes){let d=l,c=Array.isArray(d.optionalActions)?d.optionalActions:[];if(n.push(...G1(d,c)),c.length===0)continue;let u=je(l),f=new Set(u.optionalActionKinds??[]),h=Array.isArray(d.tasks)?d.tasks:[],g=new Map;for(let w of h)typeof w.key=="string"&&g.set(w.key,w);let b=new Set,y=new Map;for(let w of c){let S=w.key,A=typeof S=="string"&&S.trim().length>0?S:void 0,T=A??"?",N=`nodes.${d.id}.optionalActions.${T}`,F=typeof w.action=="string"?w.action:void 0;if((F===void 0||!f.has(F))&&i(`${N}.action`,`[optionalAction/kindNotDeclared] Optionale Aktion "${T}" auf Knoten "${d.id}" hat die Art ${JSON.stringify(w.action)} \u2014 `+(f.size===0?`Knotentyp "${d.type}" deklariert keine Familien (spec.optionalActionKinds fehlt).`:`Knotentyp "${d.type}" deklariert nur: ${[...f].join(", ")}.`)),A===void 0?i(`${N}.key`,`[optionalAction/missingKey] Optionale Aktion auf Knoten "${d.id}" ohne (oder mit leerem) 'key' \u2014 Trigger-Action und Template-Keys w\xE4ren namenlos ('optionalAction::\u2026').`):(b.has(A)&&i(`${N}.key`,`[optionalAction/duplicateKey] Doppelter Aktions-Key "${A}" auf Knoten "${d.id}" \u2014 die projizierten Trigger-Actions w\xFCrden kollidieren.`),b.add(A)),a(w.label)||i(`${N}.label`,`[optionalAction/missingLabel] Optionale Aktion "${T}" auf Knoten "${d.id}" ohne Label \u2014 der Trigger-Button w\xE4re unbeschriftet.`),s(`${N}.trigger`,w.trigger),F==="spawnTasks"){w.except!==void 0&&i(`${N}.except`,`[optionalAction/exceptRetired] Optionale Aktion "${T}" auf Knoten "${d.id}" tr\xE4gt 'except' \u2014 das gibt es nicht mehr: solange die Aufgaben offen sind, ist die ganze Aktionsgruppe des Knotens gesperrt. 'except' entfernen.`);let x=Array.isArray(w.tasks)?w.tasks:void 0;if(x===void 0||x.length===0)i(`${N}.tasks`,`[optionalAction/tasksEmpty] Optionale Aktion "${T}" auf Knoten "${d.id}" referenziert keine Aufgaben-Templates \u2014 der Trigger w\xFCrde nichts erzeugen.`);else{let v=new Set,P=new Set(x.filter(E=>typeof E=="string"));for(let E of x){let M=typeof E=="string"?E:void 0;if(M===void 0||M.length===0){i(`${N}.tasks`,`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${d.id}" enth\xE4lt eine leere/ung\xFCltige Template-Referenz.`);continue}if(v.has(M)){i(`${N}.tasks.${M}`,`[optionalAction/duplicateTaskRef] Template "${M}" ist in der Aktion "${T}" auf Knoten "${d.id}" doppelt referenziert.`);continue}v.add(M);let q=g.get(M);if(q===void 0){i(`${N}.tasks.${M}`,`[optionalAction/unknownTaskRef] Optionale Aktion "${T}" auf Knoten "${d.id}" referenziert das Template "${M}", das node.tasks nicht deklariert. Vorhanden: ${[...g.keys()].join(", ")||"keine"}.`);continue}let te=y.get(M);te!==void 0&&te!==T?i(`${N}.tasks.${M}`,`[optionalAction/taskDoublyBound] Template "${M}" auf Knoten "${d.id}" ist bereits von der Aktion "${te}" referenziert \u2014 ein Template geh\xF6rt zu h\xF6chstens einer optionalen Aktion.`):y.set(M,T);let B=q.assign,H=typeof B?.group=="string"&&B.group.length>0,$=typeof B?.userId=="string"&&B.userId.length>0;!H&&!$&&i(`${N}.tasks.${M}`,`[optionalAction/unassignedTask] Dem Template "${M}" auf Knoten "${d.id}" fehlt 'assign.group' \u2014 die Zeile w\xFCrde beim Trigger f\xFCr niemanden entstehen (eine optionale Aufgabe ohne Halter ist ein steckender Prozess).`);let _=q.blocks?.templateKey;typeof _=="string"&&!P.has(_)&&i(`${N}.tasks.${M}`,`[optionalAction/taskRefBlocks] Template "${M}" auf Knoten "${d.id}" tr\xE4gt 'blocks' auf "${_}", das nicht zur selben Aktion "${T}" geh\xF6rt \u2014 eine Referenz darf nur eine Referenz DERSELBEN Aktion zur\xFCckhalten (Checklisten-Reihenfolge), nie ein Template au\xDFerhalb.`);for(let j of h){let C=typeof j.key=="string"?j.key:void 0;j.blocks?.templateKey===M&&(C!==void 0&&P.has(C)||i(`${N}.tasks.${M}`,`[optionalAction/taskRefBlocks] Template "${M}" auf Knoten "${d.id}" ist Ziel eines 'blocks' von ${C!==void 0?`"${C}"`:"einem Template"} au\xDFerhalb der Aktion "${T}" \u2014 ein Template au\xDFerhalb darf eine Referenz nie zur\xFCckhalten (ihr Spawn geh\xF6rt dem Trigger, nicht onEnter).`))}}}}}}return n}o(D1,"checkOptionalActions");function F1(t){return typeof t=="number"?"number":typeof t=="boolean"?"boolean":"string"}o(F1,"literalValueType");function L1(t,e){let n=[],r=e?.notificationTemplates;for(let i of t.nodes){let s=i,l=je(i).notificationEvents?.(i)??[],d=s.notifications??{};if(l.length===0&&Object.keys(d).length===0)continue;let c=new Map(l.map(u=>[u.id,u]));for(let u of Object.keys(d))c.has(u)||n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${s.id}.notifications.${u}`,reason:`[notification/unknownEvent] Knoten "${s.id}" bindet einen Brief an das Ereignis "${u}", das der Knotentyp "${s.type}" nicht kennt. Angeboten werden: ${l.map(f=>f.id).join(", ")||"(keine)"}.`,severity:"error"});for(let u of l){let f=d[u.id];if(u.required===!0&&(f===void 0||f.disabled===!0)){n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${s.id}.notifications.${u.id}`,reason:`[notification/missingBinding] Knoten "${s.id}" muss beim Ereignis "${u.label.de}" (${u.id}) einen Brief verschicken \u2014 es ist ${f===void 0?"keiner gebunden":"einer gebunden, aber abgeschaltet"}.`,severity:"error"});continue}if(f===void 0||f.disabled===!0)continue;let h=`nodes.${s.id}.notifications.${u.id}`;if(u.audience!=="external"){n.push({layer:"GRAPH",kind:"nodeRule",path:h,reason:`[notification/internalAudienceUnsupported] Knoten "${s.id}": das Ereignis "${u.id}" richtet sich an die Schule, und Briefe an die Schule k\xF6nnen noch nicht zugestellt werden \u2014 der gebundene Brief "${f.templateId}" w\xFCrde den Vorgang beim Versand abbrechen.`,severity:"error"});continue}if(r===void 0)continue;let g=r.get(f.templateId);if(g===void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:h,reason:`[notification/unknownTemplate] Knoten "${s.id}": der Brief "${f.templateId}" ist nicht im Katalog. Bekannt sind: ${[...r.keys()].sort().join(", ")||"(keine)"}.`,severity:"error"});continue}g.audience!==void 0&&g.audience!==u.audience&&n.push({layer:"GRAPH",kind:"nodeRule",path:h,reason:`[notification/audienceMismatch] Der Brief "${g.id}" ist f\xFCr ${g.audience==="internal"?"die Schule":"die Familie"} geschrieben, das Ereignis "${u.id}" richtet sich aber an die Familie.`,severity:"warning"});let b=a_(u),y=new Set(g.params.map(w=>w.key));for(let w of Object.keys(f.args??{}))y.has(w)||n.push({layer:"GRAPH",kind:"nodeRule",path:`${h}.args.${w}`,reason:`[notification/unknownArg] Der Brief "${g.id}" hat kein Argument "${w}" \u2014 erwartet werden: ${g.params.map(S=>S.key).join(", ")||"(keine)"}.`,severity:"error"});for(let w of g.params){let S=f.args?.[w.key],A=`${h}.args.${w.key}`;if(S!==void 0&&"literal"in S){let N=F1(S.literal);w.type!==void 0&&!Ob(N,w.type)&&n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:`[notification/argTypeMismatch] "${w.key}" erwartet ${Cb(w.type)}, festgelegt ist aber ${JSON.stringify(S.literal)} (${N}).`,severity:"error"});continue}if(S!==void 0){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:`[notification/unsupportedArg] "${w.key}" ist an ${JSON.stringify(S)} gebunden \u2014 ein Brief-Argument kann nur ein Festwert ({ literal }) sein oder automatisch aus ${q1(b)} kommen.`,severity:"error"});continue}let T=l_(w,b.get(w.key)??[]);if(!(T.status==="resolved"||T.status==="unused")){if(T.status==="sometimes"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:`[notification/unresolvedArg] Der Brief "${g.id}" braucht "${w.key}" immer, ${T.source.source} liefert es aber nur manchmal. In notifications.${u.id}.args.${w.key} einen Festwert benennen \u2014 oder einen Brief w\xE4hlen, der ohne "${w.key}" auskommt.`,severity:"error"});continue}if(T.status==="ambiguous"){n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:`[notification/ambiguousArg] "${w.key}" hat mehrere passende Quellen \u2014 ${T.matches.map(N=>N.source).join(", ")}. In notifications.${u.id}.args.${w.key} einen Festwert setzen.`,severity:"error"});continue}n.push({layer:"GRAPH",kind:"nodeRule",path:A,reason:`[notification/unresolvedArg] Der Brief "${g.id}" braucht "${w.key}"${w.type!==void 0?` (${Cb(w.type)})`:""}, und der Knoten hat daf\xFCr ${T.rejected.length===0?"keine Quelle":`nur unpassende Quellen: ${T.rejected.map(N=>`${N.source} (${N.type})`).join(", ")}`}.`,severity:"error"})}}}}return n}o(L1,"checkNotificationBindings");function M1(t){return bR(t).map(e=>({layer:"GRAPH",kind:"assignment",path:"assignmentRules",reason:e,severity:"error"}))}o(M1,"checkAssignmentRules");function q1(t){let e=[...t.keys()].sort();return e.length===0?"(nichts)":e.join(", ")}o(q1,"describeCandidates");function B1(t,e){return u_(t,e?.chatTeamKeys).map(n=>({layer:"GRAPH",kind:"nodeRule",path:n.path,reason:n.reason,severity:"error"}))}o(B1,"checkChannels");function V1(t){return RE(t).map(e=>({layer:"GRAPH",kind:"nodeRule",path:e.path,reason:e.reason,severity:"error"}))}o(V1,"checkStaffInputs");function K1(t,e){let n=[];for(let r of t.nodes){let i=r.reads;if(i===void 0)continue;let s=`nodes.${r.id}.reads`,a=`Knoten \u201E${We(t,r.id,"de")}\u201C (${r.id})`,l=o(c=>{n.push({layer:"GRAPH",kind:"nodeRule",path:s,reason:c,severity:"error"})},"issue");if(!h_(r)){l(`[readiness/readsNotGated] ${a} (${r.type}) deklariert \`reads\`, aber die Bereitschaftspr\xFCfung h\xE4lt nur Entscheidungs-Knoten und Dokument-Knoten mit Produktion \u2014 hier w\xFCrde \`reads\` nichts bewirken.`);continue}if(!Array.isArray(i)){l(`[readiness/readsDuplicate] \`reads\` von ${a} muss eine Liste von Feldadressen sein, erhalten ${JSON.stringify(i)}.`);continue}let d=new Set;for(let c of i){if(!Se(c))continue;let u=fe(c);if(d.has(u)){l(`[readiness/readsDuplicate] ${a} liest ${nt(t,c,"de")} mehrfach.`);continue}if(d.add(u),!Xe(c)){l(`[readiness/readsUnknownField] ${a} liest ${nt(t,c,"de")} \u2014 \`reads\` nennt nur Felder eines Formulars ($node.<formular>.admission.<feld>).`);continue}let f=ur(e,c);f!=null&&ai("nodeReads",si(f),r.type)==="repeated"&&l(`[readiness/readsUnknownField] ${a} liest ${nt(t,c,"de")} \u2014 ein Feld in einer Wiederholgruppe ist kein einzelnes Feld der Anmeldung und kann nicht gelesen werden.`)}}return n}o(K1,"checkReadinessReads");function U1(t,e){let n=[];for(let r of t.nodes){if(r.type!=="setFlag")continue;let{target:i,flagKey:s}=r;if(!Se(i)||!Pa(i)||typeof s!="string"||s.length===0)continue;let a=e?.formFlagKeysByFormNode?.get(i.owner);if(a===void 0||a.has(s))continue;let l=[...a].sort();n.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${r.id}.flagKey`,reason:`[setFlag/unknownFlag] Knoten \u201E${We(t,r.id,"de")}\u201C (${r.id}) setzt \u201E${s}\u201C, aber das Formular von \u201E${We(t,i.owner,"de")}\u201C hat kein externes Merkmal dieses Namens`+(l.length>0?` (vorhanden: ${l.join(", ")}).`:" \u2014 es deklariert gar keins."),severity:"error"})}return n}o(U1,"checkSetFlagKeys");function j1(t,e){let n=e?.readinessFormFieldsByFormNode,r=e?.readinessPartyConditionKeysByFormNode;if(n===void 0||r===void 0)return[];let i=[];for(let s of t.nodes){if(s.type!=="governedDocument"||s.production!=="resolver")continue;let a=s.form;if(!Se(a)||!Pa(a))continue;let l=n.get(a.owner),d=r.get(a.owner);if(l===void 0||d===void 0||d.size===0)continue;let c=Fb(l,d);if(c.size===0)continue;let u=s.reads,f=(Array.isArray(u)?u:[]).filter(y=>Xe(y)&&y.owner===a.owner),h=Fb(l,[...f.map(y=>y.path),...b_(s).filter(y=>y.owner===a.owner).map(y=>y.fieldKey)]),g=[...c].filter(y=>!h.has(y)).sort();if(g.length===0)continue;let b=We(t,a.owner,"de");i.push({layer:"GRAPH",kind:"nodeRule",path:`nodes.${s.id}.reads`,reason:`[readiness/readsMissesPartyCondition] Knoten \u201E${We(t,s.id,"de")}\u201C (${s.id}) erzeugt ein Dokument, dessen Vertragsparteien von Angaben im Formular \u201E${b}\u201C abh\xE4ngen, die er weder liest noch bindet: ${g.join(", ")}. Eine Korrektur darauf h\xE4lt den Knoten nicht an und kann nach der Ausstellung eine Vertragspartei entfernen \u2014 die Felder (oder den berechneten Schl\xFCssel) aus \u201E${b}\u201C in \`reads\` erg\xE4nzen.`,severity:"warning"})}return i}o(j1,"checkReadinessPartyConditions");function Q_(t,e,n){let r=[],i=N1(t);if(i.length>0)return i;r.push(...y1(t)),r.push(...h1(t)),r.push(...b1(t)),r.push(...g1(t)),r.push(...f1(t)),r.push(...p1(t)),r.push(...m1(t)),r.push(...k1(t)),r.push(...v1(t)),r.push(...S1(t)),r.push(...x1(t,e)),r.push(...A1(t,e)),r.push(...E1(t,e)),r.push(...x_(t,e?.layout)),r.push(...R1(t,e)),r.push(...T1(t,e)),r.push(...$1(t,e)),r.push(...ZT(t,n)),r.push(...j$(t)),r.push(...J$(t,n)),r.push(...U$(t)),r.push(..._1(t)),r.push(...O1(t,n)),r.push(...B_(t,n)),r.push(...G_(t)),r.push(...U_(t)),r.push(...W_(t,n)),r.push(...P1(t,n)),r.push(...L1(t,n)),r.push(...D1(t,n)),r.push(...M1(t)),r.push(...K1(t,n)),r.push(...j1(t,n)),r.push(...U1(t,n)),r.push(...B1(t,n)),r.push(...V1(t));for(let s of t.nodes){let a=je(s);a.validate&&r.push(...a.validate(s,t,n))}return r}o(Q_,"checkGraph");function G1(t,e){let n=t.requiresOneOf;if(n===void 0)return[];let r=`nodes.${t.id}.requiresOneOf`,i=o(d=>({layer:"GRAPH",kind:"nodeRule",path:r,reason:d,severity:"error"}),"issue");if(t.type!=="decision")return[i(`[decision/requiresOneOfNotDecision] Knoten "${t.id}" (Typ "${t.type}") tr\xE4gt 'requiresOneOf' \u2014 die Regel gilt nur an Entscheidungsknoten (decision).`)];if(!Array.isArray(n)||n.length===0||n.some(d=>typeof d!="string"||d.length===0))return[i(`[decision/requiresOneOfEmpty] 'requiresOneOf' an Knoten "${t.id}" muss eine nicht-leere Liste von Aktions-Keys sein \u2014 sonst Feld weglassen.`)];let s=e.map(d=>d.key).filter(d=>typeof d=="string"),a=[],l=new Set;for(let d of n){if(l.has(d)){a.push(i(`[decision/requiresOneOfDuplicate] 'requiresOneOf' an Knoten "${t.id}" nennt "${d}" doppelt.`));continue}l.add(d),s.includes(d)||a.push(i(`[decision/requiresOneOfUnknownAction] 'requiresOneOf' an Knoten "${t.id}" nennt "${d}", aber dieser Knoten hat keine optionale Aktion mit diesem Key \u2014 die Regel w\xE4re nie erf\xFCllbar. `+(s.length===0?"Der Knoten hat keine optionalen Aktionen.":`Optionale Aktionen dieses Knotens: ${s.join(", ")}.`)))}return a}o(G1,"checkRequiresOneOf");function Y_(t,e,n){return Q_(t,e,n)}o(Y_,"runWorkflowValidators");function J_(t){return Qu(t)}o(J_,"blockingWorkflowErrors");var W1="$";function z1(t){return typeof t=="string"&&t.startsWith(W1)}o(z1,"isRef");function uf(t){return t.slice(1)}o(uf,"stripRef");function*H1(t){switch(t.kind){case"relationship":if(yield t.from,yield t.to,t.meta)for(let e of Object.values(t.meta))yield e;return;case"fieldMap":yield t.target;return;case"shareValue":yield t.from,yield t.to;return;case"person":case"organization":return}}o(H1,"refSlots");function Q1(t){let e=new Set;for(let n of H1(t))z1(n)&&e.add(uf(n));return[...e]}o(Q1,"collectRefs");function Y1(t){let e=new Set(t.map(s=>s.id)),n=new Map,r=new Map,i=new Map;for(let s of t)i.set(s.id,s),n.set(s.id,[]),r.set(s.id,[]);for(let s of t)for(let a of Q1(s))e.has(a)&&(n.get(s.id).push(a),r.get(a).push(s.id));for(let s of t){if(s.kind!=="shareValue")continue;let a=uf(s.from);for(let l of t)l.id===s.id||!(l.kind==="fieldMap"&&uf(l.target)===a||l.kind==="shareValue"&&uf(l.to)===a)||n.get(s.id).includes(l.id)||(n.get(s.id).push(l.id),r.get(l.id).push(s.id))}return{refsOf:n,successors:r,byId:i}}o(Y1,"buildAdjacency");function Z_(t){let{refsOf:e}=Y1(t),r=lf(t.map(i=>i.id),i=>(e.get(i)??[]).map(s=>({target:s,edge:null})))[0];return r===void 0?{hasCycle:!1}:{hasCycle:!0,cycle:r.cycle}}o(Z_,"detectCycle");function X_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}o(X_,"escapeRegExp");function gi(t){return new RegExp(`^${X_(t)}\\[(\\d+)\\]\\.(.+)$`)}o(gi,"repeatedRowKeyPattern");function Bb(t,e){let n=gi(e),r=0;for(let i of Object.keys(t)){let s=i.match(n);if(!s)continue;let a=Number(s[1]);Number.isInteger(a)&&a+1>r&&(r=a+1)}return r}o(Bb,"countRepeatedRows");function eO(t,e,n){let r=gi(e);for(let[i,s]of Object.entries(t)){let a=i.match(r);if(!(!a||Number(a[1])!==n)&&s!=null&&!(typeof s=="string"&&s.trim()==="")&&!(Array.isArray(s)&&s.length===0))return!0}return!1}o(eO,"repeatedRowHasData");function tO(t){return t.endsWith(".count")?t.slice(0,-6):t}o(tO,"readKeyOf");function Vb(t){return{sections:t,fields:[]}}o(Vb,"hiddenSectionsOnly");function nO(t,e,n){for(let r of t.fields)e.add(r.key);for(let r of t.groups??[])for(let i of r.fields)e.add(i.key);for(let r of t.computed??[])e.add(r.key);for(let r of t.repeated??[])n.add(r.key);for(let r of t.subsections??[])nO(r,e,n)}o(nO,"collectKeys");function rO(t){let e=[],n=o(r=>{if(r.visibleTo!==void 0){let i=new Set,s=new Set;nO(r,i,s),e.push({sectionId:r.id,label:r.label,visibleTo:r.visibleTo,fieldKeys:i,repeatedKeys:s,rowKeyPatterns:[...s].map(gi)});return}for(let i of r.subsections??[])n(i)},"visit");for(let r of t.sections)n(r);return e}o(rO,"restrictedSectionsOf");function iO(t,e){return e.fieldKeys.has(t)||e.repeatedKeys.has(t)?!0:e.rowKeyPatterns.some(n=>n.test(t))}o(iO,"matchesKey");function J1(t,e){return e.find(n=>iO(t,n))??null}o(J1,"hiddenSectionOfKey");function Z1(t,e){for(let n=t;;){if(iO(n,e))return!0;let r=n.lastIndexOf(".");if(r===-1)return!1;n=n.slice(0,r)}}o(Z1,"fieldOwnsKey");function X1(t,e){return e.find(n=>Z1(t,n))??null}o(X1,"restrictedFieldOfKey");function ej(t,e){let n=J1(t,e.sections);if(n!==null)return{kind:"section",section:n};let r=X1(t,e.fields);return r===null?null:{kind:"field",field:r}}o(ej,"hiddenOwnerOfKey");function ff(t,e){return ej(t,e)!==null}o(ff,"isKeyHidden");function tj(t,e,n,r,i){let s=[];r&&s.push({severity:"error",path:n,code:"section.visibleTo-nested",message:`Abschnitt '${t}' liegt in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) und darf selbst keine tragen.`});let a=o(l=>typeof l!="string"||l.trim()==="","isBlank");if((e.length===0||e.some(a)||new Set(e).size!==e.length)&&s.push({severity:"error",path:n,code:"section.visibleTo-invalid",message:`Abschnitt '${t}': visibleTo braucht mindestens ein Team, ohne leere oder doppelte Eintr\xE4ge.`}),i===void 0)return s;for(let l of e)a(l)||i.has(l)||s.push({severity:"error",path:n,code:"section.visibleTo-unknown",message:`Abschnitt '${t}': '${l}' ist weder ein Team noch eine Rechtegruppe dieser Schule.`});return s}o(tj,"visibleToListIssues");function oO(t,e,n){let r=[],i=o((c,u,f)=>{let h=c.visibleTo;h!==void 0&&r.push(...tj(c.id,h,`${u}.visibleTo`,f,n));let g=f||h!==void 0;if(g){let b=[...c.fields,...(c.groups??[]).flatMap(y=>y.fields),...(c.repeated??[]).flatMap(y=>y.itemTemplate)];for(let y of b)y.kind==="cf_value"&&r.push({severity:"error",path:`${u}.fields`,code:"section.visibleTo-party",message:`Feld '${y.key}' wird in die Personendaten \xFCbernommen und kann deshalb nicht in einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) liegen.`})}(c.subsections??[]).forEach((b,y)=>i(b,`${u}.subsections[${y}]`,g))},"visitRaw");t.sections.forEach((c,u)=>i(c,`sections[${u}]`,!1));let s=rO(t);if(s.length===0)return r;let a=o((c,u,f)=>{if(c===void 0)return;let h=Vb(f);for(let g of dt(c)){let b=tO(g);(ff(g,h)||ff(b,h))&&r.push({severity:"error",path:u,code:"section.visibleTo-read-outside",message:`${u} liest '${g}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo) \u2014 wer den Abschnitt nicht sieht, bek\xE4me hier ein anderes Ergebnis.`})}},"checkAst"),l=o((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&&ff(c.sameAs.source,Vb(f))&&r.push({severity:"error",path:`${u}.sameAs`,code:"section.visibleTo-read-outside",message:`${u} \xFCbernimmt '${c.sameAs.source}' aus einem Abschnitt mit eingeschr\xE4nkter Sichtbarkeit (visibleTo).`})},"checkField"),d=o((c,u,f)=>{let h=c.visibleTo!==void 0?c.id:f,g=s.filter(b=>b.sectionId!==h);a(c.visibleIf,`${u}.visibleIf`,c.visibleTo!==void 0?s:g),c.fields.forEach((b,y)=>l(b,`${u}.fields[${y}]`,g)),c.groups?.forEach((b,y)=>{a(b.visibleIf,`${u}.groups[${y}].visibleIf`,g),b.fields.forEach((w,S)=>l(w,`${u}.groups[${y}].fields[${S}]`,g))}),c.repeated?.forEach((b,y)=>{a(b.itemVisibleIf,`${u}.repeated[${y}].itemVisibleIf`,g),b.itemTemplate.forEach((w,S)=>l(w,`${u}.repeated[${y}].itemTemplate[${S}]`,g))}),c.computed?.forEach((b,y)=>a(b.expression,`${u}.computed[${y}]`,g)),c.subsections?.forEach((b,y)=>d(b,`${u}.subsections[${y}]`,h))},"visitCompiled");return e.sections.forEach((c,u)=>d(c,`sections[${u}]`,null)),r}o(oO,"sectionVisibilityIssues");var Zi="#";function es(t,e=[],n){let r=[];return t.forEach((i,s)=>{let a=[...e,s];r.push({section:i,path:a,parentId:n});for(let l of es(i.subsections??[],a,i.id))r.push(l)}),r}o(es,"walkSections");function nj(t,e){for(let n of t.fields)if(n.key===e)return n;for(let n of t.groups??[])for(let r of n.fields)if(r.key===e)return r;for(let n of t.repeated??[])for(let r of n.itemTemplate)if(r.key===e)return r;return null}o(nj,"findFieldInSection");function sO(t,e){for(let n of es(t.sections)){let r=nj(n.section,e);if(r)return{section:n.section,field:r}}return null}o(sO,"findField");var rj=["Baby","BookOpen","BriefcaseBusiness","Building2","FileText","GraduationCap","HeartHandshake","Scale","UserCheck","UserRound","Users","UsersRound"],ij=["blue","rose","amber","violet","teal","emerald","slate"];function aO(t){return rj.includes(t)}o(aO,"isBucketIconName");function lO(t){return ij.includes(t)}o(lO,"isBucketColorName");var oj="__clear__";function dO(t){return t===""?"empty":t===oj?"reserved":null}o(dO,"selectOptionValueDefect");var yi=1024*1024,il=["application/pdf","image/jpeg","image/png","image/webp"];var sj=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","image/jpeg","image/png"],cO={docRef:{maxBytes:25*yi,allowedMime:il},partyFile:{maxBytes:25*yi,allowedMime:il},import:{maxBytes:500*yi,allowedMime:null},signedContract:{maxBytes:25*yi,allowedMime:il},artifactVersion:{maxBytes:25*yi,allowedMime:il},chatAttachment:{maxBytes:25*yi,allowedMime:il},tenantFile:{maxBytes:20*yi,allowedMime:sj},documentTemplate:{maxBytes:25*yi,allowedMime:null}};var Oke=Object.freeze({});function aj(t,e){return Object.freeze(Yc(Ar,t,e))}o(aj,"formContextEntries");function uO(t){return t.env??[]}o(uO,"declaredContextKeys");function fO(t,e){return uO(t).every(n=>pO(n,e?.[n]))}o(fO,"scenarioContextComplete");function pO(t,e){return zE(Ar,t,e)}o(pO,"contextValueComplete");function mO(t,e){return aj(e??{},uO(t))}o(mO,"scenarioContextEntries");function Kb(t){return Xs(t)}o(Kb,"isContextIdentifier");function lj(t,e,n){let r=Qc(Ar,t);if(r!==null)return{severity:"error",path:n,code:"env/unknownKey",message:r.message};let[,i=""]=t.split(".");return e.has(i)?null:{severity:"error",path:n,code:"env/undeclared",message:`'${t}' reads the environment key '${i}', which the form does not declare in \`env\`.`}}o(lj,"contextIdentifierIssue");var hO=Uc("stage.key");function dj(t){let e=[],n=o(i=>i.kind==="ident"&&i.path===hO,"isStageKey"),r=o(i=>{switch(i.kind){case"binary":if((i.op==="=="||i.op==="!=")&&(n(i.left)&&i.right.kind==="str"&&e.push(i.right.value),n(i.right)&&i.left.kind==="str"&&e.push(i.left.value)),i.op==="in"&&n(i.left)&&i.right.kind==="arr")for(let s of i.right.items)s.kind==="str"&&e.push(s.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(t),e}o(dj,"stageKeyLiterals");function gO(t,e,n){return e===void 0?[]:dj(t).filter(r=>!e.has(r)).map(r=>bO(r,e,n))}o(gO,"stageKeyAstIssues");function yO(t,e){if(e===void 0)return[];let n=[];for(let r of t.testScenarios??[]){let i=r.env?.stage;typeof i?.key=="string"&&!e.has(i.key)&&n.push(bO(i.key,e,`scenario:${r.id}/env`))}return n}o(yO,"scenarioStageKeyIssues");function bO(t,e,n){let r=[...e].sort();return{severity:"error",path:n,code:"env/unknownStageKey",message:`'${t}' is not a stage key of the offer's program \u2014 `+(r.length>0?`known: ${r.join(", ")}.`:"the offer has no program with stages.")+` \`${hO}\` is the bundle key (\`program.stages[].key\`), never the stored \`<program>-stufe-<key>\`.`}}o(bO,"unknownStageKeyIssue");function wO(t,e,n){let r=[];for(let i of dt(t)){if(!Kb(i))continue;let s=lj(i,e,n);s!==null&&r.push(s)}if(r.length>0)return r;for(let{identifier:i,op:s}of mg(t,Vc))r.push({severity:"error",path:n,code:"env/unguardedNullable",message:`'${s}' over '${i}', which is empty for some applications, needs a guard '${i} != null &&' before it \u2014 say what an empty value means.`});return r}o(wO,"contextAstIssues");function kO(t,e){let n=[...cj(t)],r=new Set(t.env??[]);for(let i of t.env??[]){if(!Eo(i)){n.push({severity:"error",path:"env",code:"env/unknownKey",message:`Declared environment key '${i}' is not in the vocabulary (${Qs.join(", ")}).`});continue}e!==void 0&&!e.has(i)&&n.push({severity:"error",path:"env",code:"env/unsupplied",message:`The form declares environment key '${i}', but its host does not supply it.`})}for(let i of t.testScenarios??[]){let s=[...r].filter(a=>Eo(a)&&!pO(a,i.env?.[a]));s.length>0&&n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unsampled",message:`Scenario '${i.id}' does not sample the declared environment key(s) ${s.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??{}))Eo(a)?r.has(a)||n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/undeclared",message:`Scenario '${i.id}' samples environment key '${a}', which the form does not declare.`}):n.push({severity:"error",path:`scenario:${i.id}/env`,code:"env/unknownKey",message:`Scenario '${i.id}' samples unknown environment key '${a}'.`})}return n}o(kO,"formContextIssues");function cj(t){let e=[];Object.hasOwn(t,"context")&&e.push({severity:"error",path:"context",code:"env/retiredField",message:"`context` is retired \u2014 a form declares the environment it reads as `env`."});let n=t.testScenarios;for(let r of Array.isArray(n)?n:[])r!==null&&typeof r=="object"&&Object.hasOwn(r,"context")&&e.push({severity:"error",path:`scenario:${String(r.id)}/context`,code:"env/retiredField",message:"`context` is retired \u2014 a scenario samples the environment as `env`."});return e}o(cj,"retiredContextFields");var vO=cO.docRef.allowedMime;function AO(t,e={}){let n=Yo(t).compiled,r=[],i=new Set,s=new Map,a=new Set,l=new Set,d=new Set,c=new Map,u=new Map;function f($,_){if(i.has($))return;i.add($);let j=s.get($.id);j&&j!==$?r.push({severity:"error",path:`sections[${_.join(".")}]`,code:"duplicate.section-id",message:`Section id '${$.id}' is declared more than once.`}):s.set($.id,$);let C=`sections[${_.join(".")}]`;$.fields.forEach((ne,le)=>{ts(a,ne.key,`${C}.fields[${le}]`,"duplicate.field-key",r),l.add(ne.key),u.set(ne.key,ne),c.set(ne.key,jb(ne)),ne.externalFlag&&(ne.type!=="boolean"&&r.push({severity:"error",path:`${C}.fields[${le}]`,code:"flag.not-boolean",message:`External flag '${ne.key}' must be type 'boolean' (got '${ne.type}').`}),ne.defaultValue==null&&r.push({severity:"error",path:`${C}.fields[${le}]`,code:"flag.missing-default",message:`External flag '${ne.key}' must declare a defaultValue (e.g. "false") so it is hidden by default.`})),r.push(...SO(ne,`${C}.fields[${le}]`))}),$.groups?.forEach((ne,le)=>{ne.fields.forEach((de,$e)=>{ts(a,de.key,`${C}.groups[${le}].fields[${$e}]`,"duplicate.field-key",r),l.add(de.key),u.set(de.key,de),c.set(de.key,jb(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.groups[${le}].fields[${$e}]`,code:"flag.invalid-location",message:`External flag '${de.key}' must be a direct section field, not a group field.`}),r.push(...SO(de,`${C}.groups[${le}].fields[${$e}]`))})}),$.repeated?.forEach((ne,le)=>{ne.itemTemplate.forEach((de,$e)=>{ts(a,de.key,`${C}.repeated[${le}].itemTemplate[${$e}]`,"duplicate.field-key",r),c.set(de.key,jb(de)),de.externalFlag&&r.push({severity:"error",path:`${C}.repeated[${le}].itemTemplate[${$e}]`,code:"flag.invalid-location",message:`External flag '${de.key}' must be a direct section field, not a repeated item field.`}),de.export&&r.push({severity:"error",path:`${C}.repeated[${le}].itemTemplate[${$e}]`,code:"export.in-repeated",message:`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[${le}].itemTemplate[${$e}]`,code:"config.sameas-in-repeated",message:`Field '${de.key}' declares sameAs inside a repeated itemTemplate \u2014 not supported.`}),de.type==="docRef"&&de.docRefConstraints?.multiple===!0&&r.push({severity:"error",path:`${C}.repeated[${le}].itemTemplate[${$e}]`,code:"config.docref-multiple-in-repeated",message:`Field '${de.key}' sets docRefConstraints.multiple inside a repeated itemTemplate \u2014 a multi-file upload is supported only as a section or group field.`})})}),$.computed?.forEach(ne=>{d.add(ne.key),ts(a,ne.key,`${C}.computed[${ne.key}]`,"duplicate.field-key",r),ne.export===!0&&ne.exportType===void 0&&r.push({severity:"error",path:`${C}.computed[${ne.key}]`,code:"export.computed-untyped",message:`Computed '${ne.key}' is exported without an exportType \u2014 declare string | number | boolean | date.`})}),$.subsections?.forEach((ne,le)=>f(ne,[..._,le]))}o(f,"visitRawSection"),t.sections.forEach(($,_)=>f($,[_]));let h=new Set;n.effects.forEach(($,_)=>{ts(h,$.id,`effects[${_}]`,"duplicate.effect-id",r)});let g=new Set;n.outcomes.forEach(($,_)=>{ts(g,$.id,`outcomes[${_}]`,"duplicate.outcome-id",r)}),n.outcomes.forEach(($,_)=>{$.output.effectRefs?.forEach((j,C)=>{h.has(j.effect)||r.push({severity:"error",path:`outcomes[${_}].output.effectRefs[${C}]`,code:"ref.unknown-effect",message:`Outcome '${$.id}' references unknown effect '${j.effect}'.`})})}),n.outcomes.forEach(($,_)=>{$.output.fields?.forEach((j,C)=>{sO(n,j.path)||r.push({severity:"error",path:`outcomes[${_}].output.fields[${C}]`,code:"ref.unknown-field",message:`Outcome '${$.id}' references unknown field '${j.path}'.`})})});let b=new Set;for(let $ of es(n.sections))for(let _ of $.section.repeated??[])b.add(`${_.key}.count`);for(let $ of b)(a.has($)||d.has($))&&r.push({severity:"error",path:"sections",code:"duplicate.field-key",message:`'${$}' is both a declared key and the derived row count of a repeated group \u2014 the derived value would silently win.`});let y={known:new Set([...a,...d,...b]),declaredContext:new Set(t.env??[]),stageKeys:e.stageKeys};r.push(...kO(t)),r.push(...oO(t,n,e.visibleToKeys)),r.push(...yO(t,e.stageKeys));for(let $ of es(n.sections)){let _=$.section,j=`sections[${$.path.join(".")}]`;_.visibleIf&&(qn(_.visibleIf,`${j}.visibleIf`,y,!1,r),ns(_.visibleIf,`${j}.visibleIf`,c,r)),_.fields.forEach((C,ne)=>Ub(C,`${j}.fields[${ne}]`,y,!1,c,r)),_.groups?.forEach((C,ne)=>{C.visibleIf&&(qn(C.visibleIf,`${j}.groups[${ne}].visibleIf`,y,!1,r),ns(C.visibleIf,`${j}.groups[${ne}].visibleIf`,c,r)),C.fields.forEach((le,de)=>Ub(le,`${j}.groups[${ne}].fields[${de}]`,y,!1,c,r))}),_.repeated?.forEach((C,ne)=>{C.itemVisibleIf&&(qn(C.itemVisibleIf,`${j}.repeated[${ne}].itemVisibleIf`,y,!0,r),ns(C.itemVisibleIf,`${j}.repeated[${ne}].itemVisibleIf`,c,r)),C.itemTemplate.forEach((le,de)=>Ub(le,`${j}.repeated[${ne}].itemTemplate[${de}]`,y,!0,c,r)),C.effects?.forEach((le,de)=>{le.when&&qn(le.when,`${j}.repeated[${ne}].effects[${de}].when`,y,!0,r)})}),_.computed?.forEach((C,ne)=>qn(C.expression,`${j}.computed[${ne}].expression`,y,!1,r))}n.effects.forEach(($,_)=>{$.when&&qn($.when,`effects[${_}].when`,y,!1,r)}),n.outcomes.forEach(($,_)=>{qn($.when,`outcomes[${_}].when`,y,!1,r)});let w=new Set(n.outcomes.map($=>$.id));function S($,_){$.requiredFor&&$.requiredFor.forEach((j,C)=>{w.has(j)||r.push({severity:"error",path:`${_}.requiredFor[${C}]`,code:"ref.unknown-required-for-outcome",message:`field "${$.key}": requiredFor references unknown outcome "${j}"`})})}o(S,"checkRequiredFor");for(let $ of es(n.sections)){let _=$.section,j=`sections[${$.path.join(".")}]`;_.fields.forEach((C,ne)=>S(C,`${j}.fields[${ne}]`)),_.groups?.forEach((C,ne)=>{C.fields.forEach((le,de)=>S(le,`${j}.groups[${ne}].fields[${de}]`))}),_.repeated?.forEach((C,ne)=>{C.itemTemplate.forEach((le,de)=>S(le,`${j}.repeated[${ne}].itemTemplate[${de}]`))})}function A($,_){let j=o((C,ne)=>{let le=(C.type==="docRef"?C.docRefConstraints?.mimeType??[]:[]).filter(de=>!vO.includes(de));le.length>0&&r.push({severity:"error",path:ne,code:"config.docref-type-outside-ceiling",message:`Field '${C.key}' allows ${le.map(de=>`'${de}'`).join(", ")} \u2014 no document upload accepts that type (allowed: ${vO.join(", ")}).`}),C.multiple===!0&&C.type!=="enum"&&r.push({severity:"error",path:ne,code:"config.multiple-non-enum",message:`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:ne,code:"config.yesno-non-boolean",message:`Field '${C.key}' sets presentation: 'yesNo' but is type '${C.type}' \u2014 only 'boolean' fields can be drawn as the Ja | Nein answer.`}),C.presentation==="yesNo"&&C.defaultValue!=null&&r.push({severity:"error",path:ne,code:"config.yesno-default",message:`Field '${C.key}' is a Ja | Nein question (presentation: 'yesNo') with a defaultValue \u2014 the family must choose the answer themselves. Remove the defaultValue.`}),typeof C.minSelections=="number"&&typeof C.maxSelections=="number"&&C.minSelections>C.maxSelections&&r.push({severity:"error",path:ne,code:"config.min-gt-max-selections",message:`Field '${C.key}' has minSelections (${C.minSelections}) > maxSelections (${C.maxSelections}).`}),(C.enumOptions??[]).forEach((de,$e)=>{let xe=dO(de);xe!==null&&r.push({severity:"error",path:`${ne}.enumOptions[${$e}]`,code:"config.enum-option-value",message:xe==="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 '${de}', which the single select reserves for its clear row. Rename the option.`})}),(C.attachments??[]).forEach((de,$e)=>{if("storageId"in de){r.push({severity:"error",path:`${ne}.attachments[${$e}]`,code:"config.attachment-source",message:`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 xe=de.fileKey!==void 0&&de.fileKey!=="",et=de.url!==void 0&&de.url!=="";xe===et&&r.push({severity:"error",path:`${ne}.attachments[${$e}]`,code:"config.attachment-source",message:`Field '${C.key}' attachment must set exactly one of 'fileKey' or 'url' (got ${xe&&et?"both":"neither"}).`}),de.renderAs==="inlineLink"&&de.label===void 0&&r.push({severity:"error",path:`${ne}.attachments[${$e}]`,code:"config.attachment-inline-link-label",message:`Field '${C.key}' inlineLink attachment needs a 'label' \u2014 the linked phrase shown in the field label.`})})},"considerField");$.fields.forEach((C,ne)=>j(C,`${_}.fields[${ne}]`)),$.groups?.forEach((C,ne)=>{C.fields.forEach((le,de)=>j(le,`${_}.groups[${ne}].fields[${de}]`))}),$.repeated?.forEach((C,ne)=>{C.itemTemplate.forEach((le,de)=>j(le,`${_}.repeated[${ne}].itemTemplate[${de}]`))}),$.subsections?.forEach((C,ne)=>A(C,`${_}.subsections[${ne}]`))}o(A,"visitFieldConfig"),t.sections.forEach(($,_)=>A($,`sections[${_}]`)),t.effects.forEach(($,_)=>{$.kind!=="person"&&$.kind!=="organization"||$.nameFrom?.forEach((j,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${_}].nameFrom[${C}]`,code:"ref.unknown-name-field",message:`Effect '${$.id}' nameFrom references unknown field '${j}'.`})})});let T=o(($,_)=>{if($.kind!=="person"&&$.kind!=="organization")return;let j=$.display;if(!j){r.push({severity:"error",path:`${_}.display`,code:"display.missing",message:`Effect '${$.id}' declares a party bucket but no display \u2014 Titel, Icon und Akzentfarbe der Partei w\xE4ren nicht aufl\xF6sbar.`});return}aO(j.icon)||r.push({severity:"error",path:`${_}.display.icon`,code:"display.unknown-icon",message:`Effect '${$.id}' display.icon '${j.icon}' is not a known bucket icon.`}),lO(j.color)||r.push({severity:"error",path:`${_}.display.color`,code:"display.unknown-color",message:`Effect '${$.id}' display.color '${j.color}' is not a known bucket colour.`})},"checkBucketDisplay");t.effects.forEach(($,_)=>T($,`effects[${_}]`));let N=new Set,F=o($=>{$.kind==="person"?N.add($.bucket):$.kind==="organization"&&N.add($.id.replace(/^o\./,""))},"declareBucket");t.effects.forEach(F);let x=new Set,v=o($=>{for(let _ of $)_.repeated?.forEach(j=>j.effects?.forEach(C=>F(C))),v(_.subsections??[])},"collectRepeatedBuckets");v(t.sections);let P=o(($,_)=>{N.size!==0&&$.forEach((j,C)=>{j.bucket===void 0||N.has(j.bucket)||r.push({severity:"error",path:`${_}[${C}].bucket`,code:"bucket.undeclared",message:`Field '${j.key}' belongs to bucket '${j.bucket}', but no person/organization effect declares it \u2014 das Feld geh\xF6rt zu keiner Partei.`})})},"checkFieldBuckets"),E=o(($,_)=>{if(x.has($))return;x.add($);let j=`sections[${_.join(".")}]`;P($.fields,`${j}.fields`),$.groups?.forEach((C,ne)=>P(C.fields,`${j}.groups[${ne}].fields`)),$.repeated?.forEach((C,ne)=>P(C.itemTemplate,`${j}.repeated[${ne}].itemTemplate`)),$.subsections?.forEach((C,ne)=>E(C,[..._,ne]))},"visitBucketSection");t.sections.forEach(($,_)=>E($,[_]));let M=t.effects.flatMap(($,_)=>$.kind==="person"&&$.subject===!0?[{e:$,i:_}]:[]);M.length>1&&M.slice(1).forEach(({e:$,i:_})=>{r.push({severity:"error",path:`effects[${_}].subject`,code:"subject.duplicate",message:`Effect '${$.id}' declares subject:true, but '${M[0].e.id}' already does. Genau ein Bucket darf das Subjekt der Bewerbung sein.`})}),M.forEach(({e:$,i:_})=>{($.nameFrom?.length??0)===0&&r.push({severity:"error",path:`effects[${_}].nameFrom`,code:"subject.without-name-binding",message:`Effect '${$.id}' is the application subject but declares no nameFrom \u2014 der Name der Bewerbung w\xE4re nicht aufl\xF6sbar.`})}),t.effects.forEach(($,_)=>{if(!($.kind!=="person"||$.nationalityFrom===void 0)){if($.subject!==!0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.not-subject",message:`Effect '${$.id}' declares nationalityFrom but is not the application subject \u2014 die Staatsangeh\xF6rigkeit wird nur f\xFCr das Subjekt der Bewerbung gelesen.`});return}if($.nationalityFrom.length===0){r.push({severity:"error",path:`effects[${_}].nationalityFrom`,code:"nationality.empty",message:`Effect '${$.id}' declares an empty nationalityFrom \u2014 omit it or name at least one field.`});return}$.nationalityFrom.forEach((j,C)=>{l.has(j)||r.push({severity:"error",path:`effects[${_}].nationalityFrom[${C}]`,code:"nationality.unknown-field",message:`Effect '${$.id}' nationalityFrom references unknown field '${j}'.`})})}});let q=t.effects.flatMap(($,_)=>$.kind==="person"&&$.contractParty!==void 0?[{e:$,i:_,decl:$.contractParty}]:[]);if(q.length>0){let $=q.filter(({decl:_})=>_.role==="beneficiary");$.slice(1).forEach(({e:_,i:j})=>{r.push({severity:"error",path:`effects[${j}].contractParty.role`,code:"contractParty.duplicate-beneficiary",message:`Effect '${_.id}' declares contractParty.role 'beneficiary', but '${$[0].e.id}' already does. Genau ein Bucket darf Leistungsempf\xE4nger sein.`})}),$.forEach(({e:_,i:j})=>{_.subject!==!0&&r.push({severity:"error",path:`effects[${j}].contractParty.role`,code:"contractParty.beneficiary-not-subject",message:`Effect '${_.id}' is the contract beneficiary but not the application subject. Leistungsempf\xE4nger und Subjekt der Bewerbung sind dieselbe Person \u2014 setze subject:true auf '${_.id}'.`})}),M.forEach(({e:_,i:j})=>{let C=_.contractParty?.role;C!==void 0&&C!=="beneficiary"&&r.push({severity:"error",path:`effects[${j}].contractParty.role`,code:"contractParty.subject-role-mismatch",message:`Effect '${_.id}' is the application subject but declares contractParty.role '${C}'. Das Subjekt der Bewerbung ist der Leistungsempf\xE4nger des Vertrags.`})}),q.some(({decl:_})=>_.signs===!0)||r.push({severity:"error",path:"effects",code:"contractParty.no-signer",message:"Das Formular deklariert Vertragsparteien, aber keine unterschreibt (contractParty.signs). Ein Vertrag ohne Unterzeichner kann nicht erzeugt werden."})}t.effects.forEach(($,_)=>{$.kind==="fieldMap"&&$.mappings.forEach((j,C)=>{a.has(j.from)||r.push({severity:"error",path:`effects[${_}].mappings[${C}].from`,code:"ref.unknown-fieldmap-from",message:`Effect '${$.id}' fieldMap from '${j.from}' references unknown field.`})})});for(let[$,_]of u){if(!_.sameAs)continue;let j=`fields[${$}].sameAs`,C=u.get(_.sameAs.source);C===void 0||_.sameAs.source===$?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:_.sameAs.source===$?`Field '${$}' sameAs.source references itself.`:`Field '${$}' sameAs.source references unknown field '${_.sameAs.source}' (must be a top-level or group field).`}):C.type!==_.type?r.push({severity:"error",path:`${j}.source`,code:"ref.unknown-sameas-source",message:`Field '${$}' (${_.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:`${j}.source`,code:"ref.unknown-sameas-source",message:`Field '${$}' sameAs.source '${_.sameAs.source}' itself declares sameAs \u2014 mirror chains are not supported.`});let ne=u.get(_.sameAs.toggle);(ne===void 0||ne.type!=="boolean")&&r.push({severity:"error",path:`${j}.toggle`,code:"ref.unknown-sameas-toggle",message:ne===void 0?`Field '${$}' sameAs.toggle references unknown field '${_.sameAs.toggle}'.`:`Field '${$}' sameAs.toggle '${_.sameAs.toggle}' must be type 'boolean' (got '${ne.type}').`}),_.required===!0&&r.push({severity:"error",path:`fields[${$}].required`,code:"config.sameas-static-required",message:`Field '${$}' 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 $=new Map;t.effects.forEach(_=>$.set(_.id,_.kind)),t.effects.forEach((_,j)=>{if(_.kind!=="shareValue")return;[["from",_.from],["to",_.to]].forEach(([le,de])=>{let $e=$.get(de.slice(1));$e!==void 0&&$e!=="person"&&$e!=="organization"&&r.push({severity:"error",path:`effects[${j}].${le}`,code:"ref.sharevalue-endpoint",message:`Effect '${_.id}' shareValue ${le} '${de}' must reference a person/organization effect (got '${$e}').`})});let C=_.from.slice(1);t.effects.some(le=>le.kind==="fieldMap"&&le.target.slice(1)===C&&le.mappings.some(de=>de.to===_.field)||le.kind==="shareValue"&&le.id!==_.id&&le.to.slice(1)===C&&le.field===_.field)||r.push({severity:"error",path:`effects[${j}].field`,code:"config.sharevalue-missing-source-map",message:`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.`})})}t.effects.forEach(($,_)=>{$.kind==="person"&&$.bucket.includes(Zi)&&r.push({severity:"error",path:`effects[${_}].bucket`,code:"config.bucket-name-contains-hash",message:`Effect '${$.id}' bucket '${$.bucket}' must not contain '${Zi}' (reserved for the per-row namespace).`}),$.kind==="organization"&&$.orgKind.includes(Zi)&&r.push({severity:"error",path:`effects[${_}].orgKind`,code:"config.bucket-name-contains-hash",message:`Effect '${$.id}' orgKind '${$.orgKind}' must not contain '${Zi}' (reserved for the per-row namespace).`})});let te=new Set;function B($,_){$.repeated?.forEach((j,C)=>{let ne=j.effects??[];if(ne.length>0){let le=`${_}.repeated[${C}]`,de=new Set(ne.map(ue=>ue.id)),$e=new Set(j.itemTemplate.map(ue=>ue.key)),xe=(j.uniqueBy?.length??0)>0,et=o(ue=>ue.startsWith("$item.")?$e.has(ue.slice(6)):l.has(ue),"resolvesName"),Ze=o(ue=>ue.startsWith("$item.")?$e.has(ue.slice(6)):a.has(ue),"resolvesFrom"),ut=o(ue=>{let ft=ue.slice(1);return de.has(ft)||h.has(ft)},"resolvesRef");ne.forEach((ue,ft)=>{let tt=`${le}.effects[${ft}]`;if(h.has(ue.id)||te.has(ue.id)?r.push({severity:"error",path:tt,code:"duplicate.repeated-effect-id",message:`Repeated effect id '${ue.id}' is declared more than once.`}):te.add(ue.id),ue.kind==="person"||ue.kind==="organization"){T(ue,tt),ue.kind==="person"&&ue.subject===!0&&r.push({severity:"error",path:`${tt}.subject`,code:"subject.in-repeated",message:`Repeated effect '${ue.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.`}),ue.kind==="person"&&ue.nationalityFrom!==void 0&&r.push({severity:"error",path:`${tt}.nationalityFrom`,code:"nationality.not-subject",message:`Repeated effect '${ue.id}' declares nationalityFrom \u2014 only the application subject (a top-level effect) carries it.`}),ue.kind==="person"&&ue.contractParty!==void 0&&r.push({severity:"error",path:`${tt}.contractParty`,code:"contractParty.in-repeated",message:`Repeated effect '${ue.id}' declares contractParty \u2014 who signs is declared once per application, not once per row. Declare it on a top-level effect.`}),xe||r.push({severity:"error",path:le,code:"config.repeated-effect-requires-uniqueBy",message:`Repeated def '${j.key}' has a party-creating effect '${ue.id}' but no 'uniqueBy' \u2014 per-row parties need a stable identity key.`});let Pe=ue.kind==="person"?ue.bucket:ue.orgKind;Pe.includes(Zi)&&r.push({severity:"error",path:`${tt}.${ue.kind==="person"?"bucket":"orgKind"}`,code:"config.bucket-name-contains-hash",message:`Repeated effect '${ue.id}' ${ue.kind==="person"?"bucket":"orgKind"} '${Pe}' must not contain '${Zi}'.`}),ue.nameFrom?.forEach((Be,Ut)=>{et(Be)||r.push({severity:"error",path:`${tt}.nameFrom[${Ut}]`,code:"ref.unknown-name-field",message:`Repeated effect '${ue.id}' nameFrom references unknown field '${Be}'.`})}),ue.identity?.strategy==="keyed"&&ue.identity.keyFrom.forEach((Be,Ut)=>{Ze(Be)||r.push({severity:"error",path:`${tt}.identity.keyFrom[${Ut}]`,code:"ref.unknown-fieldmap-from",message:`Repeated effect '${ue.id}' identity.keyFrom references unknown field '${Be}'.`})})}else if(ue.kind==="relationship"){if([["from",ue.from],["to",ue.to]].forEach(([Pe,Be])=>{ut(Be)||r.push({severity:"error",path:`${tt}.${Pe}`,code:"ref.unknown-repeated-effect",message:`Repeated relationship '${ue.id}' ${Pe} references unknown effect '${Be}'.`})}),ue.meta)for(let[Pe,Be]of Object.entries(ue.meta))typeof Be=="string"&&Be.startsWith("$")&&!ut(Be)&&r.push({severity:"error",path:`${tt}.meta.${Pe}`,code:"ref.unknown-repeated-effect",message:`Repeated relationship '${ue.id}' meta.${Pe} references unknown effect '${Be}'.`})}else ue.kind==="fieldMap"?(ut(ue.target)||r.push({severity:"error",path:`${tt}.target`,code:"ref.unknown-repeated-effect",message:`Repeated fieldMap '${ue.id}' target references unknown effect '${ue.target}'.`}),ue.mappings.forEach((Pe,Be)=>{Ze(Pe.from)||r.push({severity:"error",path:`${tt}.mappings[${Be}].from`,code:"ref.unknown-fieldmap-from",message:`Repeated fieldMap '${ue.id}' from '${Pe.from}' references unknown field.`})})):ue.kind==="shareValue"&&r.push({severity:"error",path:tt,code:"config.sharevalue-in-repeated",message:`Repeated effect '${ue.id}': shareValue is not supported inside repeated row effects.`})})}}),$.subsections?.forEach((j,C)=>B(j,`${_}.subsections[${C}]`))}o(B,"visitRepeatedEffects"),t.sections.forEach(($,_)=>B($,`sections[${_}]`));let H=Z_(n.effects);return H.hasCycle&&r.push({severity:"error",path:"effects",code:"graph.effect-cycle",message:`Effect graph contains a cycle: ${H.cycle?.join(" \u2192 ")??"?"}`}),r.push(...uj(t)),r}o(AO,"validateForm");function uj(t){let e={...t,effects:t.effects.map(EO),sections:t.sections.map(RO),testScenarios:t.testScenarios?.map(n=>({id:n.id,label:n.label,description:n.description}))};return cf(e,"form").map(n=>({severity:"error",path:n.path,code:"i18n.missing-translation",message:Mb(n)}))}o(uj,"missingTranslationIssues");function EO(t){if(!("subject"in t))return t;let{subject:e,...n}=t;return n}o(EO,"withoutSubjectFlag");function RO(t){return{...t,repeated:t.repeated?.map(e=>({...e,effects:e.effects?.map(EO)})),subsections:t.subsections?.map(RO)}}o(RO,"withoutRowSubjectFlags");function SO(t,e){if(!t.export)return[];let n=[];return t.type==="docRef"&&n.push({severity:"error",path:e,code:"export.invalid-type",message:`Field '${t.key}' (docRef) cannot be exported \u2014 a storage handle is not a bindable document value.`}),t.multiple===!0&&n.push({severity:"error",path:e,code:"export.multiple-enum",message:`Field '${t.key}' is a multi-select \u2014 N picked options are not one compound leaf, so it cannot be exported.`}),n}o(SO,"exportGateIssues");function ts(t,e,n,r,i){t.has(e)?i.push({severity:"error",path:n,code:r,message:`Duplicate ${fj(r)}: '${e}'`}):t.add(e)}o(ts,"reportIfDup");function fj(t){switch(t){case"duplicate.section-id":return"section id";case"duplicate.field-key":return"field key";case"duplicate.effect-id":return"effect id";case"duplicate.outcome-id":return"outcome id";case"ref.unknown-required-for-outcome":return"requiredFor outcome";default:return t}}o(fj,"labelForCode");function Ub(t,e,n,r,i,s){t.visibleIf&&(qn(t.visibleIf,`${e}.visibleIf`,n,r,s),ns(t.visibleIf,`${e}.visibleIf`,i,s)),t.requiredIf&&(qn(t.requiredIf,`${e}.requiredIf`,n,r,s),ns(t.requiredIf,`${e}.requiredIf`,i,s)),t.disabledIf&&(qn(t.disabledIf,`${e}.disabledIf`,n,r,s),ns(t.disabledIf,`${e}.disabledIf`,i,s)),t.defaultValue&&qn(t.defaultValue,`${e}.defaultValue`,n,r,s)}o(Ub,"checkFieldAsts");function jb(t){return{hasDefault:t.defaultValue!=null,isBoolean:t.type==="boolean",isYesNo:t.type==="boolean"&&t.presentation==="yesNo"}}o(jb,"gatingMeta");function ns(t,e,n,r){function i(s){switch(s.kind){case"binary":{(s.op==="=="||s.op==="!=")&&(xO(s.left,s.right,s.op,e,n,r),xO(s.right,s.left,s.op,e,n,r)),i(s.left),i(s.right);return}case"unary":i(s.operand);return;case"if":i(s.cond),i(s.then),i(s.else);return;case"call":s.args.forEach(i);return;case"arr":s.items.forEach(i);return;default:return}}o(i,"walk"),i(t)}o(ns,"checkGatingExpr");function xO(t,e,n,r,i,s){if(t.kind!=="ident")return;let a=i.get(t.path);a&&a.isBoolean&&(a.hasDefault||e.kind!=="null"&&e.kind==="bool"&&(a.isYesNo&&n==="=="||s.push({severity:"error",path:r,code:"expr.gating-compare-undefaulted-field",message:`Gating expression compares undefaulted boolean field '${t.path}' to a bool literal via '${n}'. In three-valued logic, 'undefined ${n} ${e.value}' is ${n==="=="?"false":"true"} \u2014 the gate fires silently for unset values. Add a 'defaultValue' to field '${t.path}' (or rewrite the expression \u2014 e.g. '${t.path} != null' for an explicit set-check).`})))}o(xO,"inspectEqualityOperand");function qn(t,e,n,r,i){i.push(...wO(t,n.declaredContext,e)),i.push(...gO(t,n.stageKeys,e));for(let s of dt(t))n.known.has(s)||Kb(s)||r&&s.startsWith("$item.")||i.push({severity:"error",path:e,code:"ref.unknown-ident",message:s.startsWith("$")?`Identifier '${s}' is no scope a form reads \u2014 environment variables are '$env.<key>.<field>', repeated rows '$item.*'.`:`Identifier '${s}' is not declared as a field, computed key, or $item slot.`})}o(qn,"checkAst");var pj="blocked";function TO(t,e){let n={values:e};for(let r of t.outcomes){let i;try{i=lt(r.when,n)}catch(s){W(`resolveActiveOutcome: outcome "${r.id}" when-expression threw: ${s instanceof Error?s.message:String(s)}`,{cause:s})}if(mj(i))return r.id===pj?null:r.id}return null}o(TO,"resolveActiveOutcome");function mj(t){return!(t==null||t===!1||t===0||t===""||Array.isArray(t)&&t.length===0)}o(mj,"truthy");function IO(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}o(IO,"isScalar");function hj(t,e,n){for(let[r,i]of Object.entries(t))if(i!==void 0){if(IO(i)){e[r]=i;continue}if(Array.isArray(i)){e[r]=i;continue}for(let[s,a]of Object.entries(i))IO(a)&&(e[`${r}.${s}`]=a)}gj(t,e,n)}o(hj,"mergeRecord");function gj(t,e,n){let r=new Set(n);for(let i of Object.keys(t)){let s=i.indexOf("[");if(s<=0)continue;let a=i.slice(0,s);gi(a).test(i)&&r.add(a)}for(let i of r){let s=Bb(t,i),a=0;for(let l=0;l<s;l++)eO(t,i,l)&&a++;e[`${i}.count`]=a}}o(gj,"mergeRepeatedCounts");function $O(t,e,n){let r={...n};return hj(t,r,e),r}o($O,"flattenValues");function _O(t){return!(t==null||t===!1||t===0||t===""||Array.isArray(t)&&t.length===0)}o(_O,"truthyEval");function OO(t){if(t==null)return!0;if(typeof t=="string")return t.trim()==="";if(Array.isArray(t))return t.length===0;if(typeof t=="object"){let e=t;if("storageId"in e)return!(typeof e.storageId=="string"&&e.storageId.trim()!=="");let n=e;return!n.street?.trim()||!n.hausnr?.trim()||!n.plz?.trim()||!n.ort?.trim()||!n.land?.trim()}return!1}o(OO,"isEmptyValue");function yj(t,e,n){let r=!!t.required;if(!r&&t.requiredIf)try{r=_O(lt(t.requiredIf,{values:e}))}catch{r=!1}return r?t.requiredFor?n===null?!1:t.requiredFor.includes(n):!0:!1}o(yj,"fieldIsLiveRequired");function bj(t,e,n){return CO(t,e,n).evalCtx}o(bj,"buildSubmitEvalContext");function CO(t,e,n){let r=wj(t),i=Object.keys(e).filter(l=>r(l)!==null),s=new Set(i),a=new Set;for(;;){let l={};for(let[g,b]of Object.entries(e))(r(g)===null||s.has(g))&&(l[g]=b);let d=PO(t,l,n),c=new Set,u=new Set;DO(t,d,g=>c.add(g.key),g=>u.add(g.key));let f=new Set(i.filter(g=>{let b=r(g);return b.kind==="field"?c.has(g):u.has(b.repeatedKey)}));if(f.size===s.size&&[...f].every(g=>s.has(g))){let g={};for(let b of i)s.has(b)||(g[b]=e[b]);return{visible:l,hidden:g,evalCtx:d}}let h=[...f].sort().join("\0");if(a.has(h)){let g=i.filter(b=>f.has(b)!==s.has(b));W(`[smartForm] visibility of ${g.join(", ")} does not settle \u2014 each depends on whether the other's value counts. The form's visibleIf conditions are contradictory.`)}a.add(h),s=f}}o(CO,"splitWithContext");function wj(t){let e=new Map,n=[];for(let r of mf(t.sections)){for(let i of r.fields)e.set(i.key,i);for(let i of r.groups??[])for(let s of i.fields)e.set(s.key,s);for(let i of r.repeated??[])n.push({key:i.key,pattern:gi(i.key),items:new Map(i.itemTemplate.map(s=>[s.key,s]))})}return r=>{let i=e.get(r);if(i!==void 0)return{kind:"field",field:i};for(let s of n){let a=s.pattern.exec(r);if(a!==null)return{kind:"row",repeatedKey:s.key,field:s.items.get(a[2])}}return null}}o(wj,"fieldOwnership");function PO(t,e,n){let r=[];for(let s of mf(t.sections))for(let a of s.repeated??[])r.push(a.key);let i=$O(e,r,n);for(let s of mf(t.sections))for(let a of s.computed??[])try{i[a.key]=lt(a.expression,{values:i})}catch{}return i}o(PO,"rawEvalContext");function NO(t,e,n){let{values:r,defaulted:i}=kj(t,e,n),s=CO(t,r,n),a={};for(let[l,d]of Object.entries(s.hidden))i.has(l)||(a[l]=d);return{...s,hidden:a}}o(NO,"splitDraftValues");function kj(t,e,n,r){let i={...e},s=new Set,a=null;for(let l of mf(t.sections))for(let d of[...l.fields,...(l.groups??[]).flatMap(c=>c.fields)]){if(!d.defaultValue||e[d.key]!=null||r?.(d.key))continue;a??=PO(t,e,n);let c;try{c=lt(d.defaultValue,{values:a})}catch(u){W(`[smartForm] defaultValue of '${d.key}' does not evaluate: ${u instanceof Error?u.message:String(u)}`)}c!=null&&(i[d.key]=c,s.add(d.key))}return{values:i,defaulted:s}}o(kj,"applyFieldDefaults");function mf(t){let e=[],n=o(r=>{e.push(r);for(let i of r.subsections??[])n(i)},"walk");for(let r of t)n(r);return e}o(mf,"walkSectionsDeep");function vj(t,e,n,r=!1){if(OO(e))return null;let i=n.fields[t.type];i||W(`[fieldFormatIssue] no field provider registered for type "${t.type}" (field "${t.key}"). Register it in the domain form registry.`);let s=i.validate(t,e,{state:{values:{},computed:{}},testMode:r});return s.length>0?s[0].message:null}o(vj,"fieldFormatIssue");function pf(t,e){if(!t)return!0;try{return _O(lt(t,{values:e}))}catch{return!1}}o(pf,"isVisibleUnder");function DO(t,e,n,r){let i=o(s=>{if(pf(s.visibleIf,e)){for(let a of s.fields)pf(a.visibleIf,e)&&n(a);for(let a of s.groups??[])if(pf(a.visibleIf,e))for(let l of a.fields)pf(l.visibleIf,e)&&n(l);if(r!==void 0)for(let a of s.repeated??[])r(a);for(let a of s.subsections??[])i(a)}},"walk");for(let s of t.sections)i(s)}o(DO,"forEachVisibleField");function FO(t,e,n,r={}){let i=bj(t,e,n),s=[],a=TO(t,i);a===null&&r.requireOutcome!==!1&&s.push({code:"no-outcome",fieldKey:null,message:"Die Angaben ergeben keinen g\xFCltigen Abschluss \u2014 bitte pr\xFCfen Sie das Formular."});let l=new Set(r.exemptFromRequired??[]);return DO(t,i,d=>{let c=e[d.key];if(OO(c)){!l.has(d.type)&&yj(d,i,a)&&s.push({code:"required",fieldKey:d.key,message:`${d.label.de} ist ein Pflichtfeld.`});return}if(!r.registry)return;let u=vj(d,c,r.registry,r.testMode===!0);u!==null&&s.push({code:"format",fieldKey:d.key,message:u})}),{issues:s,activeOutcome:a,evalCtx:i,submittable:s.length===0}}o(FO,"checkSubmittable");function LO(t){let e=t.testScenarios??[];if(e.length===0)return[];let{compiled:n}=Yo(t),r=[];for(let i of e){let s=i.prefill??{};if(!fO(t,i.env))continue;let a=mO(t,i.env),{visible:l}=NO(n,s,a),d=FO(n,l,a,{exemptFromRequired:["docRef"]});for(let c of d.issues){if(c.code==="no-outcome"){r.push({severity:"error",path:`scenario:${i.id}`,code:"scenario.no-outcome",message:`Szenario "${i.label.de}" erreicht kein g\xFCltiges Outcome \u2013 der Testfall ist nicht absendbar.`});continue}if(c.code==="required"){r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.required-field-unfilled",message:`Szenario "${i.label.de}" l\xE4sst das Pflichtfeld ${c.fieldKey} unbef\xFCllt \u2013 kein g\xFCltiges Outcome.`});continue}r.push({severity:"error",path:`scenario:${i.id}/${c.fieldKey}`,code:"scenario.invalid-value",message:`Szenario "${i.label.de}": ${c.message}`})}}return r}o(LO,"validateScenarios");function MO(t,e={}){return[...AO(t,e),...LO(t)]}o(MO,"runFormValidators");function qO(t){return Qu(t)}o(qO,"blockingFormErrors");function Sj(t){let e=[],n=t.buses;if(!Array.isArray(n))return e;let r=n.find(i=>!!i&&typeof i=="object"&&i.key==="process");if(!r||!Array.isArray(r.states))return e;for(let i of r.states){if(!i||typeof i!="object")continue;let s=i;if(s.terminal!==!0&&(!s.external||typeof s.external!="object")){let a=typeof s.id=="string"?s.id:"?";e.push(`manifest: progress state '${a}' is non-terminal but declares no 'external' block (applicant-facing copy) \u2014 resolveStatusPresentation would throw at runtime`)}}return e}o(Sj,"validateProgressLayoutExternalCopy");function BO(t){let e=[];if(!t||typeof t!="object")return e.push("manifest: data must be an object"),e;let n=t;(typeof n.id!="string"||!n.id)&&e.push("manifest: id is required");let r=wt(n.label);if(r==="not-localized"?e.push("manifest: label is required as { de, en }"):r.length>0&&e.push(`[i18n/missingTranslation] manifest.label fehlt in: ${r.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`),typeof n.version!="number"&&e.push("manifest: version is required"),n.capacity!==void 0&&typeof n.capacity!="number"&&e.push("manifest: capacity, when present, must be numeric"),!n.progressLayout||typeof n.progressLayout!="object"?e.push("manifest: progressLayout (the full layout object) is required in data"):e.push(...Sj(n.progressLayout)),!n.roleInstances||!Array.isArray(n.roleInstances))e.push("manifest: roleInstances must be an array");else{let i=new Set;for(let s of n.roleInstances){if(!s||typeof s!="object"){e.push("manifest: roleInstance is not an object");continue}if(typeof s.key!="string"||!s.key){e.push("manifest: roleInstance.key is required");continue}i.has(s.key)&&e.push(`manifest: duplicate roleInstance key ${s.key}`),i.add(s.key),s.customRoleId||e.push(`manifest: roleInstance ${s.key} missing customRoleId`),s.cardinality||e.push(`manifest: roleInstance ${s.key} missing cardinality`),e.push(...Gb(s.label,`roleInstances.${s.key}.label`));for(let a of Array.isArray(s.attributes)?s.attributes:[])e.push(...Gb(a?.label,`roleInstances.${s.key}.attributes.${a?.key}.label`))}}if(!n.leistungen||!Array.isArray(n.leistungen))e.push("manifest: leistungen must be an array");else{let i=new Set;for(let s of n.leistungen){if(!s||typeof s!="object"||typeof s.key!="string"||!s.key){e.push("manifest: leistung.key is required");continue}i.has(s.key)&&e.push(`manifest: duplicate leistung key ${s.key}`),i.add(s.key),e.push(...Gb(s.label,`leistungen.${s.key}.label`))}}return e}o(BO,"validateManifestBlob");function Gb(t,e){let n=wt(t);return n==="not-localized"?[`[i18n/missingTranslation] manifest: ${e} ist kein zweisprachiger Text ({ de, en })`]:n.length>0?[`[i18n/missingTranslation] manifest: ${e} fehlt in: ${n.join(", ")}`]:[]}o(Gb,"unlocalizedLabel");function KO(t){let e=t.nodes??[],n=new Map;for(let r of e){if(r.type!=="form"||typeof r.id!="string"||ii(r))continue;let s=r.inputs?.smartForm;s?.kind==="literal"&&typeof s.value=="string"&&s.value&&n.set(r.id,s.value)}return n}o(KO,"formNodeSlugById");function xj(t,e){let n=t.smartforms??{},r=new Map;for(let[i,s]of KO(e)){let a=n[s];if(a===void 0)return;r.set(i,a)}return w_(r)}o(xj,"readinessContext");function Aj(t){return[...KO(t).values()]}o(Aj,"formNodeSlugs");function VO(t){let e=t.code?`[${t.code}] `:"",n=t.path?`${t.path}: `:"";return`${e}${n}${t.reason??t.message??JSON.stringify(t)}`}o(VO,"describe");function bn(t){let e=[];for(let l of BO(t.manifest))e.push({severity:"error",area:"manifest",message:l});let n=wt(t.index.label);(n==="not-localized"||n.length>0)&&e.push({severity:"error",area:"manifest",message:`[i18n/missingTranslation] bundle.yaml label fehlt in: ${n==="not-localized"?"de, en":n.join(", ")} \u2014 jeder angezeigte Text braucht Deutsch und Englisch.`});let{manifest:r,workflow:i}=t.index.slugs;i!==void 0&&i!==r&&e.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 cu(t.index.program?.stages??[]))e.push({severity:"error",area:"program",message:l.message});for(let l of pu(t.index.program?.runs??[]))e.push({severity:"error",area:"program",message:l.message});for(let l of mu(t.index.program?.runs??[],t.index.program?.stages?.map(d=>d.key)))e.push({severity:"error",area:"program",message:l});if(t.workflow!==void 0){let l=t.workflow.graph,d=t.manifest.progressLayout,c=t.workflow.progressWiring,u=Y_(l,{layout:d,wiring:c},xj(t,l)),f=new Set(J_(u));for(let h of u)e.push({severity:f.has(h)||(h.severity??"error")==="error"?"error":"warning",area:"workflow",message:VO(h)})}let s=t.index.program?.stages,a=s===void 0?void 0:new Set(s.map(l=>l.key));for(let[l,d]of Object.entries(t.smartforms??{})){let u=MO(d,{stageKeys:a}),f=new Set(qO(u));for(let h of u)e.push({severity:f.has(h)||h.severity==="error"?"error":"warning",area:"smartform",message:`${l}: ${VO(h)}`})}if(t.workflow!==void 0){let l=t.workflow.graph,d=new Set(Aj(l)),c=new Set(Object.keys(t.smartforms??{}));for(let u of d)c.has(u)||e.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)||e.push({severity:"warning",area:"consistency",message:`smartform "${u}" is carried but no form node binds it`})}return e}o(bn,"validateBundle");var Xi={same:"\xB7",create:"+",change:"~",absent:"\u2205"};async function vt(t,e,n){let i=(await t.query(R.workflow.listManifests,{client:e})).find(s=>s.offerKey===n);if(!i)throw new Error(`offer: no offer "${n}" in tenant "${e}"`);return i}o(vt,"findOfferHandle");function nn(t,e,n){return t.query(R.programAdmin.getAngebotConfig,{client:e,offerKey:n,includeArchived:!0})}o(nn,"loadConfig");function Wb(t,e){let n=t.units.find(r=>r.key===e);if(!n)throw new Error(`offer: unit "${e}" not found. Available keys: ${t.units.map(r=>r.key??"(no key)").join(", ")||"(none)"}`);return n.unitId}o(Wb,"resolveUnitId");function rs(t,e){let n=UO(t),r=t.runs.find(i=>i.key===Ir(n,e));if(!r)throw new Error(`offer: run "${e}" not found. Available keys: ${t.runs.map(i=>No(n,i.key)).join(", ")||"(none)"}`);return r.runId}o(rs,"resolveRunId");function is(t,e){let n=UO(t),r=t.stages.find(i=>i.key===ry(n,e));if(!r)throw new Error(`offer: level "${e}" not found. Available keys: ${t.stages.map(i=>In(n,i.key)).join(", ")||"(none)"}`);return r.stageId}o(is,"resolveStageId");function UO(t){if(t.programKey===null)throw new Error("offer: the offer has no program yet \u2014 link a unit first");return t.programKey}o(UO,"requireProgramKey");async function zb(t,e,n,r){let i={client:e,offerKey:n,unitId:r};await t.mutation(R.programAdmin.ensurePedagogyUnit,{client:e,unitId:r}),await t.mutation(R.programAdmin.linkManifestPedagogyUnit,i),await t.mutation(R.programAdmin.createProgramForAngebot,i)}o(zb,"linkUnit");function eo(t,e){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new Error(`offer: --${t} must be a non-negative integer`);return n}o(eo,"parsePositiveInt");async function hf(t,e,n,r){let i=await t.query(R.organization.getOrgTree,{client:e}),s=i.units.find(a=>(a.configKey??a.slug)===n);if(!s)throw new Error(`${r}: unit "${n}" not found. Available keys: ${i.units.map(a=>a.configKey??a.slug).join(", ")||"(none)"}`);return s}o(hf,"findOrgTreeUnit");var Hb=["school","kindergarten","after_school_care","department","site","other"];var ol=class extends V{static{o(this,"OfferExportCommand")}static paths=[["offer","export"]];static usage=I.Usage({category:"Offer",description:"Pull a live offer (manifest + smartform + workflow + program) into a bundle"});slug=p.String("--slug",{required:!0,description:"Manifest slug to export"});out=p.String("--out",{required:!0,description:"Output bundle directory"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await T$(e,n,this.slug),i=Qb.resolve(this.out);return or({...r,dir:i}),this.print({exported:`${n}/${this.slug}`,dir:i},s=>[{key:"exported",value:s.exported},{key:"dir",value:s.dir}]),0}},sl=class extends Re{static{o(this,"OfferInitCommand")}static paths=[["offer","init"]];static usage=I.Usage({category:"Offer",description:"Scaffold a complete, publishable, minimal linear offer bundle on disk"});slug=p.String("--slug",{required:!0,description:"New offer slug (identity key)"});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>)"});async execute(){if(this.template!=="basic")throw new Error(`offer init: unknown template "${this.template}" (only 'basic')`);let e=Qb.resolve(this.out??Qb.join("offers",this.tenant,this.slug)),n=L$({slug:this.slug,title:tn({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 or({...n,dir:e}),this.print({created:`${this.tenant}/${this.slug}`,dir:e},r=>[{key:"created",value:r.created},{key:"dir",value:r.dir},{key:"next",value:`plexus offer validate --dir ${r.dir}`}]),0}},al=class extends Re{static{o(this,"OfferValidateCommand")}static paths=[["offer","validate"]];static usage=I.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 e=_e(this.dir),n=bn(e);return this.print(n,r=>r.length===0?[{severity:"ok",area:"-",message:"local validation clean"}]:r.map(i=>({severity:i.severity,area:i.area,message:i.message}))),n.some(r=>r.severity==="error")?1:0}},ll=class extends V{static{o(this,"OfferPlanCommand")}static paths=[["offer","plan"]];static usage=I.Usage({category:"Offer",description:"Read-only: local validation + remote\u2194local diff (create/change/same)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=_e(this.dir),n=bn(e),r=await this.caller(),i=await Wu(r,e.index.tenant,e),s=await gb(r,e);return this.print({validation:n,resolverPins:i,diff:s},()=>[...n.map(a=>({kind:`local:${a.severity}`,target:a.area,detail:a.message})),...i.map(a=>({kind:"=",target:a.target,detail:a.detail})),{kind:Xi[s.manifest],target:"manifest",detail:s.manifest},...Object.entries(s.smartforms).map(([a,l])=>({kind:Xi[l],target:`smartform:${a}`,detail:l})),{kind:Xi[s.workflow],target:"workflow",detail:s.workflow},...jO(s).map(a=>({kind:a.icon,target:a.target,detail:a.status})),...GO(s).map(a=>({kind:a.icon,target:a.target,detail:a.status})),...WO(s).map(a=>({kind:a.icon,target:a.target,detail:a.status})),...zO(s).map(a=>({kind:a.icon,target:a.target,detail:a.status}))]),n.some(a=>a.severity==="error")?1:0}},dl=class extends V{static{o(this,"OfferDiffCommand")}static paths=[["offer","diff"]];static usage=I.Usage({category:"Offer",description:"Read-only remote\u2194local drift (no local validation)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=_e(this.dir),n=await this.caller(),r=await Wu(n,e.index.tenant,e),i=await gb(n,e);return this.print(i,()=>[...r.map(s=>({icon:"=",target:s.target,status:s.detail})),{icon:Xi[i.manifest],target:"manifest",status:i.manifest},...Object.entries(i.smartforms).map(([s,a])=>({icon:Xi[a],target:`smartform:${s}`,status:a})),{icon:Xi[i.workflow],target:"workflow",status:i.workflow},...jO(i),...GO(i),...WO(i),...zO(i)]),0}};function jO(t){return t.addresses===null?[]:E$(t.addresses)}o(jO,"addressRows");function GO(t){let e={insert:"+",update:"~",archive:"-"};return t.stages.map(n=>({icon:e[n.op],target:`stage:${n.key}`,status:fu(n)}))}o(GO,"stageRows");function WO(t){return t.capacities.map(e=>({icon:"~",target:`cap:${e.run}\xD7${e.stageKey}`,status:hu(e)}))}o(WO,"capacityRows");function zO(t){if(t.publishPending===null)return[];let e=t.externalHeadRevision===null?"none":`v${t.externalHeadRevision}`;return[{icon:t.publishPending?"!":"=",target:"publish",status:t.publishPending?`pending (draft v${t.draftRevision} ahead of live ${e})`:`up to date (live ${e})`}]}o(zO,"publishPendingRows");var cl=class extends V{static{o(this,"OfferApplyCommand")}static paths=[["offer","apply"]];static usage=I.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(){let e=_e(this.dir),r=bn(e).filter(l=>l.severity==="error");if(r.length>0){let l=this.publish?"\u2716":"\u26A0";for(let d of r)this.context.stderr.write(` ${l} ${d.area}: ${d.message}
|
|
413
|
+
`);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)
|
|
414
|
+
`)}if(this.stage!=="internal"&&this.stage!=="external")throw new Error(`offer: --stage must be 'internal' or 'external' (got "${this.stage}")`);let i=await this.caller(),s=await Wu(i,e.index.tenant,e);for(let l of s)this.context.stderr.write(` = ${l.target}: ${l.detail}
|
|
415
|
+
`);let a=await R$(i,e,{publish:this.publish,publishStage:this.stage});return this.print(a,l=>l.steps.map(d=>({step:d.step,action:d.action,detail:d.detail??""}))),0}};var ul=class extends V{static{o(this,"OfferListCommand")}static paths=[["offer","list"]];static usage=I.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 e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.workflow.listManifests,{client:n}),i=this.all?r:r.filter(s=>s.archivedAt==null);return this.print(i,s=>s.map(a=>({slug:a.offerKey,state:a.archivedAt!=null?"archived":a.isPublished?"published":"draft",sortOrder:a.sortOrder?.toString()??"-",label:Fe(a.label)}))),0}},fl=class extends V{static{o(this,"OfferStatusCommand")}static paths=[["offer","status"]];static usage=I.Usage({category:"Offer",description:"Publish state + whether program/pedagogy links resolve (applyable?)"});slug=p.String("--slug",{required:!0,description:"Manifest slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),i=(await e.query(R.workflow.listManifests,{client:n})).find(d=>d.offerKey===this.slug);if(!i)throw new Error(`offer: no offer "${this.slug}" in "${n}"`);let s=await e.query(R.workflow.getOfferPublishState,{client:n,offerKey:this.slug}),a=o(d=>d==null?"-":`v${d}`,"rev"),l={manifest:i.isPublished?"published":"draft",workflow:i.workflowDefinitionId?"bound":"MISSING",pedagogy:i.pedagogy?Fe(i.pedagogy.unitName):"UNLINKED (not applyable)",draft:a(s?.draftRevision),internal:a(s?.internalHeadRevision),live:a(s?.externalHeadRevision),publish:s===null?"-":s.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}};var HO={de:"--title",en:"--title-en"},pl=class extends V{static{o(this,"OfferCreateCommand")}static paths=[["offer","create"]];static usage=I.Usage({category:"Offer",description:"Create a draft offer (manifest) \u2014 title (= program name) + optional unit"});slug=p.String("--slug",{required:!0,description:"New offer slug (identity key)"});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 e=await this.caller(),n=this.requireTenant(e),r=tn({de:this.title,en:this.titleEn},"offer create",HO);if(await e.mutation(R.workflow.createManifest,{client:n,slug:this.slug,label:r}),this.unit){let i=await nn(e,n,this.slug);await zb(e,n,this.slug,Wb(i,this.unit))}return this.print({created:this.slug,title:r,unit:this.unit??null},i=>[{key:"created",value:i.created},{key:"title",value:Fe(i.title)},{key:"unit",value:i.unit??"\u2014"}]),0}},ml=class extends V{static{o(this,"OfferShowCommand")}static paths=[["offer","show"]];static usage=I.Usage({category:"Offer",description:"Full view of an offer: title, unit, levels, runs, capacity, state (incl. archived)"});slug=p.String("--slug",{required:!0,description:"Offer slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey),s=new Map(i.stages.map(c=>[c.stageId,c.name])),a=new Map(i.runs.map(c=>[c.runId,c.name])),l=r.archivedAt!=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:s.get(c.stageId)??c.stageId,capacity:c.capacity,isOpen:c.isOpen}))};return this.print(d,c=>[{section:"offer",item:c.slug,detail:Fe(c.title)},{section:"state",item:c.state,detail:`unit=${c.unit?Fe(c.unit):"\u2014"} sortOrder=${c.sortOrder??"\u2014"} workflow=${c.workflow} applyable=${c.applyable}`},...c.levels.map(u=>({section:"level",item:Fe(u.name),detail:`seq=${u.sequence}${u.gradeLevel!=null?` grade=${u.gradeLevel}`:""}${u.archived?" [archived]":""}`})),...c.runs.map(u=>({section:"run",item:Fe(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:Fe(u.run)} \xD7 ${typeof u.level=="string"?u.level:Fe(u.level)}`,detail:`${u.capacity??"\u221E"}${u.isOpen?" open":" closed"}`}))]),0}},hl=class extends V{static{o(this,"OfferSetCommand")}static paths=[["offer","set"]];static usage=I.Usage({category:"Offer",description:"Update an offer's title and/or pedagogic unit"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e);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 vt(e,n,this.slug),i=[],s;if(this.sortOrder!==void 0&&(s=Number(this.sortOrder),!Number.isFinite(s)||s<0))throw new Error(`offer set: --sort-order must be a non-negative number, got "${this.sortOrder}"`);let a=tr(r.label,{de:this.title,en:this.titleEn},"offer set",HO);if((a!==void 0||s!==void 0)&&(await e.mutation(R.workflow.createManifest,{client:n,slug:this.slug,label:a??r.label,...s!==void 0?{sortOrder:s}:{}}),a!==void 0&&i.push(`title=${Fe(a)}`),s!==void 0&&i.push(`sortOrder=${s}`)),this.programName!==void 0||this.programNameEn!==void 0){let l=tn({de:this.programName,en:this.programNameEn},"offer set",{de:"--program-name",en:"--program-name-en"});await e.mutation(R.programAdmin.updateProgram,{client:n,offerKey:r.offerKey,name:l}),i.push(`programName=${Fe(l)}`)}if(this.unit){let l=await nn(e,n,r.offerKey);await zb(e,n,r.offerKey,Wb(l,this.unit)),i.push(`unit=${this.unit}`)}return this.print({slug:this.slug,changes:i},l=>l.changes.map(d=>({change:d}))),0}},gl=class extends V{static{o(this,"OfferDeleteCommand")}static paths=[["offer","delete"]];static usage=I.Usage({category:"Offer",description:"Soft-delete (archive) an offer \u2014 restorable, never orphans data"});slug=p.String("--slug",{required:!0,description:"Offer slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug);return await e.mutation(R.programAdmin.setManifestArchived,{client:n,offerKey:r.offerKey,archived:!0}),this.print({archived:this.slug},i=>[{key:"archived (soft-deleted)",value:i.archived}]),0}},yl=class extends V{static{o(this,"OfferRestoreCommand")}static paths=[["offer","restore"]];static usage=I.Usage({category:"Offer",description:"Restore a soft-deleted (archived) offer"});slug=p.String("--slug",{required:!0,description:"Offer slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug);return await e.mutation(R.programAdmin.setManifestArchived,{client:n,offerKey:r.offerKey,archived:!1}),this.print({restored:this.slug},i=>[{key:"restored",value:i.restored}]),0}},bl=class extends V{static{o(this,"OfferHardDeleteCommand")}static paths=[["offer","hard-delete"]];static usage=I.Usage({category:"Offer",description:"HARD-delete an offer (manifest + versions + workflow + smartform + program + stages + runs). Irreversible; refuses if any application exists. Prefer 'offer delete' (archive) unless you need an exact offer count."});slug=p.String("--slug",{required:!0,description:"Offer slug"});yes=p.Boolean("--yes",!1,{description:"Confirm the irreversible hard delete"});async execute(){let e=await this.caller(),n=this.requireTenant(e);if(!this.yes)throw new Error(`offer hard-delete: refusing without --yes (irreversible). Re-run with --yes to hard-delete "${this.slug}".`);let r=await vt(e,n,this.slug),i=await e.mutation(R.programAdmin.hardDeleteOffer,{client:n,offerKey:r.offerKey});return this.print(i,s=>[{key:"hard-deleted offer",value:this.slug},{key:"offerKey",value:s.deletedOfferKey},{key:"program",value:s.deletedProgramId??"(none)"},{key:"counts",value:JSON.stringify(s.counts)}]),0}};var QO={de:"--name",en:"--name-en"},wl=class extends V{static{o(this,"OfferRunAddCommand")}static paths=[["offer","run","add"]];static usage=I.Usage({category:"Offer",description:"Add a run (Schuljahr) to an offer"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=eo("capacity",this.capacity),s=tn({de:this.name,en:this.nameEn},"offer run add",QO);return await e.mutation(R.programAdmin.addProgramRun,{client:n,offerKey:r.offerKey,name:s,...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:s},a=>[{key:"run added",value:Fe(a.added)}]),0}},kl=class extends V{static{o(this,"OfferRunSetCommand")}static paths=[["offer","run","set"]];static usage=I.Usage({category:"Offer",description:"Update a run: rename / dates"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey),s=rs(i,this.run),a=i.runs.find(d=>d.runId===s),l=tr(a.name,{de:this.name,en:this.nameEn},"offer run set",QO);return await e.mutation(R.programAdmin.updateProgramRun,{client:n,offerKey:r.offerKey,runId:s,...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}},vl=class extends V{static{o(this,"OfferRunArchiveCommand")}static paths=[["offer","run","archive"]];static usage=I.Usage({category:"Offer",description:"Soft-delete (archive) a run \u2014 retired from the portal, restorable"});slug=p.String("--slug",{required:!0,description:"Offer slug"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey);return await e.mutation(R.programAdmin.updateProgramRun,{client:n,offerKey:r.offerKey,runId:rs(i,this.run),status:"archived"}),this.print({archived:this.run},s=>[{key:"run archived",value:s.archived}]),0}},Sl=class extends V{static{o(this,"OfferRunRestoreCommand")}static paths=[["offer","run","restore"]];static usage=I.Usage({category:"Offer",description:"Restore an archived run"});slug=p.String("--slug",{required:!0,description:"Offer slug"});run=p.String("--run",{required:!0,description:"Run key (bundle.yaml program.runs[].key)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey);return await e.mutation(R.programAdmin.updateProgramRun,{client:n,offerKey:r.offerKey,runId:rs(i,this.run),status:"active"}),this.print({restored:this.run},s=>[{key:"run restored",value:s.restored}]),0}};var YO={de:"--name",en:"--name-en"},xl=class extends V{static{o(this,"OfferLevelAddCommand")}static paths=[["offer","level","add"]];static usage=I.Usage({category:"Offer",description:"Add a level (Klassenstufe) to an offer"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=eo("grade",this.grade),s=tn({de:this.name,en:this.nameEn},"offer level add",YO);return await e.mutation(R.programAdmin.addProgramStage,{client:n,offerKey:r.offerKey,name:s,...i!==void 0?{gradeLevel:i}:{},...this.key!==void 0?{key:this.key}:{}}),this.print({added:s},a=>[{key:"level added",value:Fe(a.added)}]),0}},Al=class extends V{static{o(this,"OfferLevelRenameCommand")}static paths=[["offer","level","rename"]];static usage=I.Usage({category:"Offer",description:"Rename a level / change its grade"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e);if(this.name===void 0&&this.nameEn===void 0&&this.grade===void 0)throw new Error("offer level rename: pass --name/--name-en and/or --grade");let r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey),s=eo("grade",this.grade),a=is(i,this.level),l=i.stages.find(c=>c.stageId===a),d=tr(l.name,{de:this.name,en:this.nameEn},"offer level rename",YO);return await e.mutation(R.programAdmin.updateProgramStage,{client:n,offerKey:r.offerKey,stageId:a,...d!==void 0?{name:d}:{},...s!==void 0?{gradeLevel:s}:{}}),this.print({updated:this.level},c=>[{key:"level updated",value:c.updated}]),0}},El=class extends V{static{o(this,"OfferLevelRemoveCommand")}static paths=[["offer","level","remove"]];static usage=I.Usage({category:"Offer",description:"Soft-delete (archive) a level \u2014 retired from the portal, restorable. Refused while an active application sits on the level"});slug=p.String("--slug",{required:!0,description:"Offer slug"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey),{warnings:s}=await e.mutation(R.programAdmin.updateProgramStage,{client:n,offerKey:r.offerKey,stageId:is(i,this.level),archived:!0});return this.print({removed:this.level,warnings:s},a=>[{key:"level removed (soft)",value:a.removed},...a.warnings.map(l=>({key:"warning",value:l}))]),0}},Rl=class extends V{static{o(this,"OfferLevelRestoreCommand")}static paths=[["offer","level","restore"]];static usage=I.Usage({category:"Offer",description:"Restore an archived level"});slug=p.String("--slug",{required:!0,description:"Offer slug"});level=p.String("--level",{required:!0,description:"Level key (bundle.yaml program.stages[].key)"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey);return await e.mutation(R.programAdmin.updateProgramStage,{client:n,offerKey:r.offerKey,stageId:is(i,this.level),archived:!1}),this.print({restored:this.level},s=>[{key:"level restored",value:s.restored}]),0}},Tl=class extends V{static{o(this,"OfferLevelMoveCommand")}static paths=[["offer","level","move"]];static usage=I.Usage({category:"Offer",description:"Reorder a level among the offer's levels (--before|--after another level)"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e);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 vt(e,n,this.slug),s=await nn(e,n,i.offerKey);if(s.programKey===null)throw new Error("offer level move: the offer has no program yet");let a=s.programKey,l=s.stages.map(f=>({stageId:f.stageId,key:In(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 e.mutation(R.programAdmin.updateProgramStage,{client:n,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 Il=class extends V{static{o(this,"OfferCapacitySetCommand")}static paths=[["offer","capacity","set"]];static usage=I.Usage({category:"Offer",description:"Set seat capacity and/or open-state for one run \xD7 level cell"});slug=p.String("--slug",{required:!0,description:"Offer slug"});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 e=await this.caller(),n=this.requireTenant(e);if(this.open&&this.close)throw new Error("offer capacity set: pass only one of --open / --close");let r=await vt(e,n,this.slug),i=await nn(e,n,r.offerKey),s=this.capacity==="unlimited"?"unlimited":eo("capacity",this.capacity),a=this.open?!0:this.close?!1:void 0;return await e.mutation(R.programAdmin.setRunStageCapacity,{client:n,offerKey:r.offerKey,runId:rs(i,this.run),stageId:is(i,this.level),...s!==void 0?{capacity:s}:{},...a!==void 0?{isOpen:a}:{}}),this.print({run:this.run,level:this.level},l=>[{key:"capacity set",value:`${l.run} \xD7 ${l.level}`}]),0}};var Yb=["self","proxy","both"],Jb=["wet_ink","FES","QES"],Zb=["immediate","batch"],Xb=["arrival","manual"];function ss(t){return t.manifest}o(ss,"manifestOf");function os(t,e,n){if(!e.includes(t))throw new Error(`offer manifest: ${n} must be one of ${e.join("|")} (got "${t}")`)}o(os,"assertEnum");function JO(t,e){let n=t.manifest,r=!1;if(e.applicantMode!==void 0&&(os(e.applicantMode,Yb,"--applicant-mode"),n.applicantMode=e.applicantMode,r=!0),e.signatureLevel!==void 0&&(os(e.signatureLevel,Jb,"--signature-level"),n.signatureLevel=e.signatureLevel,r=!0),e.windowStart!==void 0||e.windowEnd!==void 0){let i=n.bewerbungsfenster??{start:"",end:""};n.bewerbungsfenster={start:e.windowStart??i.start,end:e.windowEnd??i.end},r=!0}if(e.capacity!==void 0){if(!Number.isFinite(e.capacity)||e.capacity<0)throw new Error(`offer manifest: --capacity must be a non-negative number (got "${e.capacity}")`);n.capacity=e.capacity,r=!0}if(e.selectionRelease!==void 0||e.selectionWaitlistOrder!==void 0||e.selectionAutoPromote!==void 0||e.selectionDeadline!==void 0){let i={...n.selection??{}};if(e.selectionRelease!==void 0&&(os(e.selectionRelease,Zb,"--selection-release"),i.releaseStrategy=e.selectionRelease),e.selectionWaitlistOrder!==void 0&&(os(e.selectionWaitlistOrder,Xb,"--selection-waitlist-order"),i.waitlistOrder=e.selectionWaitlistOrder),e.selectionAutoPromote!==void 0&&(i.autoPromoteOnVacancy=e.selectionAutoPromote),e.selectionDeadline!==void 0&&(e.selectionDeadline===""?delete i.decisionDeadline:i.decisionDeadline=e.selectionDeadline),i.releaseStrategy===void 0||i.waitlistOrder===void 0)throw new Error("offer manifest: selection needs --selection-release and --selection-waitlist-order (set both the first time)");i.autoPromoteOnVacancy===void 0&&(i.autoPromoteOnVacancy=!1),n.selection=i,r=!0}if(!r)throw new Error("offer manifest set: nothing to change \u2014 pass at least one --\u2026 flag")}o(JO,"setManifestMeta");function ZO(t,e){let n=ss(t),r=n.roleInstances??(n.roleInstances=[]);if(r.some(i=>i.key===e.key))throw new Error(`offer role add: roleInstance "${e.key}" already exists`);if(!e.customRoleId)throw new Error("offer role add: --custom-role-id is required (the tenant custom-role this slot binds)");r.push({key:e.key,label:Je(e.label,e.labelEn,`offer role add: roleInstance "${e.key}"`),customRoleId:e.customRoleId,cardinality:{min:e.min??1,max:e.max??1},required:e.required??!0,flags:{legallyRelevant:e.legallyRelevant??!1,canSignContract:e.canSignContract??!1,requiresEvidence:e.requiresEvidence??!1},attributes:[]})}o(ZO,"addRole");function XO(t,e){let n=(ss(t).roleInstances??[]).find(r=>r.key===e.key);if(!n)throw new Error(`offer role set: roleInstance "${e.key}" not found`);if(at(n,"label",{de:e.label,en:e.labelEn},`offer role set: roleInstance "${e.key}"`),e.customRoleId!==void 0){if(e.customRoleId==="")throw new Error("offer role set: --custom-role-id cannot be empty");n.customRoleId=e.customRoleId}e.min!==void 0&&(n.cardinality.min=e.min),e.max!==void 0&&(n.cardinality.max=e.max),e.required!==void 0&&(n.required=e.required),e.legallyRelevant!==void 0&&(n.flags.legallyRelevant=e.legallyRelevant),e.canSignContract!==void 0&&(n.flags.canSignContract=e.canSignContract),e.requiresEvidence!==void 0&&(n.flags.requiresEvidence=e.requiresEvidence)}o(XO,"setRole");function eC(t,e){let n=ss(t),r=n.roleInstances??[],i=r.filter(s=>s.key!==e);if(i.length===r.length)throw new Error(`offer role rm: roleInstance "${e}" not found`);n.roleInstances=i}o(eC,"removeRole");function gf(t){return(ss(t).roleInstances??[]).map(e=>({key:e.key,label:e.label,customRoleId:e.customRoleId,cardinality:`${e.cardinality.min}..${e.cardinality.max}`,required:e.required,flags:[e.flags.legallyRelevant?"legallyRelevant":"",e.flags.canSignContract?"canSignContract":"",e.flags.requiresEvidence?"requiresEvidence":""].filter(Boolean).join(",")}))}o(gf,"listRoles");function tC(t,e){let n=ss(t),r=n.leistungen??(n.leistungen=[]);if(r.some(i=>i.key===e.key))throw new Error(`offer leistung add: leistung "${e.key}" already exists`);r.push({key:e.key,label:Je(e.label,e.labelEn,`offer leistung add: leistung "${e.key}"`),selectableByApplicant:e.selectableByApplicant??!0,assignedByProvider:e.assignedByProvider??!1})}o(tC,"addLeistung");function nC(t,e){let n=ss(t),r=n.leistungen??[],i=r.filter(s=>s.key!==e);if(i.length===r.length)throw new Error(`offer leistung rm: leistung "${e}" not found`);n.leistungen=i}o(nC,"removeLeistung");var $l=class extends V{static{o(this,"OfferUnitCreateCommand")}static paths=[["offer","unit","create"]];static usage=I.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): ${Hb.join("|")}`});parent=p.String("--parent",{description:"Parent unit (nest under it) \u2014 its config key, or URL slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=this.kind??"school";os(r,Hb,"--kind");let i;this.parent&&(i=(await hf(e,n,this.parent,"offer unit create: parent unit")).id);let{id:s}=await e.mutation(R.masterData.createUnit,{client:n,name:tn({de:this.name,en:this.nameEn},"offer unit create",{de:"--name",en:"--name-en"}),kind:r,...i?{parentUnitId:i}:{}}),{pedagogyUnitId:a,created:l}=await e.mutation(R.programAdmin.ensurePedagogyUnit,{client:n,unitId:s});return this.print({unitId:s,pedagogyUnitId:a,created:l},d=>[{key:"unit created",value:d.unitId},{key:"pedagogyUnit",value:d.pedagogyUnitId},{key:"applyable",value:"yes"}]),0}},_l=class extends V{static{o(this,"OfferUnitEnsurePedagogyCommand")}static paths=[["offer","unit","ensure-pedagogy"]];static usage=I.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 config key, or URL slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await hf(e,n,this.unit,"offer unit ensure-pedagogy"),{pedagogyUnitId:i,created:s}=await e.mutation(R.programAdmin.ensurePedagogyUnit,{client:n,unitId:r.id});return this.print({pedagogyUnitId:i,created:s},a=>[{key:"pedagogyUnit",value:a.pedagogyUnitId},{key:s?"created":"already a pedagogy unit",value:"yes"}]),0}},Ol=class extends V{static{o(this,"OfferUnitDeleteCommand")}static paths=[["offer","unit","delete"]];static usage=I.Usage({category:"Offer",description:"Delete a unit + its pedagogy/profile/location bridges. Fail-loud if it still has bound programs (offers), child units, or members \u2014 re-home those first."});unit=p.String("--unit",{required:!0,description:"Unit to delete \u2014 its config key, or URL slug"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await hf(e,n,this.unit,"offer unit delete"),i=await e.mutation(R.masterData.deleteUnit,{client:n,unitId:r.id});return this.print(i,s=>[{key:"unit deleted",value:Fe(s.name)},{key:"pedagogy bridges",value:String(s.pedagogy)},{key:"profiles",value:String(s.profiles)},{key:"locations",value:String(s.locations)}]),0}};var rC=[sl,ol,al,ll,dl,cl,ul,fl,pl,ml,hl,gl,yl,bl,wl,kl,vl,Sl,xl,Al,Tl,El,Rl,Il,$l,_l,Ol];import{existsSync as _j,unlinkSync as Oj}from"node:fs";import Cj from"node:path";var Dr=["string","boolean","date","enum","email","tel","address","docRef"],as=Object.keys(Nb),Cl=["person","organization","relationship","fieldMap"],bi=["auto-on-any-write","auto-on-required-complete","workflow-explicit"],ls=["fresh","keyed","manual"];function Pl(t,e,n,r){if(t===void 0||t===""){if(e!==void 0&&e!=="")throw new Error(`${n}: ${r}-en needs ${r} too`);return}return Je(t,e,n,r)}o(Pl,"optionalLocalizedText");function Vt(t,e){if(!(t===void 0||t===""))try{Ft(t)}catch(n){throw new Error(`offer form: ${e} is not a valid expression: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}o(Vt,"assertExpression");function Nl(t){return Object.keys(t.smartforms??{})}o(Nl,"carriedFormSlugs");function ew(t){let n=t.workflow?.graph?.nodes??[],r=[];for(let i of n){if(i.type!=="form")continue;let s=i.inputs?.smartForm;s?.kind==="literal"&&typeof s.value=="string"&&s.value&&r.push(s.value)}return r}o(ew,"boundFormSlugs");function yf(t,e){let n=Nl(t);if(e){if(!n.includes(e))throw new Error(`offer form: no smartform "${e}" in this bundle (have: ${n.join(", ")||"none"})`);return e}if(n.length===0)throw new Error("offer form: bundle carries no smartforms \u2014 run `offer form add` first");if(n.length>1)throw new Error(`offer form: bundle carries ${n.length} smartforms \u2014 pass --form <key> (one of: ${n.join(", ")})`);return n[0]}o(yf,"resolveFormSlug");function bf(t,e){let n=t.smartforms?.[e];if(!n)throw new Error(`offer form: smartform "${e}" not found in bundle`);return n}o(bf,"getForm");function Bn(t){let e=[],n=o(r=>{e.push(r),r.subsections?.forEach(i=>n(i))},"visit");return t.sections.forEach(n),e}o(Bn,"walkSections");function Cn(t,e){return Bn(t).find(n=>n.id===e)}o(Cn,"findSection");function ds(t,e){for(let n of Bn(t)){let r=n.fields.findIndex(i=>i.key===e);if(r>=0)return{section:n,field:n.fields[r],index:r}}}o(ds,"findField");function to(t){let e=new Set;for(let n of Bn(t))n.fields.forEach(r=>e.add(r.key)),n.groups?.forEach(r=>r.fields.forEach(i=>e.add(i.key))),n.repeated?.forEach(r=>r.itemTemplate.forEach(i=>e.add(i.key))),n.computed?.forEach(r=>e.add(r.key));return e}o(to,"allFieldKeys");function Ej(t){let{key:e}=t,n=Je(t.label,t.labelEn,"offer form add"),r={id:zo("section.allgemein"),label:{de:"Allgemein",en:"General"},fields:[]},i={id:pr("standard"),label:{de:"Standard",en:"Standard"},when:"true",output:{includeForm:!0}};return{id:e,label:n,sections:[r],effects:[],outcomeIds:[pr("standard")],outcomes:[i]}}o(Ej,"buildSkeletonSmartForm");function wf(t,e){let{key:n,label:r}=e;if(Nl(t).includes(n))throw new Error(`offer form add: smartform "${n}" already exists in this bundle`);let i=Ej({key:n,label:r,...e.labelEn?{labelEn:e.labelEn}:{}});t.smartforms={...t.smartforms??{},[n]:i},t.index.smartforms={...t.index.smartforms??{},[n]:{outcomeFnRef:"admission.generic"}}}o(wf,"addForm");function iC(t,e){if(!Nl(t).includes(e))throw new Error(`offer form rm: smartform "${e}" not found in bundle`);if(ew(t).includes(e))throw new Error(`offer form rm: smartform "${e}" is still bound by a form node \u2014 remove the form node first (offer workflow node rm), then the form`);return delete t.smartforms[e],t.index.smartforms&&delete t.index.smartforms[e],e}o(iC,"removeForm");function oC(t,e){let n=bf(t,e.slug);if(e.label===void 0&&e.labelEn===void 0)throw new Error("offer form set: nothing to change \u2014 pass --label/--label-en");if(e.label==="")throw new Error("offer form set: --label cannot be empty");at(n,"label",{de:e.label,en:e.labelEn},"offer form set")}o(oC,"setForm");function sC(t,e){if(Cn(t,e.id))throw new Error(`offer form section add: section "${e.id}" already exists`);Vt(e.visibleIf,`section "${e.id}" visibleIf`);let n={id:zo(e.id),label:Je(e.label,e.labelEn,`offer form section add: section "${e.id}"`),fields:[],...e.visibleIf?{visibleIf:e.visibleIf}:{}};if(e.parentId){let r=Cn(t,e.parentId);if(!r)throw new Error(`offer form section add: parent section "${e.parentId}" not found`);r.subsections=[...r.subsections??[],n]}else t.sections.push(n)}o(sC,"addSection");function aC(t,e){let n=Cn(t,e.id);if(!n)throw new Error(`offer form section set: section "${e.id}" not found`);if(Vt(e.visibleIf,`section "${e.id}" visibleIf`),at(n,"label",{de:e.label,en:e.labelEn},`offer form section set: section "${e.id}"`),e.visibleIf!==void 0&&(e.visibleIf===""?delete n.visibleIf:n.visibleIf=e.visibleIf),e.visibleTo!==void 0){let r=n;if(e.visibleTo==="")delete r.visibleTo;else{let i=e.visibleTo.split(",").map(s=>s.trim());if(i.some(s=>s===""))throw new Error(`offer form section set: --visible-to "${e.visibleTo}" has an empty key`);r.visibleTo=i}}if(e.parentId!==void 0&&Rj(t,e.id,e.parentId),e.label===void 0&&e.labelEn===void 0&&e.visibleIf===void 0&&e.visibleTo===void 0&&e.parentId===void 0)throw new Error("offer form section set: nothing to change \u2014 pass --label/--label-en/--visible-if/--visible-to/--parent")}o(aC,"setSection");function lC(t,e){return t.id===e?!0:t.subsections?.some(n=>lC(n,e))??!1}o(lC,"isSelfOrDescendant");function dC(t,e){let n=o(i=>{let s=i.findIndex(a=>a.id===e);if(s>=0)return i.splice(s,1)[0];for(let a of i)if(a.subsections){let l=n(a.subsections);if(l)return l}},"removeFrom"),r=n(t.sections);if(!r)throw new Error(`offer form: section "${e}" not found`);return r}o(dC,"detachSection");function Rj(t,e,n){let r=Cn(t,e);if(!r)throw new Error(`offer form section set: section "${e}" not found`);if(n!==""){if(!Cn(t,n))throw new Error(`offer form section set: parent section "${n}" not found`);if(lC(r,n))throw new Error(`offer form section set: cannot reparent "${e}" under "${n}" \u2014 that would create a cycle`)}let i=dC(t,e);if(n==="")t.sections.push(i);else{let s=Cn(t,n);s.subsections=[...s.subsections??[],i]}}o(Rj,"reparentSection");function cC(t,e){let n=dC(t,e),r=[],i=o(s=>{s.fields.forEach(a=>r.push(a.key)),s.subsections?.forEach(a=>i(a))},"collect");return i(n),r}o(cC,"removeSection");function uC(t,e,n,r,i){if(t==="enum"){let s=[e?"--enum":null,n?"--enum-ref":null,r?"--enum-list-key":null].filter(a=>a!==null);if(s.length>1)throw new Error(`${i}: pass only one of ${s.join(", ")} (enum options come from exactly one source)`);if(n&&!as.includes(n))throw new Error(`${i}: unknown --enum-ref "${n}" (one of: ${as.join(", ")})`)}else if(e||n||r)throw new Error(`${i}: --enum/--enum-ref/--enum-list-key only valid on an enum field`)}o(uC,"validateEnumChoice");function Tj(t,e,n){if(!(t===void 0&&e===void 0&&n===void 0))return{...t&&t.length?{mimeType:t}:{},...e!==void 0?{maxSize:e}:{},...n!==void 0?{multiple:n}:{}}}o(Tj,"buildDocRef");function fC(t,e,n,r){let i=e===void 0&&n===void 0?{de:"Erkl\xE4rung",en:"Declaration"}:Je(e??"",n,r,"--declaration-label");return{url:t,filename:i.de,mimeType:"text/html",label:i,renderAs:"inlineLink"}}o(fC,"declarationAttachment");function pC(t,e){if(t!=="yesNo")throw new Error(`${e}: --presentation must be "yesNo" (or "" to clear), got "${t}"`)}o(pC,"validatePresentation");function mC(t,e){if(!Dr.includes(e.type))throw new Error(`offer form field add: unknown --type "${e.type}" (one of: ${Dr.join(", ")})`);let n=Cn(t,e.section);if(!n)throw new Error(`offer form field add: section "${e.section}" not found`);if(to(t).has(e.key))throw new Error(`offer form field add: field key "${e.key}" already exists in this form`);if(e.type==="enum"&&!e.enum&&!e.enumRef&&!e.enumListKey)throw new Error(`offer form field add: enum field "${e.key}" needs --enum a,b,c, --enum-ref <catalog>, or --enum-list-key <list>`);if(e.multiple&&e.type!=="enum")throw new Error("offer form field add: --multiple only valid on an enum field");uC(e.type,e.enum,e.enumRef,e.enumListKey,"offer form field add"),e.presentation!==void 0&&pC(e.presentation,"offer form field add");let r=Tj(e.docMime,e.docMaxSize,e.docMultiple);if(r&&e.type!=="docRef")throw new Error("offer form field add: --doc-mime/--doc-max-size/--doc-multiple only valid with --type docRef");let i=`offer form field add: field "${e.key}"`,s=e.label===void 0&&e.labelEn===void 0?{de:e.key,en:e.key}:Je(e.label??"",e.labelEn,i),a=Pl(e.placeholder,e.placeholderEn,i,"--placeholder"),l=Pl(e.help,e.helpEn,i,"--help-text"),d={key:Bt(e.key),label:s,kind:e.kind??"control",type:e.type,...e.required?{required:!0}:{},...e.bucket?{bucket:e.bucket}:{},...e.enum?{enumOptions:e.enum}:{},...e.enumRef?{enumRef:e.enumRef}:{},...e.enumListKey?{enumListKey:e.enumListKey}:{},...e.multiple?{multiple:!0}:{},...e.presentation?{presentation:e.presentation}:{},...a?{placeholder:a}:{},...l?{helpText:l}:{},...r?{docRefConstraints:r}:{},...e.consentTextKey?{consentTextKey:e.consentTextKey}:{},...e.consentVersion?{consentVersion:e.consentVersion}:{},...e.declarationUrl?{attachments:[fC(e.declarationUrl,e.declarationLabel,e.declarationLabelEn,`${i} declaration`)]}:{}};n.fields.push(d)}o(mC,"addField");function hC(t,e){let n=ds(t,e.key);if(!n)throw new Error(`offer form field set: field "${e.key}" not found`);Vt(e.visibleIf,`field "${e.key}" visibleIf`),Vt(e.requiredIf,`field "${e.key}" requiredIf`),Vt(e.defaultValue,`field "${e.key}" defaultValue`),Vt(e.disabledIf,`field "${e.key}" disabledIf`);let r=n.field,i=String(r.type),s=`offer form field set: field "${e.key}"`;at(r,"label",{de:e.label,en:e.labelEn},s),at(r,"placeholder",{de:e.placeholder,en:e.placeholderEn,clearable:!0},`${s} placeholder`),at(r,"helpText",{de:e.helpText,en:e.helpTextEn,clearable:!0},`${s} help text`),e.required!==void 0&&(r.required=e.required);let a=o((l,d)=>{let c=e[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"),(e.enum!==void 0||e.enumRef!==void 0||e.enumListKey!==void 0)&&(uC(i,e.enum,e.enumRef,e.enumListKey,"offer form field set"),e.enum!==void 0&&(e.enum.length?r.enumOptions=e.enum:delete r.enumOptions,delete r.enumRef,delete r.enumListKey),e.enumRef!==void 0&&(e.enumRef===""?delete r.enumRef:(r.enumRef=e.enumRef,delete r.enumOptions,delete r.enumListKey)),e.enumListKey!==void 0&&(e.enumListKey===""?delete r.enumListKey:(r.enumListKey=e.enumListKey,delete r.enumOptions,delete r.enumRef))),e.multiple!==void 0){if(i!=="enum")throw new Error("offer form field set: --multiple only valid on an enum field");e.multiple?r.multiple=!0:delete r.multiple}if(e.presentation!==void 0&&(e.presentation===""?delete r.presentation:(pC(e.presentation,"offer form field set"),r.presentation=e.presentation)),e.requiredFor!==void 0&&(e.requiredFor.length?r.requiredFor=e.requiredFor.map(l=>pr(l)):delete r.requiredFor),e.docMime!==void 0||e.docMaxSize!==void 0||e.docMultiple!==void 0){if(i!=="docRef")throw new Error("offer form field set: --doc-mime/--doc-max-size/--doc-multiple only valid on a docRef field");let d={...r.docRefConstraints??{}};e.docMime!==void 0&&(e.docMime.length?d.mimeType=e.docMime:delete d.mimeType),e.docMaxSize!==void 0&&(d.maxSize=e.docMaxSize),e.docMultiple!==void 0&&(d.multiple=e.docMultiple),Object.keys(d).length?r.docRefConstraints=d:delete r.docRefConstraints}if(e.declarationUrl!==void 0){let l=Array.isArray(r.attachments)?r.attachments:[],d=l.filter(c=>c.renderAs!=="inlineLink");if(e.declarationUrl==="")d.length?r.attachments=d:delete r.attachments;else{let c=l.find(u=>u.renderAs==="inlineLink");if(c===void 0)d.push(fC(e.declarationUrl,e.declarationLabel,e.declarationLabelEn,`${s} declaration`));else{let u={...c,url:e.declarationUrl};at(u,"label",{de:e.declarationLabel,en:e.declarationLabelEn},`offer form field set: field "${e.key}" declaration`),u.filename=u.label.de,d.push(u)}r.attachments=d}}}o(hC,"setField");function gC(t,e,n,r,i){if(n.kind==="top"){t.unshift(e);return}if(n.kind==="bottom"){t.push(e);return}let s=t.findIndex(a=>r(a)===n.anchor);if(s<0)throw new Error(`${i}: anchor "${n.anchor}" not found among siblings`);t.splice(n.kind==="before"?s:s+1,0,e)}o(gC,"spliceAt");function yC(t,e,n,r){let i=ds(t,e);if(!i)throw new Error(`offer form field move: field "${e}" not found`);if((n.kind==="before"||n.kind==="after")&&n.anchor===e)throw new Error("offer form field move: --before/--after anchor cannot be the field itself");let s=r===void 0?i.section:Cn(t,r);if(!s)throw new Error(`offer form field move: section "${r}" not found`);let a=s.fields;if((n.kind==="before"||n.kind==="after")&&!a.some(d=>d.key===n.anchor))throw new Error(`offer form field move: anchor "${n.anchor}" not found in section "${s.id}"`);let[l]=i.section.fields.splice(i.index,1);gC(a,l,n,d=>d.key,"offer form field move")}o(yC,"moveField");function bC(t,e,n){if((n.kind==="before"||n.kind==="after")&&n.anchor===e)throw new Error("offer form section move: --before/--after anchor cannot be the section itself");let r=o(l=>{if(l.some(d=>d.id===e))return l;for(let d of l)if(d.subsections){let c=r(d.subsections);if(c)return c}},"findContainer"),i=r(t.sections);if(!i)throw new Error(`offer form section move: section "${e}" not found`);let s=i.findIndex(l=>l.id===e),[a]=i.splice(s,1);gC(i,a,n,l=>l.id,"offer form section move")}o(bC,"moveSection");function wC(t,e){let n=ds(t,e);if(!n)throw new Error(`offer form field rm: field "${e}" not found`);return n.section.fields.splice(n.index,1),e}o(wC,"removeField");function kC(t,e){let n=ds(t,e.key);if(!n)throw new Error(`offer form field attach: field "${e.key}" not found`);if(!$c(e.fileKey))throw new Error(`offer form field attach: --file-key "${e.fileKey}" is not a valid key (a-z, 0-9, "-")`);let r=e.renderAs??"download";if(r==="inlineLink"&&!e.label)throw new Error("offer form field attach: --render inlineLink needs --label (the linked phrase in the field label)");let i=n.field,s=(i.attachments??[]).filter(a=>a.fileKey!==e.fileKey);s.push({fileKey:e.fileKey,...r==="inlineLink"?{renderAs:r}:{},...e.label?{label:Je(e.label,e.labelEn,`offer form field attach: field "${e.key}"`)}:{}}),i.attachments=s}o(kC,"attachFile");function vC(t,e,n){let r=ds(t,e);if(!r)throw new Error(`offer form field detach: field "${e}" not found`);let i=r.field,s=(i.attachments??[]).filter(a=>a.fileKey!==n);if(s.length===(i.attachments??[]).length)throw new Error(`offer form field detach: field "${e}" does not attach file "${n}"`);s.length>0?i.attachments=s:delete i.attachments}o(vC,"detachFile");function SC(t,e){let n=t,r=n.outcomes??(n.outcomes=[]);if(r.some(a=>a.id===e.id))throw new Error(`offer form outcome add: outcome "${e.id}" already exists`);Vt(e.when,`outcome "${e.id}" when`);let i=e.label===void 0&&e.labelEn===void 0?{de:e.id,en:e.id}:Je(e.label??"",e.labelEn,`offer form outcome add: outcome "${e.id}"`),s={id:pr(e.id),label:i,when:e.when,...e.blocking?{blocking:!0}:{},output:{...e.fields&&e.fields.length?{fields:e.fields.map(a=>({path:Bt(a)}))}:{},...e.effectRefs&&e.effectRefs.length?{effectRefs:e.effectRefs.map(a=>({effect:a.effect,as:a.as}))}:{},includeForm:!0}};r.push(s),n.outcomeIds.push(e.id)}o(SC,"addOutcome");function xC(t,e){let n=Ij(t,e.id);if(!n)throw new Error(`offer form outcome set: outcome "${e.id}" not found`);if(Vt(e.when,`outcome "${e.id}" when`),e.when!==void 0&&(n.when=e.when),e.blocking!==void 0&&(n.blocking=e.blocking),at(n,"label",{de:e.label,en:e.labelEn},`offer form outcome set: outcome "${e.id}"`),e.fields!==void 0||e.effectRefs!==void 0){let r=n.output??{includeForm:!0};e.fields!==void 0&&(e.fields.length?r.fields=e.fields.map(i=>({path:Bt(i)})):delete r.fields),e.effectRefs!==void 0&&(e.effectRefs.length?r.effectRefs=e.effectRefs.map(i=>({effect:i.effect,as:i.as})):delete r.effectRefs),n.output=r}}o(xC,"setOutcome");function AC(t,e){let n=t,r=n.outcomes??[];if(!r.some(i=>i.id===e))throw new Error(`offer form outcome rm: outcome "${e}" not found`);n.outcomes=r.filter(i=>i.id!==e),n.outcomeIds=n.outcomeIds.filter(i=>i!==e)}o(AC,"removeOutcome");function nw(t,e){return t.effects.find(n=>n.id===e)}o(nw,"findEffect");function Ij(t,e){return t.outcomes?.find(n=>n.id===e)}o(Ij,"findOutcome");function cs(t){return t.startsWith("$")?t:`$${t}`}o(cs,"asRef");function tw(t,e){if(t!==void 0){if(!ls.includes(t))throw new Error(`offer form effect: unknown --identity "${t}" (one of: ${ls.join(", ")})`);if(t==="keyed"){if(!e||e.length===0)throw new Error("offer form effect: --identity keyed needs --identity-key-from <fieldKeys>");return{strategy:"keyed",keyFrom:e}}return{strategy:t}}}o(tw,"buildIdentity");function EC(t,e){let n=t.effects;if(nw(t,e.id))throw new Error(`offer form effect add: effect "${e.id}" already exists`);Vt(e.when,`effect "${e.id}" when`);let r={id:F$(e.id),...e.when?{when:e.when}:{}},i;switch(e.kind){case"person":{if(!e.bucket)throw new Error("offer form effect add: person needs --bucket");let s=e.policy??"auto-on-required-complete";if(!bi.includes(s))throw new Error(`offer form effect add: unknown --policy "${s}" (one of: ${bi.join(", ")})`);let a=tw(e.identity,e.identityKeyFrom);i={...r,kind:"person",bucket:e.bucket,policy:s,...a?{identity:a}:{},...e.nameFrom?.length?{nameFrom:e.nameFrom.map(l=>Bt(l))}:{},...e.role?{role:e.role}:{}};break}case"organization":{if(!e.orgKind)throw new Error("offer form effect add: organization needs --org-kind");let s=tw(e.identity,e.identityKeyFrom);i={...r,kind:"organization",orgKind:e.orgKind,...s?{identity:s}:{},...e.nameFrom?.length?{nameFrom:e.nameFrom.map(a=>Bt(a))}:{},...e.role?{role:e.role}:{}};break}case"relationship":{if(!e.from||!e.to||!e.relKind)throw new Error("offer form effect add: relationship needs --from, --to and --rel-kind");i={...r,kind:"relationship",from:cs(e.from),to:cs(e.to),relKind:e.relKind};break}case"fieldMap":{if(!e.target||!e.mappings||e.mappings.length===0)throw new Error("offer form effect add: fieldMap needs --target and --map from:to,\u2026");i={...r,kind:"fieldMap",target:cs(e.target),mappings:e.mappings};break}default:throw new Error(`offer form effect add: unknown --kind "${e.kind}" (one of: ${Cl.join(", ")})`)}n.push(i)}o(EC,"addEffect");function Vn(t,e,n,r){if(!e.includes(t))throw new Error(`offer form effect set: ${n} is only valid on a ${r} effect (this effect is "${t}")`)}o(Vn,"assertEffectKind");function RC(t,e){let n=nw(t,e.id);if(!n)throw new Error(`offer form effect set: effect "${e.id}" not found`);let r=String(n.kind);if(Vt(e.when,`effect "${e.id}" when`),e.when!==void 0&&(e.when===""?delete n.when:n.when=e.when),e.role!==void 0&&(Vn(r,["person","organization"],"--role","person/organization"),e.role===""?delete n.role:n.role=e.role),e.policy!==void 0){if(Vn(r,["person"],"--policy","person"),!bi.includes(e.policy))throw new Error(`offer form effect set: unknown --policy "${e.policy}" (one of: ${bi.join(", ")})`);n.policy=e.policy}if(e.nameFrom!==void 0&&(Vn(r,["person","organization"],"--name-from","person/organization"),n.nameFrom=e.nameFrom.map(i=>Bt(i))),e.bucket!==void 0&&(Vn(r,["person"],"--bucket","person"),n.bucket=e.bucket),e.identity!==void 0||e.identityKeyFrom!==void 0){Vn(r,["person","organization"],"--identity","person/organization");let i=e.identity??n.identity?.strategy;n.identity=tw(i,e.identityKeyFrom)}if(e.orgKind!==void 0&&(Vn(r,["organization"],"--org-kind","organization"),n.orgKind=e.orgKind),e.from!==void 0&&(Vn(r,["relationship"],"--from","relationship"),n.from=cs(e.from)),e.to!==void 0&&(Vn(r,["relationship"],"--to","relationship"),n.to=cs(e.to)),e.relKind!==void 0&&(Vn(r,["relationship"],"--rel-kind","relationship"),n.relKind=e.relKind),e.target!==void 0&&(Vn(r,["fieldMap"],"--target","fieldMap"),n.target=cs(e.target)),e.mappings!==void 0){if(Vn(r,["fieldMap"],"--map","fieldMap"),e.mappings.length===0)throw new Error("offer form effect set: --map cannot be empty for a fieldMap");n.mappings=e.mappings}}o(RC,"setEffect");function TC(t,e){let n=t;if(!nw(t,e))throw new Error(`offer form effect rm: effect "${e}" not found`);n.effects=n.effects.filter(r=>r.id!==e)}o(TC,"removeEffect");function IC(t,e){let n=Cn(t,e.section);if(!n)throw new Error(`offer form repeated add: section "${e.section}" not found`);let r=to(t);if(r.has(e.key))throw new Error(`offer form repeated add: key "${e.key}" already exists in this form`);if(e.itemFields.length===0)throw new Error("offer form repeated add: needs --item-fields key:type,\u2026");for(let l of e.itemFields){if(!Dr.includes(l.type))throw new Error(`offer form repeated add: item field "${l.key}" has unknown type "${l.type}" (one of: ${Dr.join(", ")})`);if(r.has(l.key))throw new Error(`offer form repeated add: item field key "${l.key}" already exists in this form`)}Vt(e.itemVisibleIf,`repeated "${e.key}" itemVisibleIf`);let i=new Set(e.itemFields.map(l=>l.key));for(let l of e.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 s=e.label===void 0&&e.labelEn===void 0?{de:e.key,en:e.key}:Je(e.label??"",e.labelEn,`offer form repeated add: repeated "${e.key}"`),a={key:Bt(e.key),label:s,itemTemplate:e.itemFields.map(l=>({key:Bt(l.key),label:{de:l.key,en:l.key},kind:"control",type:l.type})),...e.min!==void 0?{minItems:e.min}:{},...e.max!==void 0?{maxItems:e.max}:{},...e.itemVisibleIf?{itemVisibleIf:e.itemVisibleIf}:{},...e.uniqueBy?.length?{uniqueBy:e.uniqueBy}:{}};n.repeated=[...n.repeated??[],a]}o(IC,"addRepeated");function $C(t,e){for(let n of Bn(t)){let r=(n.repeated??[]).findIndex(i=>i.key===e);if(r>=0)return{section:n,repeated:n.repeated[r],index:r}}}o($C,"findRepeated");function _C(t,e){let n=$C(t,e.key);if(!n)throw new Error(`offer form repeated set: repeated field "${e.key}" not found`);Vt(e.itemVisibleIf,`repeated "${e.key}" itemVisibleIf`);let r=n.repeated;if(at(r,"label",{de:e.label,en:e.labelEn},`offer form repeated set: repeated field "${e.key}"`),e.min!==void 0&&(e.min<0?delete r.minItems:r.minItems=e.min),e.max!==void 0&&(e.max<0?delete r.maxItems:r.maxItems=e.max),e.itemVisibleIf!==void 0&&(e.itemVisibleIf===""?delete r.itemVisibleIf:r.itemVisibleIf=e.itemVisibleIf),e.uniqueBy!==void 0)if(e.uniqueBy.length){let i=new Set(n.repeated.itemTemplate.map(s=>s.key));for(let s of e.uniqueBy)if(!i.has(s))throw new Error(`offer form repeated set: --unique-by "${s}" is not an item field (${[...i].join(", ")})`);r.uniqueBy=e.uniqueBy}else delete r.uniqueBy}o(_C,"setRepeated");function OC(t,e){let n=$C(t,e);if(!n)throw new Error(`offer form repeated rm: repeated field "${e}" not found`);return n.section.repeated.splice(n.index,1),e}o(OC,"removeRepeated");function CC(t,e){let n=Cn(t,e.section);if(!n)throw new Error(`offer form computed add: section "${e.section}" not found`);if(to(t).has(e.key))throw new Error(`offer form computed add: key "${e.key}" already exists in this form`);Vt(e.expression,`computed "${e.key}" expression`);let r={key:Bt(e.key),expression:e.expression};n.computed=[...n.computed??[],r]}o(CC,"addComputed");function PC(t,e){for(let n of Bn(t)){let r=(n.computed??[]).findIndex(i=>i.key===e);if(r>=0)return{section:n,index:r}}}o(PC,"findComputed");function NC(t,e){let n=PC(t,e.key);if(!n)throw new Error(`offer form computed set: computed field "${e.key}" not found`);Vt(e.expression,`computed "${e.key}" expression`),n.section.computed[n.index].expression=e.expression}o(NC,"setComputed");function DC(t,e){let n=PC(t,e);if(!n)throw new Error(`offer form computed rm: computed field "${e}" not found`);return n.section.computed.splice(n.index,1),e}o(DC,"removeComputed");function FC(t){let e=new Set(ew(t));return Nl(t).map(n=>{let r=bf(t,n),i=Bn(r);return{slug:n,label:r.label,sections:i.length,fields:[...to(r)].length,outcomes:(r.outcomes??[]).length,effects:(r.effects??[]).length,boundByNode:e.has(n)}})}o(FC,"listForms");function LC(t,e){let n=bf(t,e),r=[];for(let i of Bn(n)){for(let s of i.fields){let a=[],l=s;for(let d of["visibleIf","requiredIf","disabledIf","defaultValue","requiredFor","enumRef","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:s.key,type:s.type,required:s.required===!0,flags:a.join(",")})}for(let s of i.repeated??[])r.push({section:i.id,key:s.key,type:"repeated",required:(s.minItems??0)>0,flags:[`items:${s.itemTemplate.length}`,s.uniqueBy?.length?"uniqueBy":"",s.itemVisibleIf?"itemVisibleIf":""].filter(Boolean).join(",")});for(let s of i.computed??[])r.push({section:i.id,key:s.key,type:"computed",required:!1,flags:"expr"})}return{slug:e,label:n.label,fields:r,outcomes:(n.outcomes??[]).map(i=>({id:i.id,when:i.when})),effects:(n.effects??[]).map(i=>({id:i.id,kind:i.kind}))}}o(LC,"showForm");function Dl(t){return t.testScenarios??[]}o(Dl,"scenarios");function kf(t,e,n){let r=Dl(t).find(i=>i.id===e);if(!r){let i=Dl(t).map(s=>s.id);throw new Error(`${n}: no scenario "${e}" (have: ${i.join(", ")||"none"})`)}return r}o(kf,"findScenario");function $j(t){let e=new Map;for(let n of Bn(t)){for(let r of n.fields)e.set(r.key,r);for(let r of n.groups??[])for(let i of r.fields)e.set(i.key,i)}return e}o($j,"prefillableFields");function rw(t,e,n){let r=$j(t),i={};for(let s of e){let a=s.indexOf("=");if(a<=0)throw new Error(`${n}: --prefill "${s}" must be key=value`);let l=s.slice(0,a),d=s.slice(a+1),c=r.get(l);if(c===void 0)throw new Error(`${n}: --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(`${n}: --prefill ${l} is a boolean field \u2014 use true or false`);i[l]=d==="true";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(`${n}: --prefill ${l} is an address \u2014 pass it with --prefill-json`);case"docRef":throw new Error(`${n}: --prefill ${l} is a file field \u2014 test mode stubs files itself, they are never prefilled`);default:i[l]=d}}return i}o(rw,"parsePrefillPairs");function us(t,e,n){let r;try{r=JSON.parse(t)}catch(i){throw new Error(`${n}: ${e} 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(`${n}: ${e} must be a JSON object`);return r}o(us,"parseJsonObject");function MC(t,e){let n="offer form scenario add";if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e.id))throw new Error(`${n}: --id "${e.id}" must be a kebab-case key (e.g. standard, mit-geschwistern)`);if(Dl(t).some(d=>d.id===e.id))throw new Error(`${n}: scenario "${e.id}" already exists`);if(e.label.trim()==="")throw new Error(`${n}: --label cannot be empty`);let r=Je(e.label,e.labelEn,n),i=Pl(e.description,e.descriptionEn,n,"--description"),s=e.from===void 0?void 0:structuredClone(kf(t,e.from,n)),a=e.env??s?.env,l=t;(l.testScenarios??=[]).push({id:e.id,label:r,...i?{description:i}:{},prefill:{...s?.prefill??{},...e.prefill},...a!==void 0?{env:a}:{}})}o(MC,"addScenario");function qC(t,e){let n=`offer form scenario set: scenario "${e.id}"`,r=kf(t,e.id,"offer form scenario set");if(e.prefillMerge!==void 0&&e.prefillReplace!==void 0)throw new Error(`${n}: pass --prefill (merge) or --prefill-json (replace), not both`);if(e.label==="")throw new Error(`${n}: --label cannot be empty`);at(r,"label",{de:e.label,en:e.labelEn},n),at(r,"description",{de:e.description,en:e.descriptionEn,clearable:!0},`${n} description`),e.prefillReplace!==void 0&&(r.prefill=e.prefillReplace),e.prefillMerge!==void 0&&(r.prefill={...r.prefill,...e.prefillMerge});for(let s of e.unset??[]){if(!(s in r.prefill))throw new Error(`${n}: --unset "${s}" is not in the prefill`);let a={...r.prefill};delete a[s],r.prefill=a}if(e.env===null?delete r.env:e.env!==void 0&&(r.env=e.env),![e.label,e.labelEn,e.description,e.descriptionEn,e.prefillMerge,e.prefillReplace,e.unset,e.env].some(s=>s!==void 0))throw new Error(`${n}: nothing to change \u2014 pass --label/--label-en/--description/--prefill/--prefill-json/--unset/--env-json`)}o(qC,"setScenario");function BC(t,e){kf(t,e,"offer form scenario rm");let n=t;n.testScenarios=Dl(t).filter(r=>r.id!==e),n.testScenarios.length===0&&delete n.testScenarios}o(BC,"removeScenario");function VC(t,e){let n="offer form env set";for(let a of e.keys)if(!Eo(a))throw new Error(`${n}: unknown environment key "${a}" (one of: ${Qs.join(", ")})`);let r=new Set(e.keys),i=t;r.size===0?delete i.env:i.env=[...r];for(let[a,l]of Object.entries(e.samples??{})){let d=Object.keys(l).filter(u=>!r.has(u));if(d.length>0)throw new Error(`${n}: --sample ${a} samples ${d.join(", ")}, which --keys does not declare`);let c=kf(t,a,n);c.env={...c.env??{},...l}}let s=[];for(let a of Dl(t)){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&&(s.push(a.id),Object.keys(l).length===0?delete a.env:a.env=l)}return s}o(VC,"setEnv");function hr(t,e){let n;try{n=bn(t)}catch(i){throw new Error(`${e}: validation threw \u2014 nothing written: ${Dn(i)}`,{cause:i})}let r=n.filter(i=>i.severity==="error");if(r.length>0)throw new Error(`${e}: validation failed \u2014 nothing written:
|
|
416
|
+
`+r.map(i=>` [${i.area}] ${i.message}`).join(`
|
|
417
|
+
`));return or(t),n.filter(i=>i.severity==="warning")}o(hr,"commitBundle");function vf(t,e,n,r){if([t!==void 0?"before":null,e!==void 0?"after":null,n?"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 t!==void 0?{kind:"before",anchor:t}:e!==void 0?{kind:"after",anchor:e}:n?{kind:"top"}:{kind:"bottom"}}o(vf,"parseMove");function rt(t){return t?t.split(",").map(e=>e.trim()).filter(e=>e.length>0):[]}o(rt,"csv");function iw(t,e){if(t!==void 0)return rt(t).map(n=>{let[r,i]=n.split(":");if(!r||!i)throw new Error(`${e}: --effect-refs token "${n}" must be effect:slot`);return{effect:r,as:i}})}o(iw,"parseEffectRefs");function ow(t,e){if(t!==void 0)return rt(t).map(n=>{let[r,i]=n.split(":");if(!r||!i)throw new Error(`${e}: --map token "${n}" must be from:to`);return{from:r,to:i}})}o(ow,"parseMappings");var De=class extends So{static{o(this,"FormMutationCommand")}withBundle(e,n){let r=_e(e);n(r);let i=hr(r,"offer form");return this.warn(i),[r,i]}withForm(e,n,r){let i=_e(e),s=yf(i,n);r(i,s);let a=hr(i,"offer form");return this.warn(a),[i,s,a]}};var Fl=class extends Re{static{o(this,"OfferFormListCommand")}static paths=[["offer","form","list"]];static usage=I.Usage({category:"Offer",description:"List the bundle's SmartForms"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=FC(_e(this.dir));return this.print(e,n=>n.length===0?[{slug:"(none)",label:"",fields:"",outcomes:"",bound:""}]:n.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}},Ll=class extends Re{static{o(this,"OfferFormShowCommand")}static paths=[["offer","form","show"]];static usage=I.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 e=_e(this.dir),n=LC(e,yf(e,this.form));return this.print(n,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}},Ml=class extends De{static{o(this,"OfferFormAddCommand")}static paths=[["offer","form","add"]];static usage=I.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,e=>{wf(e,{key:this.key,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}),this.print({added:this.key,file:`smartforms/${this.key}.json`},e=>[{key:"added",value:e.added},{key:"file",value:e.file},{key:"next",value:`offer workflow node add --type form --form ${e.added}`}]),0}},ql=class extends De{static{o(this,"OfferFormRemoveCommand")}static paths=[["offer","form","rm"]];static usage=I.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 e=this.form,[n]=this.withBundle(this.dir,i=>iC(i,e)),r=Cj.join(n.dir,"smartforms",`${e}.json`);return _j(r)&&Oj(r),this.print({removed:e},i=>[{key:"removed",value:i.removed}]),0}},Bl=class extends De{static{o(this,"OfferFormSetCommand")}static paths=[["offer","form","set"]];static usage=I.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,e=>{oC(e,{slug:this.form,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}),this.print({form:this.form,updated:!0},e=>[{key:"form",value:e.form}]),0}};var Vl=class extends De{static{o(this,"OfferFormSectionAddCommand")}static paths=[["offer","form","section","add"]];static usage=I.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"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{sC(n.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}:{}})});return this.print({form:e,section:this.id},n=>[{key:"form",value:n.form},{key:"section",value:n.section}]),0}},Kl=class extends De{static{o(this,"OfferFormSectionSetCommand")}static paths=[["offer","form","section","set"]];static usage=I.Usage({category:"Offer",description:"Update a section's label/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)'});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{aC(n.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}:{}})});return this.print({form:e,section:this.id,updated:!0},n=>[{key:"form",value:n.form},{key:"section",value:n.section}]),0}},Ul=class extends De{static{o(this,"OfferFormSectionMoveCommand")}static paths=[["offer","form","section","move"]];static usage=I.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[,e]=this.withForm(this.dir,this.form,(n,r)=>{bC(n.smartforms[r],this.id,vf(this.before,this.after,this.toTop,this.toBottom))});return this.print({form:e,section:this.id,moved:!0},n=>[{key:"form",value:n.form},{key:"section",value:n.section}]),0}},jl=class extends De{static{o(this,"OfferFormSectionRemoveCommand")}static paths=[["offer","form","section","rm"]];static usage=I.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 e=[],[,n]=this.withForm(this.dir,this.form,(r,i)=>{e=cC(r.smartforms[i],this.id)});return this.print({form:n,section:this.id,removedFields:e},r=>[{key:"form",value:r.form},{key:"section",value:r.section},{key:"removedFields",value:e.join(", ")||"(none)"}]),e.length>0&&this.context.stderr.write(`warning: removed ${e.length} field key(s) \u2014 re-publishing this form over an already-published version will be rejected by the field-key stability gate.
|
|
418
|
+
`),0}};var Gl=class extends De{static{o(this,"OfferFormFieldAddCommand")}static paths=[["offer","form","field","add"]];static usage=I.Usage({category:"Offer",description:`Add a field to a section (types: ${Dr.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:Dr.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"});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"});enumRef=p.String("--enum-ref",{description:`Central catalog (${as.join("|")})`});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"});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"});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"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{mC(n.smartforms[r],{section:this.section,key:this.key,type:this.type,required:this.required,...this.label?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.bucket?{bucket:this.bucket}:{},...this.enumOpts?{enum:rt(this.enumOpts)}:{},...this.enumRef?{enumRef:this.enumRef}:{},...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.docMime?{docMime:rt(this.docMime)}:{},...this.docMaxSize!==void 0?{docMaxSize:Number(this.docMaxSize)}:{},...this.docMultiple?{docMultiple:!0}:{},...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:e,section:this.section,field:this.key,type:this.type},n=>[{key:"form",value:n.form},{key:"field",value:n.field},{key:"type",value:n.type}]),0}},Wl=class extends De{static{o(this,"OfferFormFieldSetCommand")}static paths=[["offer","form","field","set"]];static usage=I.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"});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)"});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"});enumOpts=p.String("--enum",{description:"Replace inline enum options (a,b,c)"});enumRef=p.String("--enum-ref",{description:`Set central catalog (${as.join("|")}); "" clears`});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)"});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"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{hC(n.smartforms[r],{key:this.key,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.required!==void 0?{required:this.required}:{},...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.enumOpts!==void 0?{enum:rt(this.enumOpts)}:{},...this.enumRef!==void 0?{enumRef:this.enumRef}:{},...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:rt(this.requiredFor)}:{},...this.docMime!==void 0?{docMime:rt(this.docMime)}:{},...this.docMaxSize!==void 0?{docMaxSize:Number(this.docMaxSize)}:{},...this.docMultiple!==void 0?{docMultiple:this.docMultiple}:{},...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:e,field:this.key,updated:!0},n=>[{key:"form",value:n.form},{key:"field",value:n.field}]),0}},zl=class extends De{static{o(this,"OfferFormFieldAttachCommand")}static paths=[["offer","form","field","attach"]];static usage=I.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 e=this.render,[,n]=this.withForm(this.dir,this.form,(r,i)=>{kC(r.smartforms[i],{key:this.key,fileKey:this.fileKey,...e?{renderAs:e}:{},...this.label?{label:this.label}:{},...this.labelEn?{labelEn:this.labelEn}:{}})});return this.print({form:n,field:this.key,fileKey:this.fileKey},r=>[{key:"form",value:r.form},{key:"field",value:r.field},{key:"fileKey",value:r.fileKey}]),0}},Hl=class extends De{static{o(this,"OfferFormFieldDetachCommand")}static paths=[["offer","form","field","detach"]];static usage=I.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[,e]=this.withForm(this.dir,this.form,(n,r)=>{vC(n.smartforms[r],this.key,this.fileKey)});return this.print({form:e,field:this.key,detached:this.fileKey},n=>[{key:"form",value:n.form},{key:"field",value:n.field},{key:"detached",value:n.detached}]),0}},Ql=class extends De{static{o(this,"OfferFormFieldMoveCommand")}static paths=[["offer","form","field","move"]];static usage=I.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[,e]=this.withForm(this.dir,this.form,(n,r)=>{yC(n.smartforms[r],this.key,vf(this.before,this.after,this.toTop,this.toBottom),this.section)});return this.print({form:e,field:this.key,section:this.section??null,moved:!0},n=>[{key:"form",value:n.form},{key:"field",value:n.field},...n.section?[{key:"section",value:n.section}]:[]]),0}},Yl=class extends De{static{o(this,"OfferFormFieldRemoveCommand")}static paths=[["offer","form","field","rm"]];static usage=I.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[,e]=this.withForm(this.dir,this.form,(n,r)=>{wC(n.smartforms[r],this.key)});return this.print({form:e,removed:this.key},n=>[{key:"form",value:n.form},{key:"removed",value:n.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).
|
|
419
|
+
`),0}};var Jl=class extends De{static{o(this,"OfferFormOutcomeAddCommand")}static paths=[["offer","form","outcome","add"]];static usage=I.Usage({category:"Offer",description:"Add an outcome 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:"Outcome id (e.g. jugendamtCase)"});when=p.String("--when",{required:!0,description:"when expression (e.g. true)"});blocking=p.Boolean("--blocking",!1,{description:"Halt downstream workflow"});label=p.String("--label",{description:"Outcome label (default: id)"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label (every SmartForm text needs German and English)"});fields=p.String("--fields",{description:"Output field paths (a,b,c)"});effectRefs=p.String("--effect-refs",{description:"Output effect slots (effect:slot,\u2026)"});async execute(){let e=iw(this.effectRefs,"offer form outcome add")??[],[,n]=this.withForm(this.dir,this.form,(r,i)=>{SC(r.smartforms[i],{id:this.id,when:this.when,blocking:this.blocking,...this.label?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.fields?{fields:rt(this.fields)}:{},...e.length?{effectRefs:e}:{}})});return this.print({form:n,outcome:this.id},r=>[{key:"form",value:r.form},{key:"outcome",value:r.outcome}]),0}},Zl=class extends De{static{o(this,"OfferFormOutcomeSetCommand")}static paths=[["offer","form","outcome","set"]];static usage=I.Usage({category:"Offer",description:"Update an outcome's when/label/flags"});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:"Outcome id"});when=p.String("--when",{description:"when expression"});blocking=p.Boolean("--blocking",{description:"Blocking (or --no-blocking)"});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)"});fields=p.String("--fields",{description:'Replace output field paths (a,b,c); "" clears'});effectRefs=p.String("--effect-refs",{description:'Replace output effect slots (effect:slot,\u2026); "" clears'});async execute(){let e=iw(this.effectRefs,"offer form outcome set"),[,n]=this.withForm(this.dir,this.form,(r,i)=>{xC(r.smartforms[i],{id:this.id,...this.when!==void 0?{when:this.when}:{},...this.blocking!==void 0?{blocking:this.blocking}:{},...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.fields!==void 0?{fields:rt(this.fields)}:{},...e!==void 0?{effectRefs:e}:{}})});return this.print({form:n,outcome:this.id,updated:!0},r=>[{key:"form",value:r.form},{key:"outcome",value:r.outcome}]),0}},Xl=class extends De{static{o(this,"OfferFormOutcomeRemoveCommand")}static paths=[["offer","form","outcome","rm"]];static usage=I.Usage({category:"Offer",description:"Remove an outcome 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:"Outcome id"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{AC(n.smartforms[r],this.id)});return this.print({form:e,removed:this.id},n=>[{key:"form",value:n.form},{key:"removed",value:n.removed}]),0}};var ed=class extends De{static{o(this,"OfferFormEffectAddCommand")}static paths=[["offer","form","effect","add"]];static usage=I.Usage({category:"Offer",description:`Add an effect (${Cl.join("|")}) \u2014 materialize Person/Org/Relationship/fieldMap`});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:"Effect id (e.g. p.kind, o.jugendamt)"});kind=p.String("--kind",{required:!0,description:Cl.join("|")});when=p.String("--when",{description:"when expression (gates the effect)"});bucket=p.String("--bucket",{description:"person: party bucket (e.g. kind, elternteil_1)"});policy=p.String("--policy",{description:`person: ${bi.join("|")}`});nameFrom=p.String("--name-from",{description:"person/org: display-name field keys (a,b)"});role=p.String("--role",{description:"person/org: role key assigned to the party"});identity=p.String("--identity",{description:`person/org: ${ls.join("|")}`});identityKeyFrom=p.String("--identity-key-from",{description:"person/org: keyed identity fields (a,b)"});orgKind=p.String("--org-kind",{description:"organization: org kind (e.g. jugendamt)"});from=p.String("--from",{description:"relationship: source effect id/ref"});to=p.String("--to",{description:"relationship: target effect id/ref"});relKind=p.String("--rel-kind",{description:"relationship: relationship kind"});target=p.String("--target",{description:"fieldMap: target effect id/ref"});map=p.String("--map",{description:"fieldMap: from:to,from:to mappings"});async execute(){let e=ow(this.map,"offer form effect add")??[],[,n]=this.withForm(this.dir,this.form,(r,i)=>{EC(r.smartforms[i],{id:this.id,kind:this.kind,...this.when!==void 0?{when:this.when}:{},...this.bucket?{bucket:this.bucket}:{},...this.policy?{policy:this.policy}:{},...this.nameFrom?{nameFrom:rt(this.nameFrom)}:{},...this.role?{role:this.role}:{},...this.identity?{identity:this.identity}:{},...this.identityKeyFrom?{identityKeyFrom:rt(this.identityKeyFrom)}:{},...this.orgKind?{orgKind:this.orgKind}:{},...this.from?{from:this.from}:{},...this.to?{to:this.to}:{},...this.relKind?{relKind:this.relKind}:{},...this.target?{target:this.target}:{},...e.length?{mappings:e}:{}})});return this.print({form:n,effect:this.id,kind:this.kind},r=>[{key:"form",value:r.form},{key:"effect",value:r.effect},{key:"kind",value:r.kind}]),0}},td=class extends De{static{o(this,"OfferFormEffectSetCommand")}static paths=[["offer","form","effect","set"]];static usage=I.Usage({category:"Offer",description:"Update an effect (per-kind: when/role/policy/nameFrom/bucket/identity/orgKind/from/to/relKind/target/map)"});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:"Effect id"});when=p.String("--when",{description:'when expression ("" clears)'});role=p.String("--role",{description:'person/org: role key ("" clears)'});policy=p.String("--policy",{description:`person: ${bi.join("|")}`});nameFrom=p.String("--name-from",{description:"person/org: display-name field keys (a,b)"});bucket=p.String("--bucket",{description:"person: party bucket"});identity=p.String("--identity",{description:`person/org: ${ls.join("|")}`});identityKeyFrom=p.String("--identity-key-from",{description:"person/org: keyed identity fields (a,b)"});orgKind=p.String("--org-kind",{description:"organization: org kind"});from=p.String("--from",{description:"relationship: source effect id/ref"});to=p.String("--to",{description:"relationship: target effect id/ref"});relKind=p.String("--rel-kind",{description:"relationship: relationship kind"});target=p.String("--target",{description:"fieldMap: target effect id/ref"});map=p.String("--map",{description:"fieldMap: replace mappings (from:to,\u2026)"});async execute(){let e=ow(this.map,"offer form effect set"),[,n]=this.withForm(this.dir,this.form,(r,i)=>{RC(r.smartforms[i],{id:this.id,...this.when!==void 0?{when:this.when}:{},...this.role!==void 0?{role:this.role}:{},...this.policy!==void 0?{policy:this.policy}:{},...this.nameFrom!==void 0?{nameFrom:rt(this.nameFrom)}:{},...this.bucket!==void 0?{bucket:this.bucket}:{},...this.identity!==void 0?{identity:this.identity}:{},...this.identityKeyFrom!==void 0?{identityKeyFrom:rt(this.identityKeyFrom)}:{},...this.orgKind!==void 0?{orgKind:this.orgKind}:{},...this.from!==void 0?{from:this.from}:{},...this.to!==void 0?{to:this.to}:{},...this.relKind!==void 0?{relKind:this.relKind}:{},...this.target!==void 0?{target:this.target}:{},...e!==void 0?{mappings:e}:{}})});return this.print({form:n,effect:this.id,updated:!0},r=>[{key:"form",value:r.form},{key:"effect",value:r.effect}]),0}},nd=class extends De{static{o(this,"OfferFormEffectRemoveCommand")}static paths=[["offer","form","effect","rm"]];static usage=I.Usage({category:"Offer",description:"Remove an effect 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:"Effect id"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{TC(n.smartforms[r],this.id)});return this.print({form:e,removed:this.id},n=>[{key:"form",value:n.form},{key:"removed",value:n.removed}]),0}};var KC="Prefill key=value (repeatable), typed by the field: boolean true|false, multi-enum a,b; addresses and repeated rows via --prefill-json",rd=class extends De{static{o(this,"OfferFormScenarioAddCommand")}static paths=[["offer","form","scenario","add"]];static usage=I.Usage({category:"Offer",description:"Add a test scenario (one-click test-mode prefill; the publish gate submits it)"});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:"Scenario id (kebab-case, e.g. standard)"});from=p.String("--from",{description:"Derive from this scenario: copy its prefill + environment sample, --prefill overrides single keys"});label=p.String("--label",{required:!0,description:"Scenario label (German)"});labelEn=p.String("--label-en",{description:"English label \u2014 required with --label"});description=p.String("--description",{description:"Description (German)"});descriptionEn=p.String("--description-en",{description:"English description \u2014 required with --description"});prefill=p.Array("--prefill",{description:KC});prefillJson=p.String("--prefill-json",{description:"Whole prefill as a JSON object (instead of --prefill)"});envJson=p.String("--env-json",{description:'Environment sample as JSON, e.g. {"stage":{"key":"\u2026","name":"\u2026","gradeLevel":1}}'});async execute(){let e="offer form scenario add";if(this.prefill!==void 0&&this.prefillJson!==void 0)throw new Error(`${e}: pass --prefill or --prefill-json, not both`);if(this.from!==void 0&&this.prefillJson!==void 0)throw new Error(`${e}: --from copies the base's prefill \u2014 change single keys with --prefill, not --prefill-json`);let[,n]=this.withForm(this.dir,this.form,(r,i)=>{let s=r.smartforms[i],a=this.prefillJson!==void 0?us(this.prefillJson,"--prefill-json",e):rw(s,this.prefill??[],e);MC(s,{id:this.id,...this.from!==void 0?{from:this.from}:{},label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.description!==void 0?{description:this.description}:{},...this.descriptionEn!==void 0?{descriptionEn:this.descriptionEn}:{},prefill:a,...this.envJson!==void 0?{env:us(this.envJson,"--env-json",e)}:{}})});return this.print({form:n,scenario:this.id},r=>[{key:"form",value:r.form},{key:"scenario added",value:r.scenario}]),0}},id=class extends De{static{o(this,"OfferFormScenarioSetCommand")}static paths=[["offer","form","scenario","set"]];static usage=I.Usage({category:"Offer",description:"Edit a test scenario (--prefill merges, --prefill-json replaces, --unset removes keys)"});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:"Scenario id"});label=p.String("--label",{description:"New label (German)"});labelEn=p.String("--label-en",{description:"English label \u2014 required when --label changes a translated text"});description=p.String("--description",{description:'Description ("" clears it and its English)'});descriptionEn=p.String("--description-en",{description:"English description \u2014 required when --description changes a translated text"});prefill=p.Array("--prefill",{description:`${KC}; merged into the stored prefill`});prefillJson=p.String("--prefill-json",{description:"Replace the whole prefill with this JSON object"});unset=p.String("--unset",{description:"Remove these prefill keys (a,b)"});envJson=p.String("--env-json",{description:'Replace the environment sample (JSON object; "" removes it)'});async execute(){let e="offer form scenario set",[,n]=this.withForm(this.dir,this.form,(r,i)=>{let s=r.smartforms[i];qC(s,{id:this.id,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.description!==void 0?{description:this.description}:{},...this.descriptionEn!==void 0?{descriptionEn:this.descriptionEn}:{},...this.prefill!==void 0?{prefillMerge:rw(s,this.prefill,e)}:{},...this.prefillJson!==void 0?{prefillReplace:us(this.prefillJson,"--prefill-json",e)}:{},...this.unset!==void 0?{unset:rt(this.unset)}:{},...this.envJson!==void 0?{env:this.envJson===""?null:us(this.envJson,"--env-json",e)}:{}})});return this.print({form:n,scenario:this.id,updated:!0},r=>[{key:"form",value:r.form},{key:"scenario updated",value:r.scenario}]),0}},od=class extends De{static{o(this,"OfferFormScenarioRemoveCommand")}static paths=[["offer","form","scenario","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a test scenario"});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:"Scenario id"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{BC(n.smartforms[r],this.id)});return this.print({form:e,removed:this.id},n=>[{key:"form",value:n.form},{key:"scenario removed",value:n.removed}]),0}},sd=class extends De{static{o(this,"OfferFormEnvSetCommand")}static paths=[["offer","form","env","set"]];static usage=I.Usage({category:"Offer",description:"Declare the environment keys the form reads ($env.<key>.<field>) and sample them per scenario",details:"Replaces the declaration. The publish gate refuses a declared key a scenario does not sample, so pass every scenario's samples in the same step with --sample <scenarioId>='<json>'. A key dropped from the declaration takes its scenario samples with it."});dir=p.String("--dir",{required:!0,description:"Bundle directory"});form=p.String("--form",{description:"Form slug (default: the sole form)"});keys=p.String("--keys",{required:!0,description:'Environment keys (stage,run,applicant,\u2026); "" removes the declaration'});sample=p.Array("--sample",{description:"<scenarioId>=<JSON object> \u2014 merged into that scenario's environment sample (repeatable)"});async execute(){let e="offer form env set",n=[],r={};for(let a of this.sample??[]){let l=a.indexOf("=");if(l<=0)throw new Error(`${e}: --sample "${a}" must be <scenarioId>=<JSON object>`);r[a.slice(0,l)]=us(a.slice(l+1),"--sample",e)}let i=rt(this.keys),[,s]=this.withForm(this.dir,this.form,(a,l)=>{n=VC(a.smartforms[l],{keys:i,samples:r})});return this.print({form:s,env:i,trimmedScenarios:n},a=>[{key:"form",value:a.form},{key:"env",value:a.env.join(", ")||"(none)"},...a.trimmedScenarios.length>0?[{key:"samples dropped",value:a.trimmedScenarios.join(", ")}]:[]]),0}};var ad=class extends De{static{o(this,"OfferFormRepeatedAddCommand")}static paths=[["offer","form","repeated","add"]];static usage=I.Usage({category:"Offer",description:"Add a repeated (array-of-records) field to a section"});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:"Repeated field key"});itemFields=p.String("--item-fields",{required:!0,description:"Item template: key:type,key:type"});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)"});min=p.String("--min",{description:"minItems"});max=p.String("--max",{description:"maxItems"});itemVisibleIf=p.String("--item-visible-if",{description:"per-row itemVisibleIf ($item.*)"});uniqueBy=p.String("--unique-by",{description:"item field keys that must be unique across rows (a,b)"});async execute(){let e=rt(this.itemFields).map(r=>{let[i,s]=r.split(":");if(!i||!s)throw new Error(`offer form repeated add: --item-fields token "${r}" must be key:type`);return{key:i,type:s}}),[,n]=this.withForm(this.dir,this.form,(r,i)=>{IC(r.smartforms[i],{section:this.section,key:this.key,itemFields:e,...this.label?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.min!==void 0?{min:Number(this.min)}:{},...this.max!==void 0?{max:Number(this.max)}:{},...this.itemVisibleIf?{itemVisibleIf:this.itemVisibleIf}:{},...this.uniqueBy?{uniqueBy:rt(this.uniqueBy)}:{}})});return this.print({form:n,section:this.section,repeated:this.key},r=>[{key:"form",value:r.form},{key:"repeated",value:r.repeated}]),0}},ld=class extends De{static{o(this,"OfferFormRepeatedSetCommand")}static paths=[["offer","form","repeated","set"]];static usage=I.Usage({category:"Offer",description:"Update a repeated field's label/min/max/uniqueBy"});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:"Repeated field key"});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)"});min=p.String("--min",{description:"minItems (-1 clears)"});max=p.String("--max",{description:"maxItems (-1 clears)"});itemVisibleIf=p.String("--item-visible-if",{description:'per-row itemVisibleIf ("" clears)'});uniqueBy=p.String("--unique-by",{description:'unique item keys (a,b); "" clears'});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{_C(n.smartforms[r],{key:this.key,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.min!==void 0?{min:Number(this.min)}:{},...this.max!==void 0?{max:Number(this.max)}:{},...this.itemVisibleIf!==void 0?{itemVisibleIf:this.itemVisibleIf}:{},...this.uniqueBy!==void 0?{uniqueBy:rt(this.uniqueBy)}:{}})});return this.print({form:e,repeated:this.key,updated:!0},n=>[{key:"form",value:n.form},{key:"repeated",value:n.repeated}]),0}},dd=class extends De{static{o(this,"OfferFormRepeatedRemoveCommand")}static paths=[["offer","form","repeated","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a repeated 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:"Repeated field key to remove"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{OC(n.smartforms[r],this.key)});return this.print({form:e,removed:this.key},n=>[{key:"form",value:n.form},{key:"removed",value:n.removed}]),this.context.stderr.write(`warning: removing repeated field "${this.key}" \u2014 re-publishing over an already-published version will be rejected by the field-key stability gate.
|
|
420
|
+
`),0}},cd=class extends De{static{o(this,"OfferFormComputedAddCommand")}static paths=[["offer","form","computed","add"]];static usage=I.Usage({category:"Offer",description:"Add a computed (derived) field to a section"});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:"Computed field key"});expression=p.String("--expression",{required:!0,description:"Computed expression"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{CC(n.smartforms[r],{section:this.section,key:this.key,expression:this.expression})});return this.print({form:e,section:this.section,computed:this.key},n=>[{key:"form",value:n.form},{key:"computed",value:n.computed}]),0}},ud=class extends De{static{o(this,"OfferFormComputedSetCommand")}static paths=[["offer","form","computed","set"]];static usage=I.Usage({category:"Offer",description:"Update a computed field's expression"});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:"Computed field key"});expression=p.String("--expression",{required:!0,description:"New computed expression"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{NC(n.smartforms[r],{key:this.key,expression:this.expression})});return this.print({form:e,computed:this.key,updated:!0},n=>[{key:"form",value:n.form},{key:"computed",value:n.computed}]),0}},fd=class extends De{static{o(this,"OfferFormComputedRemoveCommand")}static paths=[["offer","form","computed","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a computed 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:"Computed field key to remove"});async execute(){let[,e]=this.withForm(this.dir,this.form,(n,r)=>{DC(n.smartforms[r],this.key)});return this.print({form:e,removed:this.key},n=>[{key:"form",value:n.form},{key:"removed",value:n.removed}]),0}};var UC=[Fl,Ll,Ml,Bl,ql,Vl,Kl,Ul,jl,Gl,Wl,Ql,Yl,zl,Hl,Jl,Zl,Xl,ed,td,nd,ad,ld,dd,cd,ud,fd,rd,id,od,sd];import{readFileSync as bG}from"node:fs";function pd(t,e,n,r,i){let a=o(f=>new Set(bn(f).filter(h=>h.severity==="error").map(h=>h.message)),"errorsOf")(_e(e)),l=i(_e(e)),d=bn(l),c=d.filter(f=>f.severity==="error"&&!a.has(f.message)),u=o(f=>n.some(h=>new RegExp(`${h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`).test(f)),"concernsEdit");for(let f of d)f.severity==="error"&&a.has(f.message)?t.write(` \u26A0 vorbestehend, nicht durch diese \xC4nderung: ${f.area}: ${f.message}
|
|
421
|
+
`):f.severity==="warning"&&u(f.message)&&t.write(` \u26A0 ${f.area}: ${f.message}
|
|
422
|
+
`);if(c.length>0){for(let f of c)t.write(` \u2716 ${f.area}: ${f.message}
|
|
423
|
+
`);return t.write(` \u2192 NOT written (fix the ${r})
|
|
424
|
+
`),null}return or(l),l}o(pd,"writeIfNoNewErrors");function Pj(t){let e=Ga(t);return{de:`${e.de} freigeben`,en:`Release ${e.en}`}}o(Pj,"defaultApproveTitle");function jC(t,e,n){if(t.production==="none"&&e==="release"&&ke("CONFLICT",`Knoten "${t.id}" hat production 'none' \u2014 ohne Dokument gibt es nichts freizugeben.`),e==="none"){let{releaseApproval:s,...a}=t.assign??{},{approve:l,...d}=t.titles??{},c={...t,approval:"none"};return t.assign!==void 0&&(Object.keys(a).length>0?c.assign=a:delete c.assign),t.titles!==void 0&&(c.titles=d),c}let{confirmBeforeIssue:r,...i}=t;return{...i,approval:"release",titles:{...t.titles,approve:n??t.titles?.approve??Pj(t)}}}o(jC,"withApprovalMode");function GC(t,e){let{confirmBeforeIssue:n,...r}=t;return e?((t.production==="none"||t.approval!=="none")&&ke("CONFLICT",`Knoten "${t.id}" (production '${t.production}', approval '${t.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.`),{...r,confirmBeforeIssue:!0}):r}o(GC,"withConfirmBeforeIssue");function WC(t,e){HC(t);let{confirmContractTerms:n,contractTermsQuestionText:r,...i}=t;return e?r===void 0?i:{...i,contractTermsQuestionText:r}:{...i,confirmContractTerms:!1}}o(WC,"withConfirmContractTerms");function zC(t,e){HC(t);let{contractTermsQuestionText:n,...r}=t;return e===null?r:(t.confirmContractTerms===!1&&ke("CONFLICT",`Knoten "${t.id}" fragt nicht nach den Vertragsbedingungen (confirmContractTerms: false) \u2014 erst die Best\xE4tigung einschalten, dann die Frage umformulieren.`),(e.de.trim()===""||e.en.trim()==="")&&ke("INVALID",`[i18n/missingTranslation] Knoten "${t.id}": die Frage nach den Vertragsbedingungen braucht einen deutschen UND einen englischen Text.`),{...r,contractTermsQuestionText:{de:e.de.trim(),en:e.en.trim()}})}o(zC,"withContractTermsQuestion");function HC(t){za(t)||ke("CONFLICT",`Knoten "${t.id}" (responseStrategy '${t.responseStrategy}') nimmt keine unterschriebene Fassung entgegen \u2014 die Best\xE4tigung der Vertragsbedingungen gibt es nur mit 'signedUpload' oder 'signedUploadChecked'.`)}o(HC,"assertReturnsSignedCopy");function QC(t,e){let{responseDueInDays:n,...r}=t;return e===null?((t.template?.fields??[]).some(i=>i.processSource==="responseDueInDays")&&ke("CONFLICT",`Knoten "${t.id}" druckt die Antwortfrist in seiner Vorlage \u2014 erst das Feld entfernen, dann die Frist.`),r):(Lu(e)||ke("INVALID",`Antwortfrist ${e} \u2014 erlaubt ist eine ganze Zahl von ${Ua} bis ${ja} Tagen.`),{...r,responseDueInDays:e})}o(QC,"withResponseDueInDays");var sw=["signedUploadChecked","eSignature"];function YC(t,e,n){t.production!=="resolver"&&ke("CONFLICT",`Knoten "${t.id}" erzeugt keinen Vertrag (production '${t.production}') \u2014 zwischen Papier und elektronischer Unterschrift w\xE4hlt nur ein Vertragsknoten mit production 'resolver'.`);let{signingRecovery:r,...i}=t.assign??{};if(e==="signedUploadChecked")return{...t,responseStrategy:e,assign:i};let s=n??t.assign?.signingRecovery??t.assign?.responseCheck;return{...t,responseStrategy:e,assign:s===void 0?i:{...i,signingRecovery:s}}}o(YC,"withResponseStrategy");function gr(t){let e=t.workflow?.graph;if(!e||!Array.isArray(e.nodes))throw new Error("offer workflow: the bundle carries no workflow graph with nodes");return e}o(gr,"workflowGraphOf");function Nj(t,e){return Cy(t,e).map(n=>nt(t,n.address,"de"))}o(Nj,"visibleAddressLines");function fs(t,e,n,r,i){let s=Nj(t,e);throw new St(`${n} "${r}": ${i}
|
|
425
|
+
An \u201E${We(t,e,"de")}" (${e}) lesbar:
|
|
426
|
+
`+(s.length>0?s.map(a=>` ${a}
|
|
427
|
+
`).join(""):` \u2014 nichts
|
|
428
|
+
`)+` Ein Formularfeld ist <Formular-Adresse>.<Feldschl\xFCssel>, z. B. '$node.form.${$n}.kind.vorname'. Adressen in einfache Anf\xFChrungszeichen setzen \u2014 sonst ersetzt die Shell $node.`)}o(fs,"refuseAddress");function un(t,e,n,r){let i=r.trim();i===""&&fs(t,e,n,r,"leer \u2014 eine Adresse nennt ihren Erzeuger."),i.startsWith("$")||fs(t,e,n,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 s=xr(i);return s===null&&fs(t,e,n,r,"keine g\xFCltige Adresse."),s}o(un,"parseAddressArg");function aw(t,e,n,r){return Sf(r).map(i=>un(t,e,n,i))}o(aw,"parseAddressList");function Sf(t){return(t??[]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(Boolean)}o(Sf,"splitList");function lw(t,e){let n=t.trim(),r=e.trim();if(!nr.test(n))throw new St(`--from "${t}": keine Knoten-ID (${nr.source})`);if(!Li(r))throw new St(`--field "${e}": kein Feldpfad (Segmente mit Punkt getrennt)`);return{scope:"node",owner:n,key:$n,path:r}}o(lw,"formFieldAddress");function xf(t,e){if(!Se(t))throw new Error(`${e}: ${JSON.stringify(t)} ist keine Adresse \u2014 ein B\xFCndel aus der Zeit vor den Adressen neu exportieren`);return fe(t)}o(xf,"storedAddressSpelling");var Dj={written:"geschrieben",evidence:"mitgelesen: Beleg der Schreib-Aufgabe",derivedSource:"mitgelesen: Quelle des abgeleiteten Preises",priceCheck:"mitgelesen: Preispr\xFCfung"};function JC(t){return Dj[t]}o(JC,"originLabel");function Fj(t,e){switch(e.scope){case"node":return`Knoten \u201E${We(t,e.owner,"de")}" (${e.owner})`;case"task":{let n=dr(t,e.owner,e.key),r=n===null?"auf keinem Knoten \u2014 die Aufgabe schreibt den Wert nicht":`auf \u201E${We(t,n,"de")}" (${n})`;return`Aufgabe \u201E${Gi(t,e.owner,"de")}" (${e.owner}) ${r}`}case"env":return"die Anmeldung (kein Erzeuger)";case"derived":return"abgeleiteter Preis (aus seinen Quellen)"}}o(Fj,"producerOf");function ZC(t,e){let n=gr(t),r=n.nodes.find(i=>i.id===e);if(!r)throw new St(`offer workflow node reads: no node "${e}" (nodes: ${n.nodes.map(i=>i.id).join(", ")})`);return ji(n,r).map(i=>({address:fe(i.address),display:nt(n,i.address,"de"),origin:i.origin,at:i.field.at,producer:Fj(n,i.address),via:i.via===void 0?"":fe(i.via)}))}o(ZC,"nodeReadRows");function XC(t,e){let n=gr(t),r=wT(n,e);if(r.length!==0)throw new St(`offer workflow node rm: \u201E${We(n,e,"de")}" (${e}) wird noch gelesen \u2014 zuerst diese Stellen \xE4ndern:
|
|
429
|
+
`+r.map(i=>` ${i.at}: ${fe(i.address)}
|
|
430
|
+
`).join(""))}o(XC,"refuseWhileNamed");var nP={approved:"active",rejected:"rejected",withdrawn:"withdrawn",expired:"expired"},eP=["process_ends","redirect_external"],tP=["add","remove","replace"],Ef=["form","decision","review","setFlag","waitlist","roleAssign","join","collectPayment","completenessCheck","countersign","engagePush","if","end"],dw="process";function Lj(t){return Ef.includes(t)}o(Lj,"isSupported");function Kn(t){if(!t.workflow)throw new Error("offer workflow node: bundle carries no workflow.json");let e=t.workflow.graph;if(!e||!Array.isArray(e.nodes))throw new Error("offer workflow node: workflow.graph has no nodes array");return e}o(Kn,"graphOf");function Mj(t){let e=Qi[t];if(!e)throw new Error(`offer workflow node: no spec registered for type "${t}"`);return e}o(Mj,"specFor");function rP(t,e){let n=t.inputs;return typeof n!="function"?[]:n(e)}o(rP,"specInputSlots");function cw(t){let e=t.manifest.progressLayout;if(!e||!Array.isArray(e.buses))throw new Error("offer workflow node: manifest.progressLayout is missing or malformed");let n=e.buses.find(r=>r.key===dw);if(!n)throw new Error(`offer workflow node: progress layout has no "${dw}" bus`);return{layout:e,bus:n}}o(cw,"processBus");function qj(t){let e=t.boards??[];if(e.length===0)throw new Error(`offer workflow node: "${dw}" bus has no board to add columns to`);return e.find(n=>n.id==="prozess")??e[0]}o(qj,"processBoard");function Af(t,e){let n=t.inputs?.[e];if(n&&n.kind==="literal"&&n.value!=null)return String(n.value)}o(Af,"nodeInputLiteral");function Bj(t){return t.nodes.find(e=>e.type==="end")}o(Bj,"findEndNode");function uw(t){return Kn(t).nodes.map(n=>({id:n.id,type:n.type,label:n.label??null,outcomes:(n.outcomes??[]).map(r=>r.id),next:Object.entries(n.next??{}).map(([r,i])=>({outcome:r,target:i.to})),reads:Array.isArray(n.reads)?n.reads.map((r,i)=>xf(r,`nodes.${n.id}.reads.${i}`)):[],notifications:Object.entries(n.notifications??{}).map(([r,i])=>({event:r,templateId:i.templateId,disabled:i.disabled===!0}))}))}o(uw,"listGraphNodes");function iP(t,e){let n=Kn(t),r=n.nodes.find(a=>a.id===e.id);if(!r)throw new Error(`offer workflow node set-notification: node "${e.id}" not found. Nodes: ${n.nodes.map(a=>a.id).join(", ")}`);if(!e.event)throw new Error("offer workflow node set-notification: --event is required (the node type's event id)");if(!e.templateId)throw new Error("offer workflow node set-notification: --template is required (the letter's registry key)");let i={templateId:e.templateId,...e.args&&Object.keys(e.args).length>0?{args:e.args}:{},...e.disabled===!0?{disabled:!0}:{}},s=r.notifications?.[e.event]!==void 0;return r.notifications={...r.notifications??{},[e.event]:i},{bundle:t,nodeId:e.id,event:e.event,binding:i,replaced:s}}o(iP,"setNodeNotification");function oP(t,e,n){let r=Kn(t),i=r.nodes.find(l=>l.id===e);if(!i)throw new Error(`offer workflow node clear-notification: node "${e}" not found. Nodes: ${r.nodes.map(l=>l.id).join(", ")}`);let s=i.notifications?.[n];if(s===void 0)throw new Error(`offer workflow node clear-notification: node "${e}" binds no letter at event "${n}" (bound: ${Object.keys(i.notifications??{}).join(", ")||"none"})`);let a={...i.notifications};return delete a[n],Object.keys(a).length===0?delete i.notifications:i.notifications=a,{bundle:t,nodeId:e,event:n,templateId:s.templateId}}o(oP,"clearNodeNotification");function no(t){let e=Sf(t.field);if(t.from!==void 0&&e.length===0)throw new St("--from names the form node \u2014 add --field <path> (the field of its form)");let n=t.from===void 0?e:e.map(r=>lw(t.from,r));return[...Sf(t.address),...n]}o(no,"keyListAddresses");var Vj={field:"reads",verb:"read"},Kj={field:"requires",verb:"require"};function sP(t,e,n){return lP(t,e,n,Vj)}o(sP,"editNodeReads");function aP(t,e,n){let r=Kn(t).nodes.find(i=>i.id===e);if(r&&r.type!=="completenessCheck")throw new Error(`offer workflow node ${n.op}-requires: only a completenessCheck node carries \`requires\` ("${e}" is "${r.type}") \u2014 for the fields a person reads before acting use *-reads`);return lP(t,e,n,Kj)}o(aP,"editNodeRequires");function lP(t,e,n,r){let{field:i,verb:s}=r,a=Kn(t),l=a.nodes.find(y=>y.id===e);if(!l)throw new Error(`offer workflow node ${i}: node "${e}" not found. Nodes: ${a.nodes.map(y=>y.id).join(", ")}`);let d=l[i];if(d!==void 0&&(!Array.isArray(d)||d.some(y=>!Se(y))))throw new Error(`offer workflow node ${i}: node "${e}" 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(n.op!=="clear"&&n.addresses.length===0)throw new Error(`offer workflow node ${n.op}-${i}: name at least one --address (or --from <formNode> --field <path>)`);let u=`--address (${i})`,f=n.op==="clear"?[]:n.addresses.flatMap(y=>typeof y=="string"?aw(gr(t),e,u,[y]):[y]),h=o((y,w)=>y.some(S=>fe(S)===fe(w)),"has"),g,b=[];switch(n.op){case"set":g=uP(f);break;case"add":g=[...c];for(let y of f)h(g,y)?b.push(y):g.push(y);break;case"remove":{let y=f.filter(w=>!h(c,w));if(y.length>0)throw new Error(`offer workflow node remove-${i}: node "${e}" does not ${s} ${y.map(fe).join(", ")} (${i}: ${c.map(fe).join(", ")||"nothing"})`);g=c.filter(w=>!h(f,w));break}case"clear":g=[];break}return g.length===0?delete l[i]:l[i]=g,{bundle:t,nodeId:e,before:c.map(fe),after:g.map(fe),added:g.filter(y=>!h(c,y)).map(fe),removed:c.filter(y=>!h(g,y)).map(fe),unchanged:b.map(fe)}}o(lP,"editNodeKeyList");function dP(t,e){if(!Lj(e.type))throw new Error(`offer workflow node add: unknown/unsupported type "${e.type}". Supported: ${Ef.join(", ")}.`);let n=e.type==="decision"||e.type==="review";if(!(e.type==="review")&&e.reads!==void 0)throw new Error(`offer workflow node add: --reads at add time only on a review node (got "${e.type}"); other nodes declare reads with \`offer workflow node set-reads\``);if(e.after!==void 0&&e.onEdge!==void 0)throw new Error("offer workflow node add: --after or --on-edge, not both");if(e.onEdge!==void 0&&(e.type==="end"||e.type==="join"))throw new Error(`offer workflow node add: --on-edge splices a node into a chain \u2014 not an "${e.type}" node`);if(e.decisionOutcomes?.length&&!n)throw new Error(`offer workflow node add: --decision-outcomes is only valid on a decision node (got "${e.type}")`);if(!n){if(e.assignDecision)throw new Error(`offer workflow node add: --assign-decision is only valid on a decision node (got "${e.type}")`);if(e.commentRequired?.length)throw new Error(`offer workflow node add: --comment-required is only valid on a decision node (got "${e.type}")`);if(e.decisionAsTask)throw new Error(`offer workflow node add: --decision-as-task is only valid on a decision node (got "${e.type}")`)}let i=e.type==="completenessCheck";if(i||Wj(e,"offer workflow node add",e.type),e.type!=="engagePush"&&(e.engageTarget!==void 0||e.engageContractFields!==void 0||e.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 "${e.type}")`);if(e.condition!==void 0&&e.type!=="if")throw new Error(`offer workflow node add: --condition is only valid on an if node (got "${e.type}")`);if(e.target!==void 0&&e.type!=="setFlag")throw new Error(`offer workflow node add: --target is only valid on a setFlag node (got "${e.type}")`);if(e.contract!==void 0&&e.type!=="countersign"&&e.type!=="engagePush")throw new Error(`offer workflow node add: --contract is only valid on a countersign or engagePush node (got "${e.type}")`);if((e.formSource!==void 0||e.payment!==void 0)&&e.type!=="engagePush")throw new Error(`offer workflow node add: --payment (and --form as an address) are only valid on an engagePush node (got "${e.type}")`);if(e.type!=="countersign"&&(e.assignTeam!==void 0&&e.type!=="engagePush"||e.titleDe!==void 0||e.titleEn!==void 0||e.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 "${e.type}")`);if(e.tasks?.length){for(let x of e.tasks)if(x.params?.onReject==="spawnRevision"&&!x.params.revisionGroup)throw new Error(`offer workflow node add: task "${x.key}" has params.onReject 'spawnRevision' but no revisionGroup \u2014 append it as the 5th field of --task (\u2026:<revisionGroup>).`)}let s=Kn(t),a=Mj(e.type);if(e.adoptForm!==void 0&&e.type!=="form")throw new Error(`offer workflow node add: --adopt-form is only valid on a form node (got "${e.type}")`);if(e.type==="form"&&e.adoptForm!==void 0&&e.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(e.type==="form"&&e.adoptForm===void 0){if(!e.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(!t.smartforms?.[e.formSlug])throw new Error(`offer workflow node add: no smartform "${e.formSlug}" in this bundle \u2014 create it with \`offer form add\` or pass --new-form.`)}let l=e.onEdge?.from??e.after,d=l?s.nodes.find(x=>x.id===l):Bj(s);if(e.onEdge&&!d)throw new Error(`offer workflow node add: --on-edge node "${e.onEdge.from}" not found. Nodes: ${s.nodes.map(x=>x.id).join(", ")}`);if(e.onEdge&&d&&d.next?.[e.onEdge.outcome]===void 0)throw new Error(`offer workflow node add: --on-edge "${d.id}" has no edge "${e.onEdge.outcome}" (edges: ${Object.keys(d.next??{}).join(", ")||"none"})`);if(e.after&&!d)throw new Error(`offer workflow node add: --after node "${e.after}" not found. Nodes: ${s.nodes.map(x=>x.id).join(", ")}`);if(!d)throw new Error("offer workflow node add: graph has no end node to insert before, and no --after given");let c=e.id??Ao(e.type,s.nodes.map(x=>x.id));if(s.nodes.some(x=>x.id===c))throw new Error(`offer workflow node add: node id "${c}" already exists`);let u=e.type==="form"?(Object.keys(e.outcomeTargets??{}).length?Object.keys(e.outcomeTargets):["standard"]).map(x=>({id:x,label:x==="standard"?{de:"Standard",en:"Standard"}:{de:x,en:""}})):n&&e.decisionOutcomes?.length?e.decisionOutcomes.map(x=>({id:x.id,label:x.label})):a.outcomes??[],f=zj(e,d),h={},g=e.outcomeTargets??{};if(e.type!=="end")if(u.length===0)if(Object.keys(g).length>0)for(let[x,v]of Object.entries(g))h[x]={to:v};else f&&(h.done={to:f});else{for(let x of u){let v=g[x.id]??f;v&&(h[x.id]={to:v})}for(let[x,v]of Object.entries(g))x in h||(h[x]={to:v})}let b=Je(e.label,e.labelEn,"offer workflow node add"),y={id:c,type:e.type,label:b,...u.length>0?{outcomes:u.map(x=>({...x}))}:{},...Object.keys(h).length>0?{next:h}:{}},w={};if(e.type==="end"){let x=fP(e);w.terminalStatus={kind:"literal",value:e.terminalStatus??nP[x]},w.applicationOutcome={kind:"literal",value:x},w.dataDecision={kind:"literal",value:pP(e.dataDecision)},w.terminationKind={kind:"literal",value:mP(e)}}else if(!i){if(e.type==="roleAssign"){let x=gP(t,e);if(e.person===void 0||e.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.");w.roleKey={kind:"literal",value:x},w.mode={kind:"literal",value:hP(e)}}else if(e.type==="form"&&e.formSlug)w.smartForm={kind:"literal",value:e.formSlug};else if(e.type!=="form"){if(e.type!=="engagePush"){if(e.type!=="collectPayment"){for(let x of rP(a,{id:c,type:e.type}))if(!(!x.required||x.inspector!=="literal-only"))throw new Error(`offer workflow node add: type "${e.type}" has a required literal-only input "${x.id}" that the CLI cannot author \u2014 add this node by hand. See playbooks/add-workflow-node.md.`)}}}}if(Object.keys(w).length>0&&(y.inputs=w),n&&(e.assignDecision&&(y.assign={decision:e.assignDecision}),e.commentRequired?.length&&(y.commentRequired=Object.fromEntries(e.commentRequired.map(x=>[x,!0]))),e.decisionAsTask&&(y.decisionAsTask=e.decisionAsTask)),e.artifacts?.length&&(y.artifacts=e.artifacts),e.tasks?.length&&(y.tasks=e.tasks),e.type==="setFlag"){if(!e.flagKey)throw new Error("offer workflow node add: --flag-key is required for a setFlag node");if(!e.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)");y.flagKey=e.flagKey,e.flagValue!==void 0&&(y.value=e.flagValue)}if(e.type==="countersign"){if(!e.assignTeam)throw new Error("offer workflow node add: --type countersign needs --assign-team <permissionGroupKey> (who countersigns)");if(!e.contract)throw new Error("offer workflow node add: --type countersign needs --contract '$node.<contractNode>.contract' (the contract it countersigns)");y.assign={countersign:e.assignTeam},(e.titleDe!==void 0||e.titleEn!==void 0)&&(y.titles={countersign:Je(e.titleDe,e.titleEn,"offer workflow node add","--title")}),e.dueInDays!==void 0&&(y.dueInDays=e.dueInDays)}if(e.type==="engagePush"){if(!e.assignTeam)throw new Error("offer workflow node add: --type engagePush needs --assign-team <permissionGroupKey> (who checks a stopped transfer)");if(e.engageTarget!=="sandbox"&&e.engageTarget!=="production")throw new Error("offer workflow node add: --type engagePush needs --engage-target sandbox|production");if(e.engageConfig===void 0)throw new Error("offer workflow node add: --type engagePush needs --engage-config <mapping.json>");if(!e.formSource)throw new Error("offer workflow node add: --type engagePush needs --form '$node.<formNode>.admission' (the form it maps)");let x=e.engageContractFields??"off";if(x!=="on"&&x!=="off")throw new Error("offer workflow node add: --engage-contract-fields is on|off");y.assign={engagePush:e.assignTeam},y.inputs={...y.inputs??{},target:{kind:"literal",value:e.engageTarget},contractFields:{kind:"literal",value:x}},y.engage=e.engageConfig}if(e.type==="if"&&(y.condition=cP(e.condition,"offer workflow node add")),i){if((e.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')");y.deadline=wP(e,"offer workflow node add",!0),kP(e.guestRole,e.person,"offer workflow node add"),e.guestRole!==void 0&&(y.guestRole=e.guestRole)}for(let[x,v]of Object.entries(e.notifications??{}))y.notifications={...y.notifications??{},[x]:{templateId:v}};if(e.type==="collectPayment")y.inputs={...y.inputs??{},[li]:{kind:"literal",value:bP(e.article,"offer workflow node add")},[_r]:{kind:"literal",value:yP(e.settlement,"offer workflow node add")}},e.reason&&(y.reason=e.reason);else if(e.settlement!==void 0||e.article!==void 0)throw new Error(`offer workflow node add: --article/--settlement are only valid on a collectPayment node (got "${e.type}")`);let S=s.nodes.findIndex(x=>x.id===d.id);if(e.type==="end"||e.type==="join"&&!e.after)s.nodes.splice(S,0,y);else if(e.onEdge){let x=d.next[e.onEdge.outcome];d.next[e.onEdge.outcome]={...x,to:c},s.nodes.splice(S+1,0,y)}else if(e.after){if(d.next)for(let[x,v]of Object.entries(d.next))v.to===f&&(d.next[x]={...v,to:c});s.nodes.splice(S+1,0,y)}else{for(let x of s.nodes)if(x.next)for(let[v,P]of Object.entries(x.next))P.to===d.id&&(x.next[v]={...P,to:c});s.nodes.splice(S,0,y)}if(e.type==="join"&&e.joinFrom?.length)for(let{nodeId:x,outcome:v}of e.joinFrom){let P=s.nodes.find(q=>q.id===x);if(!P)throw new Error(`offer workflow node add: --from source "${x}" not found. Nodes: ${s.nodes.map(q=>q.id).join(", ")}`);let E=(P.outcomes??[]).map(q=>q.id),M=new Set(E.length?E:[Bo]);if(!M.has(v))throw new Error(`offer workflow node add: --from ${x}:${v} \u2014 "${v}" is not a declared outcome of "${x}" (valid: ${[...M].join(", ")})`);P.next={...P.next??{},[v]:{to:c}}}Uj(t,y,e);let T=Ja({id:c,type:e.type,label:b},a),N=Hj(t,e.type,T,e.progress??{});Qj(t,N.states,N.mappings,N.columns,N.terminalSemantics);let F=[];if(i){let x=["rejected","absage"].filter(v=>g[v]===void 0);x.length>0&&f&&F.push(`node "${c}": ${x.join(", ")} not routed with --outcomes \u2014 they go to "${f}" (route them to the rejection/withdrawal path, e.g. --outcomes rejected:<discard>,absage:<discard.absage>)`)}return{bundle:t,nodeId:c,events:T.states.map(x=>x.id.slice(c.length+1)),warnings:[...T.warnings,...F]}}o(dP,"addGraphNode");function cP(t,e){if(t===void 0||t.trim()==="")throw new Error(`${e}: 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 t.trim()}o(cP,"requireCondition");function Uj(t,e,n){let r=gr(t);n.person!==void 0&&(e.inputs={...e.inputs??{},person:{kind:"binding",address:un(r,e.id,"--person",n.person)}});for(let[i,s,a]of jj){let l=n[s];l!==void 0&&(e[a]=un(r,e.id,i,l))}for(let[i,s,a]of Gj){let l=n[s];l!==void 0&&l.length>0&&(e[a]=uP(aw(r,e.id,i,l)))}}o(Uj,"resolveNodeAddresses");var jj=[["--adopt-form","adoptForm","adoptForm"],["--target","target","target"],["--form","formSource","form"],["--contract","contract","contract"],["--payment","payment","payment"]],Gj=[["--reads","reads","reads"],["--require","requires","requires"]];function uP(t){let e=new Set;return t.filter(n=>{let r=fe(n);return e.has(r)?!1:(e.add(r),!0)})}o(uP,"dedupe");function fP(t){let e=t.outcome??"approved";if(!Yu(e))throw new Error(`offer workflow node: --outcome "${e}" is not an end-node outcome (${Yi.join(", ")})`);return e}o(fP,"resolveEndOutcome");function pP(t){if(t===void 0)throw new Error(`offer workflow node: an end node needs --data-decision (${Ji.join("|")}) \u2014 whether the application's data is kept or discarded is stated, never derived from --outcome`);if(!Ju(t))throw new Error(`offer workflow node: --data-decision "${t}" invalid (${Ji.join(", ")})`);return t}o(pP,"resolveDataDecision");function mP(t){let e=t.terminationKind??"process_ends";if(!eP.includes(e))throw new Error(`offer workflow node: --termination-kind "${e}" invalid (${eP.join(", ")})`);return e}o(mP,"resolveTerminationKind");function hP(t){let e=t.mode??"add";if(!tP.includes(e))throw new Error(`offer workflow node: --mode "${e}" invalid (${tP.join(", ")})`);return e}o(hP,"resolveRoleMode");function gP(t,e){if(!e.role)throw new Error("offer workflow node: --type roleAssign needs --role <key> (the role granted)");let n=gf(t).map(r=>r.key);if(!n.includes(e.role))throw new Error(`offer workflow node: --role "${e.role}" is not a declared manifest roleInstance (declared: ${n.join(", ")||"none"}). Declare it first with 'offer role add'.`);return e.role}o(gP,"resolveRoleKey");function yP(t,e){if(!Cu(t))throw new Error(`${e}: --settlement is required for a collectPayment node \u2014 one of ${Ba.join(", ")} (online = die Familie zahlt im Portal, separate = die Schule rechnet au\xDFerhalb von Plexus ab); got ${JSON.stringify(t)}`);return t}o(yP,"requireSettlement");function bP(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(`${e}: --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 t.trim()}o(bP,"requireArticle");function Wj(t,e,n){if(t.requires?.length)throw new Error(`${e}: --require is only valid on a completenessCheck node (got "${n}")`);if(t.deadlineDays!==void 0||t.deadlineUntil!==void 0)throw new Error(`${e}: --deadline-days/--deadline-until are only valid on a completenessCheck node (got "${n}")`);if(t.guestRole!==void 0)throw new Error(`${e}: --guest-role is only valid on a completenessCheck node (got "${n}")`)}o(Wj,"assertNoCompletenessFlags");function wP(t,e,n){if(t.deadlineDays!==void 0&&t.deadlineUntil!==void 0)throw new Error(`${e}: --deadline-days and --deadline-until exclude each other (a check has ONE deadline)`);if(t.deadlineDays!==void 0)return{inDays:t.deadlineDays};if(t.deadlineUntil!==void 0)return{until:t.deadlineUntil};if(n)throw new Error(`${e}: a completenessCheck needs a deadline: --deadline-days <n> or --deadline-until <YYYY-MM-DD>`)}o(wP,"resolveCompletenessDeadline");function kP(t,e,n){if(t!==void 0&&t!==""&&(e===void 0||e===""))throw new Error(`${n}: --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(e!==void 0&&(t===void 0||t===""))throw new Error(`${n}: --person on a completenessCheck needs --guest-role (a bound person nothing is granted to does nothing)`)}o(kP,"assertGuestRolePairing");function zj(t,e){return t.onEdge?e.next[t.onEdge.outcome].to:t.after?Object.values(e.next??{}).map(r=>r.to)[0]:e.id}o(zj,"resolveDefaultTarget");function Hj(t,e,n,r){let i=Object.entries(r);if(i.length===0)return n;let s=n.mappings.map(c=>c.event),a=new Set(cw(t).bus.states.map(c=>c.id)),l=new Set,d=n.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(!s.includes(c))throw new Error(`offer workflow node add: a ${e} node emits no progress event "${c}" (it emits: ${s.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{...n,states:n.states.filter(c=>!l.has(c.id)),mappings:d,columns:n.columns.map(c=>({...c,states:c.states.filter(u=>!l.has(u))})).filter(c=>c.states.length>0),terminalSemantics:Object.fromEntries(Object.entries(n.terminalSemantics).filter(([c])=>!l.has(c)))}}o(Hj,"mapProgressOntoExistingStates");function Qj(t,e,n,r,i){let{bus:s}=cw(t),a=qj(s);s.states.push(...e),Object.keys(i).length>0&&(s.terminalSemantics={...s.terminalSemantics??{},...i});let l=zu(i);l.length>0&&(s.holdsSeat=[...new Set([...s.holdsSeat??[],...l])],s.commitsSeat!==void 0&&(s.commitsSeat=[...new Set([...s.commitsSeat,...l])]));let d=t.workflow.progressWiring;if(!d||!Array.isArray(d.mappings))throw new Error("offer workflow node: workflow.progressWiring is missing or malformed");d.mappings.push(...n);let c=Kn(t),u=a.columns,f=[];for(let g of r){let b=u.find(y=>y.id===g.id);if(b){let y=new Set([...b.states,...g.states]);b.states=[...y],g.optional||delete b.optional}else f.push(g)}if(f.length===0)return;let h=D$([...u,...f],{nodeOrder:Yj(c),columnNodeId:o(g=>Jj(g,d),"columnNodeId"),terminalStateIds:new Set(Object.keys(s.terminalSemantics??{}))});u.length=0,u.push(...h)}o(Qj,"mergeProgress");function Yj(t){let e=new Map(t.nodes.map(a=>[a.id,a])),n=t.nodes.find(a=>a.type==="eventTrigger")??t.nodes[0],r=new Map,i=n?[n.id]:[],s=0;for(;i.length>0;){let a=i.shift();if(!r.has(a)){r.set(a,s++);for(let l of Object.values(e.get(a)?.next??{}))r.has(l.to)||i.push(l.to)}}for(let a of t.nodes)r.has(a.id)||r.set(a.id,s++);return r}o(Yj,"nodeTopoOrder");function Jj(t,e){let n=new Set(t.states??[]),i=e.mappings.find(s=>n.has(s.state))?.match;return i&&"nodeId"in i?i.nodeId:void 0}o(Jj,"wiringNodeIdForColumn");function vP(t,e){let n=Kn(t),r=n.nodes.find(c=>c.id===e.id);if(!r)throw new Error(`offer workflow node set: node "${e.id}" not found. Nodes: ${n.nodes.map(c=>c.id).join(", ")}`);let i=[];if((e.label!==void 0||e.labelEn!==void 0)&&(at(r,"label",{de:e.label,en:e.labelEn},`offer workflow node set: node "${e.id}"`),i.push("label")),e.assignDecision!==void 0||e.commentRequired!==void 0||e.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 ("${e.id}" is "${r.type}")`);if(e.assignDecision!==void 0){if(e.assignDecision.length===0)throw new Error("offer workflow node set: --assign-decision cannot be empty");r.assign={decision:e.assignDecision},i.push("assign.decision")}e.commentRequired!==void 0&&(r.commentRequired=Object.fromEntries(e.commentRequired.map(c=>[c,!0])),i.push("commentRequired")),e.requiresOneOf!==void 0&&(e.requiresOneOf.length===0?delete r.requiresOneOf:r.requiresOneOf=e.requiresOneOf,i.push("requiresOneOf"))}if(e.artifacts!==void 0&&(r.artifacts=e.artifacts,i.push("artifacts")),e.tasks!==void 0){for(let c of e.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=e.tasks,i.push("tasks")}let a=gr(t),l=o((c,u)=>un(a,r.id,c,u),"address");if(e.flagKey!==void 0||e.flagValue!==void 0||e.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 ("${e.id}" is "${r.type}")`);e.target!==void 0&&(r.target=l("--target",e.target),i.push("target")),e.flagKey!==void 0&&(r.flagKey=e.flagKey,i.push("flagKey")),e.flagValue!==void 0&&(r.value=e.flagValue,i.push("value"))}if(e.form!==void 0){if(r.type==="form"){if(!t.smartforms?.[e.form])throw new Error(`offer workflow node set: no smartform "${e.form}" in this bundle \u2014 create it with \`offer form add\` first.`);r.inputs={...r.inputs??{},smartForm:{kind:"literal",value:e.form}}}else if(r.type==="governedDocument"&&r.production==="resolver"||r.type==="engagePush")r.form=l("--form",e.form);else throw new Error(`offer workflow node set: --form only valid on a form node (slug), a resolver governedDocument or an engagePush node (address) ("${e.id}" is "${r.type}")`);i.push("form")}if(e.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 ("${e.id}" is "${r.type}")`);r.contract=l("--contract",e.contract),i.push("contract")}if(e.payment!==void 0){if(r.type!=="engagePush")throw new Error(`offer workflow node set: --payment only valid on an engagePush node ("${e.id}" is "${r.type}")`);r.payment=l("--payment",e.payment),i.push("payment")}if(e.condition!==void 0){if(r.type!=="if")throw new Error(`offer workflow node set: --condition only valid on an if node ("${e.id}" is "${r.type}")`);r.condition=cP(e.condition,"offer workflow node set"),i.push("condition")}if(e.outcome!==void 0||e.terminalStatus!==void 0||e.terminationKind!==void 0||e.dataDecision!==void 0){if(r.type!=="end")throw new Error(`offer workflow node set: --outcome/--terminal-status/--termination-kind/--data-decision only valid on an end node ("${e.id}" is "${r.type}")`);let c=fP({outcome:e.outcome??Af(r,"applicationOutcome")});r.inputs={...r.inputs??{},terminalStatus:{kind:"literal",value:e.terminalStatus??Af(r,"terminalStatus")??nP[c]},applicationOutcome:{kind:"literal",value:c},dataDecision:{kind:"literal",value:pP(e.dataDecision??Af(r,"dataDecision"))},terminationKind:{kind:"literal",value:mP({terminationKind:e.terminationKind??Af(r,"terminationKind")})}},i.push("outcome")}if(e.deadlineDays!==void 0||e.deadlineUntil!==void 0||e.guestRole!==void 0||e.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 ("${e.id}" is "${r.type}")`);let c=wP(e,"offer workflow node set",!1);c!==void 0&&(r.deadline=c,i.push("deadline"));let u={...r.inputs??{}},f=u.person,h=f?.kind==="binding"?fe(f.address):void 0;if(e.guestRole===""){if(e.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 r.guestRole,delete u.person,i.push("guestRole","inputs.person")}else{let g=e.guestRole??r.guestRole,b=e.person??h;kP(g,b,"offer workflow node set"),e.guestRole!==void 0&&(r.guestRole=e.guestRole,i.push("guestRole")),e.person!==void 0&&(u.person={kind:"binding",address:l("--person",e.person)},i.push("inputs.person"))}r.inputs=u}if(e.role!==void 0||e.mode!==void 0||e.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 ("${e.id}" is "${r.type}")`);if(r.inputs={...r.inputs??{}},e.role!==void 0&&(r.inputs.roleKey={kind:"literal",value:gP(t,{role:e.role})},i.push("role")),e.mode!==void 0&&(r.inputs.mode={kind:"literal",value:hP({mode:e.mode})},i.push("mode")),e.person!==void 0){if(e.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",e.person)},i.push("person")}}if(e.approval!==void 0||e.approveTitle!==void 0||e.confirmIssue!==void 0||e.confirmTerms!==void 0||e.termsQuestion!==void 0||e.responseDueDays!==void 0||e.signing!==void 0){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 ("${e.id}" is "${r.type}")`);let c=r;if(e.signing!==void 0){if(!sw.includes(e.signing))throw new Error(`offer workflow node set: --signing "${e.signing}" \u2014 expected one of ${sw.join(", ")}`);c=YC(c,e.signing),i.push("responseStrategy")}if(e.approval!==void 0||e.approveTitle!==void 0){let u=e.approval??c.approval;if(!jo.includes(u))throw new Error(`offer workflow node set: --approval "${u}" \u2014 expected one of ${jo.join(", ")}`);if(e.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=jC(c,u,e.approveTitle!==void 0?{de:e.approveTitle,en:e.approveTitle}:void 0),i.push("approval")}e.confirmIssue!==void 0&&(c=GC(c,e.confirmIssue),i.push("confirmBeforeIssue")),e.confirmTerms!==void 0&&(c=WC(c,e.confirmTerms),i.push("confirmContractTerms")),e.termsQuestion!==void 0&&(c=zC(c,e.termsQuestion),i.push("contractTermsQuestionText")),e.responseDueDays!==void 0&&(c=QC(c,e.responseDueDays),i.push("responseDueInDays"));for(let u of Object.keys(r))delete r[u];Object.assign(r,c)}if(e.settlement!==void 0||e.article!==void 0){if(r.type!=="collectPayment")throw new Error(`offer workflow node set: --article/--settlement only valid on a collectPayment node ("${e.id}" is "${r.type}")`);e.settlement!==void 0&&(r.inputs={...r.inputs??{},[_r]:{kind:"literal",value:yP(e.settlement,"offer workflow node set")}},i.push("settlement")),e.article!==void 0&&(r.inputs={...r.inputs??{},[li]:{kind:"literal",value:bP(e.article,"offer workflow node set")}},i.push("article"))}if(e.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) ("${e.id}" is "${r.type}")`);let c=e.traeger.trim();if(c==="")throw new Error("offer workflow node set: --traeger needs a legal entity key (foundation.legalEntities[].key)");r.inputs={...r.inputs??{},[_n]:{kind:"literal",value:c}},i.push(_n)}if(e.outcomeTargets&&Object.keys(e.outcomeTargets).length>0&&Zj(n,r,e.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/--article/--traeger");return{bundle:t,nodeId:e.id,changed:i}}o(vP,"setGraphNode");function Zj(t,e,n,r){let i=new Set(t.nodes.map(l=>l.id)),s=(e.outcomes??[]).map(l=>l.id),a=new Set(s.length?s:[Bo]);e.next={...e.next??{}};for(let[l,d]of Object.entries(n)){if(!a.has(l))throw new Error(`offer workflow node set: outcome "${l}" is not a declared outcome of "${e.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(", ")})`);e.next[l]={...e.next[l]??{},to:d},r.push(`next.${l}`)}}o(Zj,"rewriteRouting");function SP(t,e){let n=Kn(t),r=n.nodes.find(l=>l.id===e);if(!r)throw new Error(`offer workflow node rm: node "${e}" not found. Nodes: ${n.nodes.map(l=>l.id).join(", ")}`);if(r.type==="eventTrigger")throw new Error(`offer workflow node rm: refusing to remove the start node "${e}"`);if(r.type==="end")throw new Error(`offer workflow node rm: refusing to remove the end node "${e}"`);XC(t,e);let i=[...new Set(Object.values(r.next??{}).map(l=>l.to))];if(i.length>1)throw new Error(`offer workflow node rm: node "${e}" has multiple successors (${i.join(", ")}); splice-removal needs a single successor. Edit the bundle manually.`);let s=i[0];for(let l of n.nodes)if(l.next)for(let[d,c]of Object.entries(l.next))c.to===e&&(s?l.next[d]={...c,to:s}:delete l.next[d]);n.nodes=n.nodes.filter(l=>l.id!==e);let a=Xj(t,e);return{bundle:t,removedStates:a}}o(SP,"removeGraphNode");function Xj(t,e){let n=cw(t).bus,r=t.workflow.progressWiring,i=r&&Array.isArray(r.mappings)?r.mappings:[],s=o(c=>"nodeId"in c.match&&c.match.nodeId===e,"isOwn"),a=new Set(i.filter(c=>!s(c)).map(c=>c.state)),l=[...new Set(i.filter(s).map(c=>c.state))].filter(c=>!a.has(c)),d=new Set(l);if(n.states=n.states.filter(c=>!d.has(c.id)),n.terminalSemantics)for(let c of l)delete n.terminalSemantics[c];for(let c of n.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=>!s(c))),l}o(Xj,"stripProgress");function xP(t){if(t.from===void 0!=(t.field===void 0))throw new Error("offer workflow node set-input: --from and --field go together (the field of that node's form)");if([t.address!==void 0,t.from!==void 0,t.literal!==void 0,t.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(t.clear===!0)return null;if(t.address!==void 0)return{kind:"address",raw:t.address};if(t.from!==void 0)return{kind:"binding",address:lw(t.from,t.field)};let n;try{n=JSON.parse(t.literal)}catch{throw new Error(`offer workflow node set-input: --literal is JSON \u2014 a text needs its quotes ('"de"'), got ${t.literal}`)}if(!(n===null||["string","number","boolean"].includes(typeof n))&&!ni(n))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:n}}o(xP,"parseInputCell");function AP(t,e,n,r){let i=Kn(t),s=i.nodes.find(h=>h.id===e);if(!s)throw new Error(`offer workflow node set-input: no node "${e}" (nodes: ${i.nodes.map(h=>h.id).join(", ")})`);if(n.trim()==="")throw new Error("offer workflow node set-input: --input is empty");let a=r?.kind==="address"?{kind:"binding",address:un(gr(t),e,"--address",r.raw)}:r;if(s.type==="end")throw new Error(`offer workflow node set-input: "${e}" is an end node \u2014 its outcome cells are set with \`offer workflow node set --outcome|--terminal-status|--termination-kind\``);let l=Qi[s.type];if(!l)throw new Error(`offer workflow node set-input: no spec for node type "${s.type}"`);let d=rP(l,s),c=d.find(h=>h.id===n);if(c===void 0&&a!==null)throw new Error(`offer workflow node set-input: "${e}" (${s.type}) has no input slot "${n}" (slots: ${d.map(h=>h.id).join(", ")||"none"})`);if(c!==void 0&&a?.kind==="literal"){let h=KE(a.value,c);if(h!==null)throw new Error(`offer workflow node set-input: ${e}.${n}: ${h}`)}let u={...s.inputs??{}},f=u[n];if(a===null){if(f===void 0)throw new Error(`offer workflow node set-input: node "${e}" has no input "${n}" to clear (inputs: ${Object.keys(u).join(", ")||"none"})`);delete u[n]}else u[n]=a;return Object.keys(u).length===0?delete s.inputs:s.inputs=u,{bundle:t,before:f,after:a??void 0}}o(AP,"setNodeInput");function EP(t,e,n){let r=Kn(t),i=r.nodes.find(a=>a.id===e);if(!i)throw new Error(`offer workflow node set-engage: no node "${e}" (nodes: ${r.nodes.map(a=>a.id).join(", ")})`);if(i.type!=="engagePush")throw new Error(`offer workflow node set-engage: "${e}" is a ${i.type} node, not engagePush`);let s=i.engage;return i.engage=n,{bundle:t,before:s}}o(EP,"setNodeEngageConfig");var eG="offer workflow node optional-action";function ct(t,e){throw new St(`${eG} ${t}: ${e}`)}o(ct,"refuse");function TP(t,e,n){let r=t.workflow?.graph;t.workflow||ct(n,"das B\xFCndel enth\xE4lt keine workflow.json."),(!r||!Array.isArray(r.nodes))&&ct(n,"workflow.graph hat keine Knotenliste.");let i=r.nodes,s=i.find(a=>a.id===e);return s||ct(n,`Knoten \u201E${e}" gibt es nicht. Knoten: ${i.map(a=>a.id).join(", ")}.`),s.optionalActions!==void 0&&!Array.isArray(s.optionalActions)&&ct(n,`Knoten \u201E${e}" tr\xE4gt eine fehlerhafte \`optionalActions\`-Liste \u2014 workflow.json zuerst reparieren.`),s}o(TP,"findNode");function Rf(t,e,n){let r=e.trim();r||ct(t,"darf nicht leer sein.");let i=n?.trim();return n!==void 0&&!i&&ct(`${t}-en`,"darf nicht leer sein."),{de:r,en:i||r}}o(Rf,"bilingual");function tG(t){let e=t.split(",").map(n=>n.trim()).filter(Boolean);return e.length===0&&ct("--tasks","leere Liste \u2014 mindestens einen Aufgabenschl\xFCssel des Knotens nennen."),e}o(tG,"parseTasks");function RP(t){return{key:t.key,action:t.action,label:t.label,...t.description!==void 0?{description:t.description}:{},...t.trigger!==void 0?{trigger:t.trigger}:{},tasks:t.tasks,...t.repeatable===!0?{repeatable:!0}:{}}}o(RP,"ordered");function IP(t,e,n,r){let i=TP(t,e,"set");n.trim()||ct("set","--key darf nicht leer sein.");let s=i.optionalActions??[],a=s.findIndex(u=>u.key===n),l=a<0?null:structuredClone(s[a]);l!==null&&l.action!=="spawnTasks"&&ct("set",`\u201E${n}" auf ${e} ist keine spawnTasks-Aktion (${String(l.action)}).`),l===null&&(r.label===void 0&&ct("set","--label ist Pflicht f\xFCr eine neue Aktion (der Eintrag im Men\xFC \u201EWeiteres\u201C)."),r.tasks===void 0&&ct("set","--tasks ist Pflicht f\xFCr eine neue Aktion (Aufgabenschl\xFCssel des Knotens, a,b)."),(r.clearDescription||r.clearTrigger)&&ct("set","--clear-* gibt es nur beim \xC4ndern \u2014 eine neue Aktion hat nichts zu entfernen.")),r.description!==void 0&&r.clearDescription&&ct("set","--description und --clear-description schlie\xDFen einander aus."),r.trigger!==void 0&&r.clearTrigger&&ct("set","--trigger und --clear-trigger schlie\xDFen einander aus.");let d=l===null?{key:n,action:"spawnTasks"}:structuredClone(l);if(r.label!==void 0?d.label=Rf("--label",r.label,r.labelEn):r.labelEn!==void 0&&(d.label={...d.label,en:Rf("--label",d.label.de,r.labelEn).en}),r.clearDescription&&(d.description===void 0&&ct("set",`\u201E${n}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete d.description),r.description!==void 0?d.description=Rf("--description",r.description,r.descriptionEn):r.descriptionEn!==void 0&&(d.description===void 0&&ct("set","--description-en braucht --description."),d.description={...d.description,en:Rf("--description",d.description.de,r.descriptionEn).en}),r.tasks!==void 0&&(d.tasks=tG(r.tasks)),r.clearTrigger&&(d.trigger===void 0&&ct("set",`\u201E${n}" hat kein --trigger \u2014 --clear-trigger hat nichts zu entfernen.`),delete d.trigger),r.trigger!==void 0){let u=r.trigger.trim();u||ct("--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=RP(d);return l!==null&&JSON.stringify(RP(l))===JSON.stringify(c)&&ct("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aktion \u201E${n}".`),i.optionalActions=a<0?[...s,c]:s.map((u,f)=>f===a?c:u),{bundle:t,nodeId:e,key:n,before:l,after:c}}o(IP,"setOptionalAction");function $P(t,e,n){let r=TP(t,e,"remove"),i=r.optionalActions??[],s=i.find(l=>l.key===n);s||ct("remove",`Knoten \u201E${e}" hat keine optionale Aktion \u201E${n}" (Aktionen: ${i.map(l=>l.key).join(", ")||"keine"}).`),r.requiresOneOf?.includes(n)===!0&&ct("remove",`\u201E${n}" steht in 'requiresOneOf' von ${e} \u2014 zuerst die Regel \xE4ndern (node set --requires-one-of \u2026).`);let a=i.filter(l=>l.key!==n);return a.length===0?delete r.optionalActions:r.optionalActions=a,{bundle:t,nodeId:e,key:n,before:s,after:null}}o($P,"removeOptionalAction");function Tf(t){if(!t.workflow)throw new Error("offer workflow channels: bundle carries no workflow.json");let e=t.workflow.graph;if(!e||!Array.isArray(e.nodes))throw new Error("offer workflow channels: workflow.graph has no nodes array");return e}o(Tf,"graphOf");function _P(t,e){let n=Tf(t),{channels:r,...i}=n,s=e.length>0?{...i,channels:e}:i;return{...t,workflow:{...t.workflow,graph:s}}}o(_P,"withChannels");function OP(t){let e=Tf(t),n=d_(e).map(i=>({key:df(i),label:i,members:[df(i)],source:"derived"})),r=Qo(e).map(i=>({key:i.key,label:Fe(i.label),members:[...i.members],source:"authored"}));return[...n,...r]}o(OP,"listChannels");function CP(t,e){let n=Qo(Tf(t)),r="offer workflow channels add",i={de:"--label",en:"--label-en"},s=e.key===void 0?void 0:n.find(f=>f.key===e.key),a=s===void 0?tn({de:e.label,en:e.labelEn},r,i):tr(s.label,{de:e.label,en:e.labelEn},r,i)??s.label,l=e.key??c_(a.de,new Set(n.map(f=>f.key))),d={key:l,label:a,members:e.teams.map(f=>f.startsWith("team:")?f:df(f))},c=n.findIndex(f=>f.key===l),u=[...n];return c>=0?u[c]=d:u.push(d),{bundle:_P(t,u),channel:d,replaced:c>=0}}o(CP,"upsertChannel");function PP(t,e){let n=Qo(Tf(t)),r=n.find(i=>i.key===e);if(r===void 0){let i=n.map(s=>s.key).join(", ")||"\u2014";throw new Error(`offer workflow channels: no authored channel "${e}" (authored: ${i}). Derived team channels cannot be removed \u2014 they follow the teams the process assigns.`)}return{bundle:_P(t,n.filter(i=>i.key!==e)),removed:r}}o(PP,"removeChannel");var ro="offer workflow staff-input";function NP(t){if(!t.workflow)throw new Error(`${ro}: bundle carries no workflow.json`);let e=t.workflow.graph;if(!e||!Array.isArray(e.nodes))throw new Error(`${ro}: workflow.graph has no nodes array`);return e}o(NP,"graphOf");function fw(t){let e=NP(t).staffInputs;if(e===void 0)return[];if(!Array.isArray(e))throw new Error(`${ro}: workflow.graph.staffInputs is not a list (${JSON.stringify(e)}) \u2014 fix workflow.json`);return e}o(fw,"declared");function DP(t,e){let{staffInputs:n,...r}=NP(t),i=e.length>0?{...r,staffInputs:e}:r;return{...t,workflow:{...t.workflow,graph:i}}}o(DP,"withStaffInputs");function FP(t){return fw(t).map(e=>({key:e.key,type:e.type,label:e.label,reads:xE(e.key)}))}o(FP,"listStaffInputs");function LP(t,e){if(!Ys.test(e.key))throw new Error(`${ro} set: key "${e.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 n=fw(t),r=n.findIndex(c=>c.key===e.key),i={de:"--label",en:"--label-en"},s=r>=0?n[r]:void 0,a=s===void 0?tn({de:e.label,en:e.labelEn},`${ro} set`,i):tr(s.label,{de:e.label,en:e.labelEn},`${ro} set`,i)??s.label,l={key:e.key,type:"boolean",label:a},d=[...n];return r>=0?d[r]=l:d.push(l),{bundle:DP(t,d),input:l,replaced:r>=0}}o(LP,"setStaffInput");function MP(t,e){let n=fw(t),r=n.find(i=>i.key===e);if(r===void 0)throw new Error(`${ro} remove: no staff input "${e}" (declared: ${n.map(i=>i.key).join(", ")||"none"})`);return{bundle:DP(t,n.filter(i=>i.key!==e)),removed:r}}o(MP,"removeStaffInput");var qP=["task","approval"],BP=["respawn","stayClosed"],nG="offer workflow node task";function ce(t,e){throw new St(`${nG} ${t}: ${e}`)}o(ce,"refuse");function mw(t,e){let n=t.workflow?.graph;return t.workflow||ce(e,"das B\xFCndel enth\xE4lt keine workflow.json."),(!n||!Array.isArray(n.nodes))&&ce(e,"workflow.graph hat keine Knotenliste."),n.nodes}o(mw,"graphNodes");function hw(t,e,n){let r=mw(t,n),i=r.find(s=>s.id===e);return i||ce(n,`Knoten \u201E${e}" gibt es nicht. Knoten: ${r.map(s=>s.id).join(", ")}.`),i.tasks!==void 0&&!Array.isArray(i.tasks)&&ce(n,`Knoten \u201E${e}" tr\xE4gt eine fehlerhafte \`tasks\`-Liste \u2014 workflow.json zuerst reparieren.`),i}o(hw,"findNode");function rG(t,e){let n=t.trim(),r=n.lastIndexOf(":"),i=r<0?e:n.slice(0,r).trim(),s=r<0?n:n.slice(r+1).trim();return(!i||!s)&&ce("--blocks",`\u201E${t}" ist kein Ziel \u2014 erwartet <knotenId>:<templateKey> oder nur <templateKey> f\xFCr denselben Knoten.`),i===e?{templateKey:s}:{node:i,templateKey:s}}o(rG,"parseBlocksTarget");function pw(t,e){let n=t.split(",").map(r=>r.trim()).filter(Boolean);return n.length===0&&ce(e,"leere Liste \u2014 mindestens einen Eintrag nennen oder die Option weglassen."),n}o(pw,"parseList");function iG(t,e){let n=t.indexOf("="),r=n<0?"":t.slice(0,n).trim(),i=n<0?"":t.slice(n+1),s=i.indexOf("|"),a=(s<0?i:i.slice(0,s)).trim(),l=s<0?a:i.slice(s+1).trim();return(!r||!a||!l)&&ce(e,`\u201E${t}" ist fehlerhaft \u2014 erwartet <schl\xFCssel>=<Bezeichnung> oder <schl\xFCssel>=<Bezeichnung>|<English>.`),{key:r,label:{de:a,en:l}}}o(iG,"parseKeyedLabel");function oG(t){return iG(t,"--option")}o(oG,"parseResultOption");function sG(t,e,n){let r;try{r=JSON.parse(t)}catch{ce("--field",`\u201E${t}" 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${t}" ist kein JSON-Objekt.`);let i=r,s=i.suggest;if(s?.kind==="form"){let a=s.address;typeof a=="string"?i.suggest={kind:"form",address:un(e,n,"--field suggest.address",a)}:(typeof a!="object"||a===null)&&fs(e,n,"--field suggest",JSON.stringify(s),'ein Formular-Vorschlag nennt seine Adresse \u2014 {"kind":"form","address":"$node.<Formular>.admission.<Export>"}.')}return i}o(sG,"parseRecordField");function aG(t){let e=Number(t);return(!/^\s*\d+\s*$/.test(t)||!Number.isInteger(e)||e<=0)&&ce("--due-in-days",`\u201E${t}" ist keine positive ganze Zahl von Tagen.`),e}o(aG,"parseDueInDays");function lG(t){return!ri(t)&&t!=="appointment"&&ce("--result",`unbekannter Ergebnistyp \u201E${t}" \u2014 erlaubt: ${[...Fo,"appointment"].map(e=>`${e} (${$r[e].label.de})`).join(", ")}.`),t}o(lG,"parseResultType");function dG(t,e,n,r,i){let s=`'$task.${r}.<schl\xFCssel>'`;i.trim().startsWith("$")||ce(t,`--writes \u201E${i}": ein nackter Schl\xFCssel \u2014 --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${s}.`);let a=un(e,n,"--writes",i);return(a.scope!=="task"||a.owner!==r)&&ce(t,`--writes \u201E${i}": --writes schreibt unter der Adresse dieser Aufgabe \u2014 ${s}.`),a.path!==void 0&&ce(t,`--writes \u201E${i}": eine Aufgabe schreibt ihren Wert als Ganzes \u2014 ${s} ohne Pfad.`),a.key}o(dG,"parseWritesArg");function cG(t,e,n,r){let i="'$derived.<schl\xFCssel>' ohne Pfad";r.trim().startsWith("$")||ce(t,`--prices \u201E${r}": ein nackter Schl\xFCssel \u2014 --prices nennt einen abgeleiteten Preis \u2014 ${i}.`);let s=un(e,n,"--prices",r);return(s.scope!=="derived"||s.path!==void 0)&&ce(t,`--prices \u201E${r}": --prices nennt einen abgeleiteten Preis \u2014 ${i}.`),s.key}o(cG,"parsePricesArg");function uG(t,e,n){let r=e.resultLabel?.trim()??n?.de;(r===void 0||r.length===0)&&ce(t,"--result-label nennt den Namen des Werts (deutsch, nicht leer), z. B. \u201ESchulgeld mit Erm\xE4\xDFigung\u201C."),e.resultLabelEn!==void 0&&e.resultLabelEn.trim().length===0&&ce(t,"--result-label-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Name auch im Englischen.");let i=e.resultLabelEn?.trim()??(e.resultLabel!==void 0?r:n?.en??r);return{de:r,en:i}}o(uG,"resultLabelOf");function fG(t){let e=Number(t);return(!/^\s*\d+\s*$/.test(t)||!Number.isInteger(e)||e<Jo||e>Zo)&&ce("--duration",`\u201E${t}" ist keine Dauer \u2014 erwartet ganze Minuten von ${Jo} bis ${Zo}.`),e}o(fG,"parseDuration");function pG(t){let e=t.trim();return e==="external"&&ce("--chat",'\u201Eexternal" ist kein Ziel \u2014 ein Aufgabenergebnis erreicht die Familie nie. Erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.'),wu(e)===null&&ce("--chat",`\u201E${t}" ist kein Ziel \u2014 erlaubt: all, team:<gruppe>, <kanalschl\xFCssel>.`),e}o(pG,"checkChat");function gt(t,e,n,r,i,s){let a=o(l=>{let d=e[l];return Array.isArray(d)?d.length>0:d!==void 0&&d!==!1},"has");a(n)&&a(r)&&ce(t,`${i} und ${s} schlie\xDFen einander aus.`)}o(gt,"exclusive");function VP(t,e,n,r,i,s){gt(t,s,"blocks","clearBlocks","--blocks","--clear-blocks"),gt(t,s,"result","clearResult","--result","--clear-result"),gt(t,s,"options","clearResult","--option","--clear-result"),gt(t,s,"chat","clearResult","--chat","--clear-result"),gt(t,s,"textRequired","clearResult","--text-required","--clear-result"),gt(t,s,"duration","clearResult","--duration","--clear-result"),gt(t,s,"resultTitle","clearResult","--result-title","--clear-result"),gt(t,s,"resultTitleEn","clearResult","--result-title-en","--clear-result"),gt(t,s,"writes","clearResult","--writes","--clear-result"),gt(t,s,"prices","clearResult","--prices","--clear-result"),gt(t,s,"item","clearResult","--item","--clear-result"),gt(t,s,"resultLabel","clearResult","--result-label","--clear-result"),gt(t,s,"resultLabelEn","clearResult","--result-label-en","--clear-result"),gt(t,s,"when","clearWhen","--when","--clear-when"),gt(t,s,"onConditionReturn","clearWhen","--on-condition-return","--clear-when"),gt(t,s,"reads","clearReads","--reads","--clear-reads"),gt(t,s,"documents","clearDocuments","--documents","--clear-documents"),gt(t,s,"description","clearDescription","--description","--clear-description"),gt(t,s,"descriptionEn","clearDescription","--description-en","--clear-description");let a=[],l=structuredClone(i??{key:r});if(s.kind!==void 0?(qP.includes(s.kind)||ce(t,`--kind \u201E${s.kind}" ist unbekannt \u2014 erlaubt: ${qP.join(", ")}.`),l.kind=s.kind):i===null&&(l.kind="task"),s.title!==void 0){let f=s.title.trim();f||ce(t,"--title darf nicht leer sein."),l.title={de:f,en:s.titleEn?.trim()||f}}else if(s.titleEn!==void 0){i===null&&ce(t,"--title-en braucht --title.");let f=s.titleEn.trim();f||ce(t,"--title-en darf nicht leer sein."),l.title={...l.title,en:f}}if(s.team!==void 0){let f=s.team.trim();f||ce(t,"--team darf nicht leer sein (Schl\xFCssel einer Berechtigungsgruppe)."),l.assign={...l.assign??{},group:f}}s.dueInDays!==void 0&&(l.params={...l.params??{},dueInDays:aG(s.dueInDays)}),s.clearBlocks&&(l.blocks===void 0&&ce(t,`Aufgabe \u201E${r}" blockiert nichts \u2014 --clear-blocks hat nichts zu entfernen.`),delete l.blocks),s.blocks!==void 0&&(l.blocks?.except!==void 0&&a.push("blocks.except"),l.blocks=rG(s.blocks,n)),s.clearResult&&(l.result===void 0&&ce(t,`Aufgabe \u201E${r}" hat kein Ergebnis \u2014 --clear-result hat nichts zu entfernen.`),delete l.result);let d=(s.options?.length??0)>0||(s.fields?.length??0)>0||s.writes!==void 0||s.prices!==void 0||s.item!==void 0||s.resultLabel!==void 0||s.resultLabelEn!==void 0||s.textRequired!==void 0||s.chat!==void 0||s.files!==void 0,c=s.duration!==void 0||s.resultTitle!==void 0||s.resultTitleEn!==void 0;if(s.result!==void 0||d||c){let f=s.result!==void 0?lG(s.result):l.result?.kind;if(f===void 0&&ce(t,`--option, --text-required, --chat, --writes, --prices, --item, --result-label, --duration und --result-title brauchen ein Ergebnis \u2014 --result ${[...Fo,"appointment"].join("|")} angeben.`),f==="appointment"){d&&ce(t,"--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 h=l.result?.kind==="appointment"?l.result:void 0;l.result!==void 0&&h===void 0&&a.push("result (vorheriger Ergebnistyp)");let g=s.resultTitle?.trim()??h?.title.de;(g===void 0||g.length===0)&&ce(t,"--result appointment braucht --result-title (neutraler Titel des Termins \u2014 steht im Familienbrief und in der Kalenderdatei).");let b=s.duration!==void 0?fG(s.duration):h?.durationMinutes;b===void 0&&ce(t,"--result appointment braucht --duration <Minuten> (vorbelegte Dauer im Termin-Dialog)."),s.resultTitleEn!==void 0&&s.resultTitleEn.trim().length===0&&ce(t,"--result-title-en darf nicht leer sein \u2014 ohne die Option steht der deutsche Titel auch im Englischen.");let y=s.resultTitleEn?.trim()??(s.resultTitle!==void 0?g:h?.title.en??g);l.result={kind:"appointment",title:{de:g,en:y},durationMinutes:b}}else{c&&ce(t,`--duration und --result-title gelten nur f\xFCr --result appointment \u2014 hier: ${f} (${$r[f].label.de}).`);let h=l.result!==void 0&&Lo(l.result)?l.result:void 0;l.result?.kind==="appointment"&&a.push("result (Termin)");let g={kind:f};h?.chat!==void 0&&(g.chat=h.chat),h?.textRequired!==void 0&&(f==="freetext"?a.push("result.textRequired"):g.textRequired=h.textRequired),h?.options!==void 0&&(f==="choice"?g.options=h.options:a.push("result.options")),h?.fields!==void 0&&(f==="record"?g.fields=h.fields:a.push("result.fields"));let b=$r[f].valueType!==null;h?.writes!==void 0&&(b?g.writes=h.writes:a.push("result.writes")),h?.label!==void 0&&(b?g.label=h.label:a.push("result.label")),h?.prices!==void 0&&(f==="reduction"?g.prices=h.prices:a.push("result.prices")),h?.item!==void 0&&(f==="pricedItem"?g.item=h.item:a.push("result.item")),h?.files===!0&&(Ui(g)?g.files=!0:a.push("result.files"));let y=Fo.filter(S=>$r[S].valueType!==null).join(", "),w=`hier: ${f} (${$r[f].label.de})`;if(s.writes!==void 0&&(b||ce(t,`--writes gibt es nur bei Ergebnissen mit Wert (${y}) \u2014 ${w}.`),g.writes=dG(t,e,n,r,s.writes)),s.prices!==void 0&&(f!=="reduction"&&ce(t,`--prices gibt es nur beim Ergebnistyp reduction \u2014 ${w}.`),g.prices=cG(t,e,n,s.prices)),s.item!==void 0){f!=="pricedItem"&&ce(t,`--item gibt es nur beim Ergebnistyp pricedItem \u2014 ${w}.`);let S=s.item.trim();S.length===0&&ce(t,"--item darf nicht leer sein (der Schl\xFCssel des Artikels, z. B. tuition)."),g.item=S}(s.resultLabel!==void 0||s.resultLabelEn!==void 0)&&(b||ce(t,`--result-label gibt es nur bei Ergebnissen mit Wert (${y}) \u2014 ${w}.`),g.label=uG(t,s,g.label)),(s.fields?.length??0)>0&&(f!=="record"&&ce(t,`--field gibt es nur beim Ergebnistyp record (Erfassung) \u2014 hier: ${f} (${$r[f].label.de}).`),g.fields=s.fields.map(S=>sG(S,e,n))),(s.options?.length??0)>0&&(f!=="choice"&&ce(t,`--option gibt es nur beim Ergebnistyp choice (Auswahl) \u2014 hier: ${f} (${$r[f].label.de}).`),g.options=s.options.map(oG)),s.textRequired!==void 0&&(f==="freetext"&&ce(t,"--text-required/--no-text-required gibt es beim Freitext nicht \u2014 sein Text ist immer Pflicht."),s.textRequired?g.textRequired=!0:delete g.textRequired),s.chat!==void 0&&(g.chat=pG(s.chat)),s.files===!0?g.files=!0:s.files===!1&&delete g.files,g.files===!0&&!Ui(g)&&(s.files===!0&&ce(t,`--files gibt es nur bei freetext, recommendation oder choice ohne --writes \u2014 hier: ${f}${g.writes!==void 0?" mit --writes":""}.`),delete g.files,a.push("result.files")),l.result=g}}if(s.clearWhen&&(l.when===void 0&&l.onConditionReturn===void 0&&ce(t,`Aufgabe \u201E${r}" hat keine Bedingung \u2014 --clear-when hat nichts zu entfernen.`),delete l.when,delete l.onConditionReturn),s.when!==void 0&&(l.when=un(e,n,"--when",s.when)),s.onConditionReturn!==void 0&&(BP.includes(s.onConditionReturn)||ce(t,`--on-condition-return \u201E${s.onConditionReturn}" ist unbekannt \u2014 erlaubt: ${BP.join(", ")}.`),l.when===void 0&&ce(t,"--on-condition-return braucht eine Bedingung (--when)."),l.onConditionReturn=s.onConditionReturn),s.clearReads&&(l.reads===void 0&&ce(t,`Aufgabe \u201E${r}" liest keine Felder \u2014 --clear-reads hat nichts zu entfernen.`),delete l.reads),s.reads!==void 0&&(l.reads=pw(s.reads,"--reads").map(f=>un(e,n,"--reads",f))),s.clearDocuments&&(l.documents===void 0&&ce(t,`Aufgabe \u201E${r}" verweist auf keine Dokumente \u2014 --clear-documents hat nichts zu entfernen.`),delete l.documents),s.documents!==void 0&&(l.documents=pw(s.documents,"--documents").map(f=>{try{return V_(f)}catch(h){fs(e,n,"--documents",f,h instanceof Error?h.message:String(h))}})),s.locksEvidence&&s.clearLocksEvidence&&ce(t,"--locks-evidence und --clear-locks-evidence schlie\xDFen sich aus."),s.clearLocksEvidence&&(l.locksEvidence===void 0&&ce(t,`Aufgabe \u201E${r}" sperrt keine Belege \u2014 --clear-locks-evidence hat nichts zu entfernen.`),delete l.locksEvidence),s.locksEvidence&&(l.locksEvidence=!0),s.clearDescription&&(l.description===void 0&&ce(t,`Aufgabe \u201E${r}" hat keine Beschreibung \u2014 --clear-description hat nichts zu entfernen.`),delete l.description),s.description!==void 0){let f=s.description.trim();f||ce(t,"--description darf nicht leer sein (entfernen mit --clear-description)."),l.description={de:f,en:s.descriptionEn?.trim()||f}}else if(s.descriptionEn!==void 0){l.description===void 0&&ce(t,"--description-en braucht --description.");let f=s.descriptionEn.trim();f||ce(t,"--description-en darf nicht leer sein."),l.description={...l.description,en:f}}if(s.clearOptional&&((s.optional!==void 0||s.optionalEn!==void 0)&&ce(t,"--clear-optional schlie\xDFt --optional und --optional-en aus."),l.optional===void 0&&ce(t,`Aufgabe \u201E${r}" ist nicht optional \u2014 --clear-optional hat nichts zu entfernen.`),delete l.optional),s.optional!==void 0){let f=s.optional.trim();f||ce(t,"--optional braucht die Worte des Knopfs (z. B. \u201EKeine Einsch\xE4tzung abgeben\u201C)."),l.optional={skipLabel:{de:f,en:s.optionalEn?.trim()||f}}}else if(s.optionalEn!==void 0){l.optional===void 0&&ce(t,"--optional-en braucht --optional.");let f=s.optionalEn.trim();f||ce(t,"--optional-en darf nicht leer sein."),l.optional={skipLabel:{...l.optional.skipLabel,en:f}}}if(s.clearAppointment&&((s.appointmentOf!==void 0||s.dueDaysAfterEnd!==void 0)&&ce(t,"--clear-appointment schlie\xDFt --appointment-of und --due-days-after-end aus."),l.appointment===void 0&&ce(t,`Aufgabe \u201E${r}" ist keine Terminaufgabe \u2014 --clear-appointment hat nichts zu entfernen.`),delete l.appointment),s.appointmentOf!==void 0||s.dueDaysAfterEnd!==void 0){let f=s.appointmentOf?.trim()??l.appointment?.of;f||ce(t,"--due-days-after-end braucht --appointment-of (die Aufgabe, die den Termin bucht).");let h=s.dueDaysAfterEnd?.trim();h!==void 0&&!/^\d+$/.test(h)&&ce(t,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(s.dueDaysAfterEnd)}.`);let g=h!==void 0?Number(h):l.appointment?.dueDaysAfterEnd;g===void 0&&ce(t,`--due-days-after-end ist eine ganze Zahl \u2265 0 (Tage nach dem Terminende), erhalten ${JSON.stringify(s.dueDaysAfterEnd)}.`),l.appointment={of:f,dueDaysAfterEnd:g}}let u=s.familyRequestFields!==void 0||s.familyRequestFrom!==void 0;if(gt(t,s,"familyRequestFields","familyRequestFrom","--family-request-fields","--family-request-from"),s.clearFamilyRequest&&(u&&ce(t,"--clear-family-request schlie\xDFt die \xFCbrigen --family-request-*-Flags aus."),l.familyRequest===void 0&&ce(t,`Aufgabe \u201E${r}" fordert nichts bei der Familie an \u2014 --clear-family-request hat nichts zu entfernen.`),delete l.familyRequest),s.familyRequestFields!==void 0){let f=pw(s.familyRequestFields,"--family-request-fields").map(h=>un(e,n,"--family-request-fields",h));l.familyRequest={fields:f}}return s.familyRequestFrom!==void 0&&(l.familyRequest={from:un(e,n,"--family-request-from",s.familyRequestFrom)}),{next:hG(l),dropped:a}}o(VP,"applyFlags");var mG=["key","kind","title","description","assign","params","blocks","result","when","onConditionReturn","reads","locksEvidence","documents","familyRequest","optional","appointment"];function hG(t){let e=t,n={};for(let r of mG)e[r]!==void 0&&(n[r]=e[r]);for(let[r,i]of Object.entries(e))!(r in n)&&i!==void 0&&(n[r]=i);return n}o(hG,"normalizeOrder");var gG=[["kind",t=>t.kind],["title",t=>t.title],["description",t=>t.description],["assign.group",t=>t.assign?.group],["params.dueInDays",t=>t.params?.dueInDays],["blocks",t=>t.blocks?{...t.blocks}:void 0],["result",t=>t.result],["when",t=>t.when],["onConditionReturn",t=>t.onConditionReturn],["reads",t=>t.reads],["locksEvidence",t=>t.locksEvidence],["documents",t=>t.documents],["familyRequest",t=>t.familyRequest],["optional",t=>t.optional],["appointment",t=>t.appointment]];function gw(t,e){let n=[];for(let[r,i]of gG){let s=t?i(t):void 0,a=e?i(e):void 0;JSON.stringify(s)!==JSON.stringify(a)&&n.push({field:r,before:s,after:a})}return n}o(gw,"diffTemplates");function KP(t,e,n,r){let i=hw(t,e,"add");n.trim()||ce("add","--key darf nicht leer sein."),(i.tasks??[]).find(d=>d.key===n)&&ce("add",`Knoten \u201E${e}" hat schon eine Aufgabe \u201E${n}" \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}=VP("add",gr(t),e,n,null,r);return i.tasks=[...i.tasks??[],a],{bundle:t,nodeId:e,key:n,before:null,after:a,changes:gw(null,a),dropped:l}}o(KP,"addNodeTask");function UP(t,e,n,r){let i=hw(t,e,"set"),s=i.tasks??[],a=s.findIndex(f=>f.key===n);a<0&&ce("set",`Knoten \u201E${e}" hat keine Aufgabe \u201E${n}" (Aufgaben: ${s.map(f=>f.key).join(", ")||"keine"}).`);let l=s[a],{next:d,dropped:c}=VP("set",gr(t),e,n,l,r),u=gw(l,d);return u.length===0&&ce("set",`nichts zu \xE4ndern \u2014 die Optionen ergeben dieselbe Aufgabe \u201E${n}".`),i.tasks=s.map((f,h)=>h===a?d:f),{bundle:t,nodeId:e,key:n,before:structuredClone(l),after:d,changes:u,dropped:c}}o(UP,"setNodeTask");function yG(t,e,n){let r=[];for(let s of mw(t,"rm"))for(let a of Array.isArray(s.tasks)?s.tasks:[]){if(s.id===e&&a.key===n)continue;let l=a.blocks;l&&l.templateKey===n&&(l.node??s.id)===e&&r.push(`Aufgabe \u201E${a.key}" auf ${s.id} (blocks)`)}let i=mw(t,"rm").find(s=>s.id===e);for(let s of i?.optionalActions??[])Array.isArray(s.tasks)&&s.tasks.includes(n)&&r.push(`optionale Aktion \u201E${s.key??"?"}" auf ${e}`);return r}o(yG,"nodeTaskDependents");function jP(t,e,n){let r=hw(t,e,"rm"),i=r.tasks??[],s=i.find(d=>d.key===n);s||ce("rm",`Knoten \u201E${e}" hat keine Aufgabe \u201E${n}" (Aufgaben: ${i.map(d=>d.key).join(", ")||"keine"}).`);let a=yG(t,e,n);a.length>0&&ce("rm",`\u201E${n}" auf ${e} 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!==n);return l.length===0?delete r.tasks:r.tasks=l,{bundle:t,nodeId:e,key:n,before:s,after:null,changes:gw(s,null),dropped:[]}}o(jP,"removeNodeTask");function md(t){if(t===void 0)return"\u2014";if(typeof t=="string"||typeof t=="number")return String(t);let e=t;return e&&typeof e=="object"&&"de"in e&&"en"in e&&Object.keys(e).length===2?e.de===e.en?String(e.de):`${String(e.de)} | ${String(e.en)}`:JSON.stringify(t)}o(md,"renderTaskValue");var If=o(t=>({de:t,en:t}),"germanInBothLocales");function wG(t){let e=t.lastIndexOf(":"),n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(e<=0||n===""||r==="")throw new Error(`offer workflow node add: --on-edge "${t}" must be <fromNodeId>:<outcome>`);return{from:n,outcome:r}}o(wG,"parseEdge");function kG(t){let e={};for(let n of t){let r=n.indexOf("="),i=n.slice(0,r).trim(),s=n.slice(r+1).trim();if(r<=0||i===""||s==="")throw new Error(`offer workflow node add: --progress "${n}" must be <event>=<stateId>`);if(i in e)throw new Error(`offer workflow node add: --progress names "${i}" twice`);e[i]=s}return e}o(kG,"parseProgressPairs");function HP(t){if(!t)return{};let e={};for(let n of t.split(",")){let r=n.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed pair "${r}" (expected key:value)`);let s=r.slice(0,i).trim(),a=r.slice(i+1).trim().replace(/^["']|["']$/g,"");if(!s||!a)throw new Error(`offer workflow node: malformed pair "${r}" (empty key/value)`);e[s]=a}return e}o(HP,"parsePairs");function vG(t){let e=o(n=>n.replace(/^["']|["']$/g,""),"unquote");return t.split(",").map(n=>n.trim()).filter(n=>n.length>0).map(n=>{let{id:r,de:i,en:s}=VA(n);if(!r||!i||s===void 0||e(s)==="")throw new Error(`offer workflow node: malformed --decision-outcomes entry "${n}" (expected <id>:<Deutsch>:<English> \u2014 both languages are required)`);return{id:r,label:{de:e(i),en:e(s)}}})}o(vG,"parseDecisionOutcomes");function SG(t){if(!t)return[];let e=[];for(let n of t.split(",")){let r=n.trim();if(!r)continue;let i=r.indexOf(":");if(i<0)throw new Error(`offer workflow node: malformed --from "${r}" (expected <nodeId>:<outcome>)`);let s=r.slice(0,i).trim(),a=r.slice(i+1).trim();if(!s||!a)throw new Error(`offer workflow node: malformed --from "${r}" (empty nodeId/outcome)`);e.push({nodeId:s,outcome:a})}return e}o(SG,"parseJoinFrom");function Ww(t){return t.split(":").map(e=>e.trim())}o(Ww,"fields");function yw(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}o(yw,"parseIdList");function QP(t,e){if(t===void 0||t==="")return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new Error(`offer workflow node: malformed ${e} dueInDays "${t}" (expected a positive integer)`);return n}o(QP,"parseDueInDays");function YP(t,e){if(!e||e.length===0)return t;for(let n of e){let[r,i,...s]=Ww(n);if(!r||!i)throw new Error(`offer workflow node: malformed --task-blocks "${n}" (expected <taskKey>:<target>)`);let a=t.find(d=>d.key===r);if(a===void 0)throw new Error(`offer workflow node: --task-blocks "${n}" names task "${r}", which is not among the --task entries (${t.map(d=>d.key).join(", ")||"none"})`);let l=s.filter(d=>d.length>0);if(l.length>0)throw new Error(`offer workflow node: malformed --task-blocks "${n}" \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 t}o(YP,"applyTaskBlocks");function JP(t,e){if(!t)return[];let n=e!==void 0;if(n&&e!=="spawnRevision")throw new Error(`offer workflow node: --task-on-reject must be 'spawnRevision' (got "${e}")`);return t.map(r=>{let i=Ww(r),[s,a,l,d]=i;if(!s||!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=QP(i[4],"--task");return{key:s,kind:a,title:If(l),...d?{assign:{group:d}}:{},...c!==void 0?{params:{dueInDays:c}}:{}}}if(a==="approval"){let[,,,,c]=i,u={};return n&&(u.onReject="spawnRevision"),c&&(u.revisionGroup=c),{key:s,kind:a,title:If(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}")`)})}o(JP,"parseTasks");function ZP(t){return t?t.map(e=>{let[n,r,i,...s]=Ww(e),a=s.join(":");if(!n||!r||!i)throw new Error(`offer workflow node: malformed --artifact "${e}" (expected key:type:visibility:label)`);if(i!=="internal"&&i!=="external")throw new Error(`offer workflow node: --artifact "${e}" \u2014 visibility must be 'internal' | 'external' (got "${i}")`);return{key:n,type:r,visibility:i,...a?{label:If(a)}:{}}}):[]}o(ZP,"parseArtifacts");function GP(t){if(t===void 0)return;let e=t.split(":"),n=e[e.length-1],r=e.length>1&&/^\d+$/.test(n)?Number(n):void 0,i=r!==void 0?e.slice(0,-1).join(":"):t;if(!i)throw new Error(`offer workflow node: malformed --decision-as-task "${t}" (expected title[:dueInDays])`);return{title:If(i),...r!==void 0?{dueInDays:r}:{}}}o(GP,"parseDecisionAsTask");function xG(t){let e={};for(let n of t??[]){let r=n.indexOf("=");if(r<=0)throw new Error(`offer workflow node: malformed --literal "${n}" (expected <param>=<value>)`);let i=n.slice(0,r).trim(),s=n.slice(r+1);if(!i)throw new Error(`offer workflow node: malformed --literal "${n}" (empty parameter)`);e[i]=s==="true"?{literal:!0}:s==="false"?{literal:!1}:/^-?\d+(\.\d+)?$/.test(s.trim())?{literal:Number(s.trim())}:{literal:s}}return e}o(xG,"parseNotificationLiterals");function XP(t){if(t!==void 0){if(!/^\d+$/.test(t.trim()))throw new Error(`offer workflow node: malformed --deadline-days "${t}" (expected whole days, e.g. 14)`);return Number(t.trim())}}o(XP,"parseDeadlineDays");function AG(t){if(!t||t.length===0)return;let e={};for(let n of t){let r=n.indexOf("="),i=r>0?n.slice(0,r).trim():"",s=r>0?n.slice(r+1).trim():"";if(!i||!s)throw new Error(`offer workflow node: malformed --notification "${n}" (expected <event>=<templateId>)`);if(i in e)throw new Error(`offer workflow node: --notification names event "${i}" twice`);e[i]=s}return e}o(AG,"parseNotificationBindings");function WP(t,e){if(e==="true")return!0;if(e==="false")return!1;throw new Error(`offer workflow node: ${t} must be 'true' | 'false' (got "${e}")`)}o(WP,"parseBoolOption");function bw(t){if(t!==void 0){if(t==="true")return!0;if(t==="false")return!1;throw new Error(`offer workflow node: --flag-value must be 'true' | 'false' (got "${t}")`)}}o(bw,"parseFlagValue");function Fr(t,e,n=` \u2192 NOT written (fix validation errors)
|
|
431
|
+
`){let r=bn(t).filter(i=>i.severity==="error");if(r.length>0){for(let i of r)e.write(` \u2716 ${i.area}: ${i.message}
|
|
432
|
+
`);return e.write(n),1}return or(t),0}o(Fr,"validateAndWrite");var ww=class extends Re{static{o(this,"OfferWorkflowNodeListCommand")}static paths=[["offer","workflow","node","list"]];static usage=I.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 e=uw(_e(this.dir));return this.print(e,n=>n.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.reads.length>0?`${r.reads.length} Felder`:"\u2014",letters:r.notifications.map(i=>`${i.event}\u2192${i.templateId}${i.disabled?" (aus)":""}`).join(", ")||"\u2014"}))),0}},kw=class extends Re{static{o(this,"OfferWorkflowNodeAddCommand")}static paths=[["offer","workflow","node","add"]];static usage=I.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 (${Ef.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"});id=p.String("--id",{description:"Node 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)"});reads=p.String("--reads",{description:"review only: the entered fields a reviewer ticks, as addresses \u2014 '$node.form.admission.a,$node.form.admission.b' (without it the review ticks nothing)"});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>:<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, 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 (${Yi.join("|")}; default approved)`});terminalStatus=p.String("--terminal-status",{description:"end only: override the free-form terminalStatus ledger label"});terminationKind=p.String("--termination-kind",{description:"end only: process_ends|redirect_external (default process_ends)"});dataDecision=p.String("--data-decision",{description:"end only (required): commit|discard \u2014 keep or discard the application's data at this end"});role=p.String("--role",{description:"roleAssign only: role key granted (must be a declared manifest roleInstance)"});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)"});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 (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"});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 e=_e(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)");wf(e,{key:this.form,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{}})}let n=dP(e,{type:this.type,label:this.label,...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.id?{id:this.id}:{},...this.after?{after:this.after}:{},...this.onEdge!==void 0?{onEdge:wG(this.onEdge)}:{},...this.progress!==void 0?{progress:kG(this.progress)}:{},...this.reads!==void 0?{reads:this.reads.split(",").map(i=>i.trim()).filter(i=>i.length>0)}:{},outcomeTargets:HP(this.outcomes),...this.decisionOutcomes?{decisionOutcomes:vG(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.terminalStatus?{terminalStatus:this.terminalStatus}:{},...this.terminationKind?{terminationKind:this.terminationKind}:{},...this.dataDecision?{dataDecision:this.dataDecision}:{},...this.role?{role:this.role}:{},...this.mode?{mode:this.mode}:{},...this.person?{person:this.person}:{},...this.from?{joinFrom:SG(this.from)}:{},...this.article!==void 0?{article:this.article}:{},...this.reason!==void 0||this.reasonEn!==void 0?{reason:Je(this.reason,this.reasonEn,"offer workflow node add","--reason")}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.assignDecision?{assignDecision:this.assignDecision}:{},...this.commentRequired?{commentRequired:yw(this.commentRequired)}:{},...this.task?{tasks:YP(JP(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact?{artifacts:ZP(this.artifact)}:{},...GP(this.decisionAsTask)?{decisionAsTask:GP(this.decisionAsTask)}:{},...this.flagKey?{flagKey:this.flagKey}:{},...bw(this.flagValue)!==void 0?{flagValue:bw(this.flagValue)}:{},...this.assignTeam!==void 0?{assignTeam:this.assignTeam}:{},...this.engageTarget!==void 0?{engageTarget:this.engageTarget}:{},...this.engageContractFields!==void 0?{engageContractFields:this.engageContractFields}:{},...this.engageConfig!==void 0?{engageConfig:tN(this.engageConfig,"--engage-config")}:{},...this.title!==void 0?{titleDe:this.title}:{},...this.titleEn!==void 0?{titleEn:this.titleEn}:{},...this.dueInDays!==void 0?{dueInDays:QP(this.dueInDays,"--due-in-days")}:{},...this.require!==void 0?{requires:this.require}:{},...this.deadlineDays!==void 0?{deadlineDays:XP(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:AG(this.notification)}:{}});for(let i of n.warnings)this.context.stderr.write(` \u26A0 ${i}
|
|
433
|
+
`);let r=Fr(n.bundle,this.context.stderr);return r!==0?r:(this.print({added:n.nodeId,type:this.type,form:this.form,events:n.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)}},vw=class extends Re{static{o(this,"OfferWorkflowNodeSetCommand")}static paths=[["offer","workflow","node","set"]];static usage=I.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/article/traeger/condition); validate before write"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});id=p.String("--id",{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"});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: 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 (${Yi.join("|")})`});terminalStatus=p.String("--terminal-status",{description:"end only: override the terminalStatus ledger label"});terminationKind=p.String("--termination-kind",{description:"end only: process_ends|redirect_external"});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 (declared manifest roleInstance)"});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) only: signedUploadChecked (auf Papier, R\xFCcklauf gepr\xFCft) | eSignature (beim E-Signatur-Anbieter der Schule; adds assign.signingRecovery = the check 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)"});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'"});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).
|
|
434
|
+
\u2192 remove the node (offer workflow node rm) and add it again (offer workflow node add).
|
|
435
|
+
`),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.
|
|
436
|
+
`),1;let e=_e(this.dir),n=vP(e,{id:this.id,...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:HP(this.outcomes)}:{},...this.outcome!==void 0?{outcome:this.outcome}:{},...this.terminalStatus!==void 0?{terminalStatus:this.terminalStatus}:{},...this.terminationKind!==void 0?{terminationKind:this.terminationKind}:{},...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:WP("--confirm-issue",this.confirmIssue)}:{},...this.confirmTerms!==void 0?{confirmTerms:WP("--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:yw(this.commentRequired)}:{},...this.requiresOneOf!==void 0?{requiresOneOf:yw(this.requiresOneOf)}:{},...this.task!==void 0?{tasks:YP(JP(this.task,this.taskOnReject),this.taskBlocks)}:{},...this.artifact!==void 0?{artifacts:ZP(this.artifact)}:{},...this.flagKey!==void 0?{flagKey:this.flagKey}:{},...this.flagValue!==void 0?{flagValue:bw(this.flagValue)}:{},...this.deadlineDays!==void 0?{deadlineDays:XP(this.deadlineDays)}:{},...this.deadlineUntil!==void 0?{deadlineUntil:this.deadlineUntil}:{},...this.guestRole!==void 0?{guestRole:this.guestRole}:{},...this.settlement!==void 0?{settlement:this.settlement}:{},...this.article!==void 0?{article:this.article}:{},...this.traeger!==void 0?{traeger:this.traeger}:{},...this.condition!==void 0?{condition:this.condition}:{}}),r=Fr(n.bundle,this.context.stderr);return r!==0?r:(this.print({node:n.nodeId,changed:n.changed},i=>[{key:"node edited",value:i.node},{key:"changed",value:i.changed.join(", ")||"\u2014"}]),0)}},Sw=class extends Re{static{o(this,"OfferWorkflowNodeSetNotificationCommand")}static paths=[["offer","workflow","node","set-notification"]];static usage=I.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 e=xG(this.literal),n=_e(this.dir),r=iP(n,{id:this.node,event:this.event,templateId:this.template,...Object.keys(e).length>0?{args:e}:{},...this.disabled?{disabled:!0}:{}}),i=Fr(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},s=>[{key:s.replaced?"binding replaced":"binding added",value:`${s.node}.${s.event}`},{key:"letter",value:s.templateId},{key:"explicit args",value:Object.entries(s.args).map(([a,l])=>`${a}=${JSON.stringify(l.literal)}`).join(", ")||"\u2014 (all resolved automatically)"},{key:"state",value:s.disabled?"disabled":"active"}]),0)}},xw=class extends Re{static{o(this,"OfferWorkflowNodeClearNotificationCommand")}static paths=[["offer","workflow","node","clear-notification"]];static usage=I.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 e=oP(_e(this.dir),this.node,this.event),n=Fr(e.bundle,this.context.stderr,` \u2192 NOT written (this event's letter is required by the node type)
|
|
437
|
+
`);return n!==0?n:(this.print({node:e.nodeId,event:e.event,templateId:e.templateId},r=>[{key:"binding removed",value:`${r.node}.${r.event}`},{key:"was",value:r.templateId}]),0)}},eN="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.",zw="`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"+eN,$f=class extends Re{static{o(this,"NodeKeyListCommand")}writeKeyListEdit(e,n,r,i){let s;if(pd(this.context.stderr,e,[`nodes.${n}.${r}`],`${r} keys`,d=>(s=i(d),s.bundle))===null)return 1;let l=s;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 zP(t){if(t===void 0)return"\u2014 (default)";let e=t;return e.kind==="binding"?`binding ${xf(e.address,"binding")}`:e.kind==="literal"?`literal ${JSON.stringify(e.value)}`:"unset"}o(zP,"describeCell");var Aw=class extends Re{static{o(this,"OfferWorkflowNodeSetInputCommand")}static paths=[["offer","workflow","node","set-input"]];static usage=I.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 fields \u2014 add the field first). 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 e=xP({...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}),n,r;return pd(this.context.stderr,this.dir,[`nodes.${this.node}.inputs.${this.input}`,`node.${this.node}.input.${this.input}`],`input "${this.input}"`,s=>{let a=AP(s,this.node,this.input,e);return n=a.before,r=a.after,a.bundle})===null?1:(this.print({node:this.node,input:this.input,before:n??null,after:r??null},s=>[{key:"node",value:s.node},{key:"input",value:s.input},{key:"before",value:zP(s.before??void 0)},{key:"now",value:zP(s.after??void 0)}]),0)}};function tN(t,e){let n;try{n=bG(t,"utf8")}catch(r){throw new Error(`${e}: ${t} is not readable (${r instanceof Error?r.message:String(r)})`,{cause:r})}try{return JSON.parse(n)}catch(r){throw new Error(`${e}: ${t} is no JSON (${r instanceof Error?r.message:String(r)})`,{cause:r})}}o(tN,"readJsonFile");var Ew=class extends Re{static{o(this,"OfferWorkflowNodeSetEngageCommand")}static paths=[["offer","workflow","node","set-engage"]];static usage=I.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 e=tN(this.config,"--config");return pd(this.context.stderr,this.dir,[`nodes.${this.node}`],"engage mapping",r=>EP(r,this.node,e).bundle)===null?1:(this.print({node:this.node,config:this.config},r=>[{key:"node",value:r.node},{key:"mapping",value:r.config}]),0)}},hd=class extends $f{static{o(this,"NodeReadsCommand")}writeReadsEdit(e,n,r){return this.writeKeyListEdit(e,n,"reads",i=>sP(i,n,r))}},Rw=class extends hd{static{o(this,"OfferWorkflowNodeSetReadsCommand")}static paths=[["offer","workflow","node","set-reads"]];static usage=I.Usage({category:"Offer",description:"Replace the form fields a node reads before acting (readiness gate); validate before write",details:zw,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, review 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 e=no({address:this.address,from:this.from,field:this.field});if(this.clear&&e.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:e})}},Tw=class extends hd{static{o(this,"OfferWorkflowNodeAddReadsCommand")}static paths=[["offer","workflow","node","add-reads"]];static usage=I.Usage({category:"Offer",description:"Add form fields to a node's reads (addresses already read are kept); validate before write",details:zw,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, review 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 e=no({address:this.address,from:this.from,field:this.field});return this.writeReadsEdit(this.dir,this.node,{op:"add",addresses:e})}},Iw=class extends hd{static{o(this,"OfferWorkflowNodeRemoveReadsCommand")}static paths=[["offer","workflow","node","remove-reads"]];static usage=I.Usage({category:"Offer",description:"Remove form fields from a node's reads (an address it does not read fails); validate before write",details:zw,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 e=no({address:this.address,from:this.from,field:this.field});return this.writeReadsEdit(this.dir,this.node,{op:"remove",addresses:e})}},Hw="`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"+eN,gd=class extends $f{static{o(this,"NodeRequiresCommand")}writeRequiresEdit(e,n,r){return this.writeKeyListEdit(e,n,"requires",i=>aP(i,n,r))}},$w=class extends gd{static{o(this,"OfferWorkflowNodeSetRequiresCommand")}static paths=[["offer","workflow","node","set-requires"]];static usage=I.Usage({category:"Offer",description:"Replace the form fields a completenessCheck waits for; validate before write",details:Hw,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 e=no({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"set",addresses:e})}},_w=class extends gd{static{o(this,"OfferWorkflowNodeAddRequiresCommand")}static paths=[["offer","workflow","node","add-requires"]];static usage=I.Usage({category:"Offer",description:"Add form fields a completenessCheck waits for (addresses already required are kept); validate before write",details:Hw,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 e=no({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"add",addresses:e})}},Ow=class extends gd{static{o(this,"OfferWorkflowNodeRemoveRequiresCommand")}static paths=[["offer","workflow","node","remove-requires"]];static usage=I.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:Hw,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 e=no({address:this.address,from:this.from,field:this.field});return this.writeRequiresEdit(this.dir,this.node,{op:"remove",addresses:e})}},Qw=`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.
|
|
438
|
+
|
|
439
|
+
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>').
|
|
440
|
+
|
|
441
|
+
\`set\` changes only the fields it is given. Every write re-runs the real publish validators; only errors the edit INTRODUCES block it, errors the bundle already carried are printed as warnings. Removing a task is refused while another task's --blocks (or an optional action) still names it.`,_f=class extends Re{static{o(this,"NodeTaskCommand")}dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id carrying the task"});key=p.String("--key",{required:!0,description:"Task key (stable identity on that node)"});writeTaskEdit(e,n){let i=o(c=>new Set(bn(c).filter(u=>u.severity==="error").map(u=>u.message)),"errorsOf")(_e(this.dir)),s=e(_e(this.dir)),a=this.context.stderr,l=bn(s.bundle),d=l.filter(c=>c.severity==="error"&&!i.has(c.message));for(let c of l)c.severity==="error"&&i.has(c.message)?a.write(` \u26A0 vorbestehend, nicht durch diese \xC4nderung: ${c.area}: ${c.message}
|
|
442
|
+
`):c.severity==="warning"&&c.message.includes(`nodes.${s.nodeId}.tasks.${s.key}`)&&a.write(` \u26A0 ${c.area}: ${c.message}
|
|
443
|
+
`);for(let c of s.dropped)a.write(` \u26A0 ${c} entf\xE4llt \u2014 passt nicht mehr zur \xC4nderung
|
|
444
|
+
`);if(d.length>0){for(let c of d)a.write(` \u2716 ${c.area}: ${c.message}
|
|
445
|
+
`);return a.write(` \u2192 NOT written (fix the task)
|
|
446
|
+
`),1}return or(s.bundle),this.print({action:n,node:s.nodeId,key:s.key,before:s.before,after:s.after,changes:s.changes,dropped:s.dropped},c=>[{field:c.action,before:"",after:`${c.node} \xB7 ${c.key}`},...c.changes.map(u=>({field:u.field,before:md(u.before),after:md(u.after)}))]),0}},Of=class extends _f{static{o(this,"NodeTaskEditCommand")}kind=p.String("--kind",{description:"task|approval (add default: task)"});title=p.String("--title",{description:"German title (without --title-en it stands in for English too)"});titleEn=p.String("--title-en",{description:"English title"});team=p.String("--team",{description:"Permission-group key that holds the task (\u2192 assign.group)"});dueInDays=p.String("--due-in-days",{description:"SLA in days (\u2192 params.dueInDays)"});blocks=p.String("--blocks",{description:"Withheld target: <templateKey> (same node) or <nodeId>:<templateKey> (later node)"});clearBlocks=p.Boolean("--clear-blocks",!1,{description:"Remove the blocks edge"});result=p.String("--result",{description:"freetext|recommendation|choice|record|appointment"});option=p.Array("--option",{description:"choice only: key=Label or key=Label|LabelEn (repeatable, replaces the list)"});field=p.Array("--field",{description:"record only: one field as JSON {key,type:number|boolean|enum,label:{de,en},writes,min?,options?,suggest?:{kind:'form',address:'$node.<form>.admission.<export>'}|{kind:'siblingRank'},evidence?,evidenceFrom?} (repeatable, replaces the list)"});textRequired=p.Boolean("--text-required",{description:"recommendation/choice: text mandatory (--no-text-required: optional)"});chat=p.String("--chat",{description:"The chat the result is posted to (required for freetext|recommendation|choice): all | team:<group> | <authored channel key>"});duration=p.String("--duration",{description:"appointment only: default duration in minutes (prefills the Termin dialog)"});resultTitle=p.String("--result-title",{description:"appointment only: neutral Termin title \u2014 family letter + calendar file (German; without --result-title-en it stands in for English too)"});resultTitleEn=p.String("--result-title-en",{description:"appointment only: English Termin title"});clearResult=p.Boolean("--clear-result",!1,{description:"Remove the result declaration"});when=p.String("--when",{description:"Spawn condition: a boolean form export, by address \u2014 '$node.<formNode>.admission.<export>'"});onConditionReturn=p.String("--on-condition-return",{description:"respawn|stayClosed (required with --when)"});clearWhen=p.Boolean("--clear-when",!1,{description:"Remove --when and --on-condition-return"});reads=p.String("--reads",{description:"Evidence: form fields by address \u2014 '$node.<formNode>.admission.a,$node.<formNode>.admission.b' (replaces the list)"});clearReads=p.Boolean("--clear-reads",!1,{description:"Remove the reads list"});documents=p.String("--documents",{description:"Documents the task points at, shown as links under it: artifact:<own slot>, field:'$node.<formNode>.admission.<docRef field>', document:'$node.<node>.document' (comma-separated; replaces the list)"});clearDocuments=p.Boolean("--clear-documents",!1,{description:"Remove the documents list"});locksEvidence=p.Boolean("--locks-evidence",!1,{description:"Once decided, lock the evidence (reads + the fields behind --when) against corrections until the team reopens the task"});clearLocksEvidence=p.Boolean("--clear-locks-evidence",!1,{description:"Remove locksEvidence"});description=p.String("--description",{description:"Plain text under the title (German; without --description-en it stands in for English too) \u2014 never a checklist"});descriptionEn=p.String("--description-en",{description:"English description"});clearDescription=p.Boolean("--clear-description",!1,{description:"Remove the description"});familyRequestFields=p.String("--family-request-fields",{description:"Nachforderung: the task asks the family when the optional action spawns it, offering these form fields at the click \u2014 addresses '$node.<formNode>.admission.a,\u2026'; completes itself when the family sends \u2014 needs --due-in-days (excludes --family-request-from)"});familyRequestFrom=p.String("--family-request-from",{description:"Nachforderung: as --family-request-fields, offering every file field of this form instance \u2014 '$node.<formNode>.admission'"});clearFamilyRequest=p.Boolean("--clear-family-request",!1,{description:"Remove the family request"});writes=p.String("--writes",{description:"choice/pricedItem/reduction: the store value the result writes, by its full address \u2014 '$task.<this task key>.<key>' (required on pricedItem and reduction; a choice without it stays in the chat)"});prices=p.String("--prices",{description:"reduction only: the derived price it lowers \u2014 '$derived.<key>'"});item=p.String("--item",{description:"pricedItem only: the article it prices \u2014 its catalog key (billing_item_definitions.configKey, e.g. tuition)"});resultLabel=p.String("--result-label",{description:"choice/pricedItem/reduction: the name of the result's value (German; without --result-label-en it stands in for English too)"});resultLabelEn=p.String("--result-label-en",{description:"English name of the result's value"});files=p.Boolean("--files",{description:"freetext/recommendation/choice without --writes: the person may attach files to the result \u2014 text and files become one chat message (--no-files removes it)"});optional=p.String("--optional",{description:"OPTIONAL task: nothing waits for it; its holder may close it without a result with this button (German, e.g. \u201EKeine Einsch\xE4tzung abgeben\u201C; without --optional-en it stands in for English too)"});optionalEn=p.String("--optional-en",{description:"English words of the skip button"});clearOptional=p.Boolean("--clear-optional",!1,{description:"The task is owed again (removes optional)"});appointmentOf=p.String("--appointment-of",{description:"TERMINAUFGABE: the task of this node whose appointment this one is done at (its result is an appointment). The task then waits for the booking, is held by the appointment's host (chosen among --team) and is due --due-days-after-end days after the appointment ends"});dueDaysAfterEnd=p.String("--due-days-after-end",{description:"Terminaufgabe: days after the appointment's END until it is due (0\u201360; replaces --due-in-days)"});clearAppointment=p.Boolean("--clear-appointment",!1,{description:"The task is no Terminaufgabe any more (removes appointment)"});flags(){return{kind:this.kind,title:this.title,titleEn:this.titleEn,team:this.team,dueInDays:this.dueInDays,blocks:this.blocks,clearBlocks:this.clearBlocks,result:this.result,options:this.option,fields:this.field,writes:this.writes,prices:this.prices,item:this.item,resultLabel:this.resultLabel,resultLabelEn:this.resultLabelEn,textRequired:this.textRequired,chat:this.chat,duration:this.duration,resultTitle:this.resultTitle,resultTitleEn:this.resultTitleEn,clearResult:this.clearResult,when:this.when,onConditionReturn:this.onConditionReturn,clearWhen:this.clearWhen,reads:this.reads,clearReads:this.clearReads,documents:this.documents,clearDocuments:this.clearDocuments,locksEvidence:this.locksEvidence,clearLocksEvidence:this.clearLocksEvidence,description:this.description,descriptionEn:this.descriptionEn,clearDescription:this.clearDescription,familyRequestFields:this.familyRequestFields,familyRequestFrom:this.familyRequestFrom,clearFamilyRequest:this.clearFamilyRequest,files:this.files,optional:this.optional,optionalEn:this.optionalEn,clearOptional:this.clearOptional,appointmentOf:this.appointmentOf,dueDaysAfterEnd:this.dueDaysAfterEnd,clearAppointment:this.clearAppointment}}},Cw=class extends Of{static{o(this,"OfferWorkflowNodeTaskAddCommand")}static paths=[["offer","workflow","node","task","add"]];static usage=I.Usage({category:"Offer",description:"Add one composed task to a workflow node (result, blocks, condition, description); validate before write",details:Qw,examples:[["A recommendation that holds a later decision (reject/waitlist stay open)",'$0 offer workflow node task add --dir ./bundle --node reviewEingereicht --key einschaetzung --title "Einsch\xE4tzung abgeben" --team oeffentlichkeitsarbeit --due-in-days 3 --blocks aufnahme:decision --result recommendation --chat all'],["A conditional choice that holds the document",`$0 offer workflow node task add --dir ./bundle --node contract --key ermaessigung --title "Erm\xE4\xDFigung pr\xFCfen" --team finanzen --blocks prepareDocument --result choice --option voll=Voll --option halb=Halbiert --when '$node.form.admission.antragErmaessigung' --on-condition-return respawn`],["A reduction that lowers the derived tuition",`$0 offer workflow node task add --dir ./bundle --node reviewEingereicht --key reducedFee --title "Erm\xE4\xDFigung berechnen" --team finanzen --result reduction --writes '$task.reducedFee.reducedFee' --prices '$derived.schulgeld' --result-label "Einkommenserm\xE4\xDFigung" --result-label-en "Income-based reduction" --chat team:finanzen`]]});async execute(){return this.writeTaskEdit(e=>KP(e,this.node,this.key,this.flags()),"task added")}},Pw=class extends Of{static{o(this,"OfferWorkflowNodeTaskSetCommand")}static paths=[["offer","workflow","node","task","set"]];static usage=I.Usage({category:"Offer",description:"Change the given fields of one composed task; validate before write",details:Qw,examples:[["Make the text mandatory","$0 offer workflow node task set --dir ./bundle --node reviewEingereicht --key einschaetzung --text-required"],["Stop blocking","$0 offer workflow node task set --dir ./bundle --node reviewEingereicht --key einschaetzung --clear-blocks"]]});async execute(){return this.writeTaskEdit(e=>UP(e,this.node,this.key,this.flags()),"task changed")}},Nw=class extends _f{static{o(this,"OfferWorkflowNodeTaskRemoveCommand")}static paths=[["offer","workflow","node","task","rm"],["offer","workflow","node","task","remove"]];static usage=I.Usage({category:"Offer",description:"Remove one composed task (refused while another task blocks on it); validate before write",details:Qw,examples:[["Drop a task","$0 offer workflow node task rm --dir ./bundle --node formAnmeldung --key oeaEinschaetzung"]]});async execute(){return this.writeTaskEdit(e=>jP(e,this.node,this.key),"task removed")}},nN="An optional action is an entry under \u201EWeiteres\u201C in the cockpit: pressing it spawns the referenced tasks of the SAME node (`--tasks`, keys of `node.tasks`; author them first with `node task add`). Who gets a task is the task's own `--team`; `--trigger` only says who may press the entry. A spawned task holds the decision until it is done \u2014 unless the task is optional (`task add --optional \u2026`), then nothing waits for it. `--repeatable` lets a finished round run again. Internal tasks never write to the family.\n\n`set` creates the binding when it is new (`--label` and `--tasks` required) and otherwise changes only the fields it is given. `remove` is refused while the node's `requiresOneOf` names the key. Every write re-runs the real publish validators.",Cf=class extends Re{static{o(this,"NodeOptionalActionCommand")}dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Decision node id carrying the action"});key=p.String("--key",{required:!0,description:"Action key (stable identity on that node)"});writeActionEdit(e,n){let r=null;if(pd(this.context.stderr,this.dir,[`nodes.${this.node}.optionalActions`,`nodes.${this.node}.tasks`],"optional action",a=>(r=e(a),r.bundle))===null||r===null)return 1;let s=r;return this.print({action:n,node:s.nodeId,key:s.key,before:s.before,after:s.after},a=>[{field:a.action,before:"",after:`${a.node} \xB7 ${a.key}`},{field:"binding",before:md(a.before??void 0),after:md(a.after??void 0)}]),0}},Dw=class extends Cf{static{o(this,"OfferWorkflowNodeOptionalActionSetCommand")}static paths=[["offer","workflow","node","optional-action","set"]];static usage=I.Usage({category:"Offer",description:"Create or change one optional action (spawnTasks) of a decision node; validate before write",details:nN,examples:[["\u201EEinsch\xE4tzung einholen\u201C \u2014 the secretariat asks the management for an optional assessment",'$0 offer workflow node optional-action set --dir ./bundle --node aufnahme --key einschaetzung --label "Einsch\xE4tzung einholen" --label-en "Request an assessment" --tasks gfEinschaetzung --trigger bewerbungsteam --repeatable'],["Let another group press it","$0 offer workflow node optional-action set --dir ./bundle --node aufnahme --key einschaetzung --trigger sekretariat"]]});label=p.String("--label",{description:"Menu entry (German; without --label-en it stands in for English too)"});labelEn=p.String("--label-en",{description:"English menu entry"});description=p.String("--description",{description:"Explanation next to the entry (German; without --description-en it stands in for English too)"});descriptionEn=p.String("--description-en",{description:"English explanation"});clearDescription=p.Boolean("--clear-description",!1,{description:"Remove the explanation"});tasks=p.String("--tasks",{description:"Task keys of this node the press spawns: a,b (replaces the list)"});trigger=p.String("--trigger",{description:"Permission-group key that may press the entry (omitted: only the responsible person)"});clearTrigger=p.Boolean("--clear-trigger",!1,{description:"Remove --trigger"});repeatable=p.Boolean("--repeatable",{description:"A finished round may run again (--no-repeatable: once)"});async execute(){let e={label:this.label,labelEn:this.labelEn,description:this.description,descriptionEn:this.descriptionEn,clearDescription:this.clearDescription,tasks:this.tasks,trigger:this.trigger,clearTrigger:this.clearTrigger,repeatable:this.repeatable};return this.writeActionEdit(n=>IP(n,this.node,this.key,e),"optional action set")}},Fw=class extends Cf{static{o(this,"OfferWorkflowNodeOptionalActionRemoveCommand")}static paths=[["offer","workflow","node","optional-action","remove"],["offer","workflow","node","optional-action","rm"]];static usage=I.Usage({category:"Offer",description:"Remove one optional action of a decision node (refused while requiresOneOf names it); validate before write",details:nN,examples:[["Drop it","$0 offer workflow node optional-action remove --dir ./bundle --node aufnahme --key einschaetzung"]]});async execute(){return this.writeActionEdit(e=>$P(e,this.node,this.key),"optional action removed")}},Lw=class extends Re{static{o(this,"OfferWorkflowNodeRemoveCommand")}static paths=[["offer","workflow","node","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a workflow node + its progress entries (refused while an address names it); validate before write",details:"Predecessors are spliced onto the node's single successor and its progress states, columns and mappings go with it. While any address elsewhere names the node \u2014 its form instance, document, contract or payment, or a value one of its tasks writes \u2014 the removal is refused and every such place is listed (config path + address): edit those first. Nothing is dropped silently."});dir=p.String("--dir",{required:!0,description:"Bundle directory"});id=p.String("--id",{required:!0,description:"Node id to remove"});async execute(){let e=_e(this.dir),n=SP(e,this.id),r=Fr(n.bundle,this.context.stderr,` \u2192 NOT written (removal would break the graph)
|
|
447
|
+
`);return r!==0?r:(this.print({removed:this.id,states:n.removedStates},i=>[{key:"node removed",value:i.removed},{key:"progress states stripped",value:i.states.join(", ")||"\u2014"}]),0)}},Mw=class extends Re{static{o(this,"OfferWorkflowNodeReadsCommand")}static paths=[["offer","workflow","node","reads"]];static usage=I.Usage({category:"Offer",description:"What arrives at a node: every address it reads, with origin and producer",details:"The node's read list (`addressReadsOf` \u2014 the same list the publish gate, the runtime's declaration check and the topology hash use). Each read is either WRITTEN in one of the node's fields, or CARRIED by what it reads: the evidence (`when` / `reads`) of the task that writes a `$task` value, the sources of a `$derived` price, or the sources the price check prices at the node writing a reduction. `at` names the config field. Offline, read-only.",examples:[["What the contract reads","$0 offer workflow node reads --dir ./bundle --node contract"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});node=p.String("--node",{required:!0,description:"Node id"});async execute(){let e=ZC(_e(this.dir),this.node);return this.print(e,n=>n.map(r=>({address:r.address,origin:JC(r.origin),via:r.via,at:r.at,producer:r.producer}))),0}},qw=class extends Re{static{o(this,"OfferWorkflowShowCommand")}static paths=[["offer","workflow","show"]];static usage=I.Usage({category:"Offer",description:"Show the workflow graph (nodes + routing + progress states)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=_e(this.dir),n=uw(e),i=(e.manifest.progressLayout?.buses??[]).flatMap(a=>(a.states??[]).map(l=>l.id)),s=e.workflow?.progressWiring;return this.print({nodes:n,progressStates:i,wiringMappings:s?.mappings?.length??0},a=>a.nodes.map(l=>({id:l.id,type:l.type,outcomes:l.outcomes.join(", ")||"\u2014",next:l.next.map(d=>`${d.outcome}\u2192${d.target}`).join(", ")||"\u2014"}))),0}},Bw=class extends Re{static{o(this,"OfferWorkflowChannelsListCommand")}static paths=[["offer","workflow","channels","list"]];static usage=I.Usage({category:"Offer",description:"List the workflow's chat channels \u2014 derived per team (read-only) and authored defaults"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=OP(_e(this.dir));return this.print(e,n=>n.map(r=>({key:r.key,label:r.label,members:r.members.join(" + "),source:r.source==="derived"?"automatisch je beteiligtem Team":"Standardkanal"}))),0}},Vw=class extends Re{static{o(this,"OfferWorkflowChannelsAddCommand")}static paths=[["offer","workflow","channels","add"]];static usage=I.Usage({category:"Offer",description:"Add (or, with --key of an existing one, replace) an authored default chat channel; validate before write",details:"Members are permission-group keys (`--team bewerbungsteam`, repeatable; `team:` prefix optional). Without --key a key is minted from the label ONCE; pass --key of an existing channel to rename or re-staff it in place (a rename never duplicates). A single team the process already assigns is refused \u2014 it has its channel automatically ([channels/duplicatesDerived]). Whether each team exists in the tenant is checked at `offer apply --publish`.",examples:[["A combined channel for the two deciding teams",'$0 offer workflow channels add --dir ./bundle --label "Bewerbungsteam + Schulleitung" --label-en "Admissions team + school leadership" --team bewerbungsteam --team schulleitung'],["Rename it, keeping its identity",'$0 offer workflow channels add --dir ./bundle --key bewerbungsteam-schulleitung --label "Aufnahme" --label-en "Admissions" --team bewerbungsteam --team schulleitung']]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});label=p.String("--label",{description:"Tab label in the cockpit chat, German (required for a new channel)"});labelEn=p.String("--label-en",{description:"Tab label in English (required for a new channel)"});team=p.Array("--team",{required:!0,description:"Permission-group key of a member team (repeatable)"});key=p.String("--key",{description:"Stable key \u2014 omit to mint one from the German label"});async execute(){let e=CP(_e(this.dir),{...this.key!==void 0?{key:this.key}:{},...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},teams:this.team}),n=Fr(e.bundle,this.context.stderr);return n!==0?n:(this.print({...e.channel,replaced:e.replaced},r=>[{key:r.replaced?"channel replaced":"channel added",value:r.key},{key:"label",value:Fe(r.label)},{key:"members",value:r.members.join(" + ")}]),0)}},Kw=class extends Re{static{o(this,"OfferWorkflowChannelsRemoveCommand")}static paths=[["offer","workflow","channels","rm"],["offer","workflow","channels","remove"]];static usage=I.Usage({category:"Offer",description:"Remove an authored default chat channel by key; validate before write",details:"Only authored channels can be removed. Applications already started keep the channels of the version they pinned; the removal applies from the next published version on.",examples:[["Drop a default channel","$0 offer workflow channels rm --dir ./bundle --key bewerbungsteam-schulleitung"]]});dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"Key of the authored channel"});async execute(){let e=PP(_e(this.dir),this.key),n=Fr(e.bundle,this.context.stderr);return n!==0?n:(this.print(e.removed,r=>[{key:"channel removed",value:r.key},{key:"was",value:`${Fe(r.label)} (${r.members.join(" + ")})`}]),0)}},Uw=class extends Re{static{o(this,"OfferWorkflowStaffInputListCommand")}static paths=[["offer","workflow","staff-input","list"]];static usage=I.Usage({category:"Offer",description:"List the workflow's staff inputs (values staff set at \u201E+ Bewerbung\u201C, read as $env.staffInput.<key>)"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=FP(_e(this.dir));return this.print(e,n=>n.map(r=>({key:r.key,type:r.type,label:Fe(r.label),reads:r.reads}))),0}},jw=class extends Re{static{o(this,"OfferWorkflowStaffInputSetCommand")}static paths=[["offer","workflow","staff-input","set"]];static usage=I.Usage({category:"Offer",description:"Declare a staff input (or relabel the one with this key); validate before write",details:"A staff input is a checkbox (type boolean) staff tick when they start an application \u2014 in the cockpit (\u201E+ Bewerbung\u201C), at a lead conversion, or with `applications start-test --staff-input key=\u2026`. Every staff start must set every declared input; a self-service start records false. An `if` node reads it as $env.staffInput.<key>. A SmartForm or document cannot read it ([address/staffInputConditionOnly]). Rules: [staffInput/*].",examples:[["Declare the staff-application checkbox",'$0 offer workflow staff-input set staffApplication --dir ./bundle --label "Mitarbeiterbewerbung" --label-en "Staff application"'],["Re-translate it, keeping its key",'$0 offer workflow staff-input set staffApplication --dir ./bundle --label-en "Employee application"']]});key=p.String({required:!0,name:"key"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});label=p.String("--label,--label-de",{description:"Checkbox label, German (required for a new input)"});labelEn=p.String("--label-en",{description:"Checkbox label, English (required for a new input)"});async execute(){let e=LP(_e(this.dir),{key:this.key,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{}}),n=Fr(e.bundle,this.context.stderr);return n!==0?n:(this.print({...e.input,replaced:e.replaced},r=>[{key:r.replaced?"staff input replaced":"staff input added",value:r.key},{key:"type",value:r.type},{key:"label",value:Fe(r.label)},{key:"reads as",value:`$env.staffInput.${r.key}`}]),0)}},Gw=class extends Re{static{o(this,"OfferWorkflowStaffInputRemoveCommand")}static paths=[["offer","workflow","staff-input","remove"],["offer","workflow","staff-input","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a staff input by key; validate before write",details:"Refused by the gate ([if/condition]) while an if node's condition still reads it \u2014 change or remove that node first. Applications already started keep the inputs of the version they pinned.",examples:[["Drop the staff-application checkbox","$0 offer workflow staff-input remove staffApplication --dir ./bundle"]]});key=p.String({required:!0,name:"key"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=MP(_e(this.dir),this.key),n=Fr(e.bundle,this.context.stderr);return n!==0?n:(this.print(e.removed,r=>[{key:"staff input removed",value:r.key},{key:"was",value:Fe(r.label)}]),0)}},rN=[ww,kw,vw,Sw,xw,Rw,Aw,Ew,Tw,Iw,$w,_w,Ow,Cw,Pw,Nw,Dw,Fw,Lw,Mw,qw,Bw,Vw,Kw,Uw,jw,Gw];var io=class extends So{static{o(this,"ManifestMutationCommand")}},Yw=class extends io{static{o(this,"OfferManifestSetCommand")}static paths=[["offer","manifest","set"]];static usage=I.Usage({category:"Offer",description:"Set manifest meta: applicant-mode/signature-level/window/capacity/selection"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});applicantMode=p.String("--applicant-mode",{description:Yb.join("|")});signatureLevel=p.String("--signature-level",{description:Jb.join("|")});windowStart=p.String("--window-start",{description:"bewerbungsfenster start (ISO date)"});windowEnd=p.String("--window-end",{description:"bewerbungsfenster end (ISO date)"});capacity=p.String("--capacity",{description:"Total seats (number)"});selectionRelease=p.String("--selection-release",{description:`selection: ${Zb.join("|")}`});selectionWaitlistOrder=p.String("--selection-waitlist-order",{description:`selection: ${Xb.join("|")}`});selectionAutoPromote=p.Boolean("--selection-auto-promote",{description:"selection: auto-promote on vacancy"});selectionDeadline=p.String("--selection-deadline",{description:'selection: batch Stichtag (ISO date; "" clears)'});sortOrder=p.String("--sort-order",{description:`Display order among the unit's offers, lower = first ("" clears)`});async execute(){let e=_e(this.dir);if(this.sortOrder!==void 0)if(this.sortOrder==="")delete e.index.sortOrder;else{let r=Number(this.sortOrder);if(!Number.isFinite(r)||r<0)throw new Error(`offer manifest set: --sort-order must be a non-negative number, got "${this.sortOrder}"`);e.index.sortOrder=r}JO(e,{...this.applicantMode!==void 0?{applicantMode:this.applicantMode}:{},...this.signatureLevel!==void 0?{signatureLevel:this.signatureLevel}:{},...this.windowStart!==void 0?{windowStart:this.windowStart}:{},...this.windowEnd!==void 0?{windowEnd:this.windowEnd}:{},...this.capacity!==void 0?{capacity:Number(this.capacity)}:{},...this.selectionRelease!==void 0?{selectionRelease:this.selectionRelease}:{},...this.selectionWaitlistOrder!==void 0?{selectionWaitlistOrder:this.selectionWaitlistOrder}:{},...this.selectionAutoPromote!==void 0?{selectionAutoPromote:this.selectionAutoPromote}:{},...this.selectionDeadline!==void 0?{selectionDeadline:this.selectionDeadline}:{}});let n=hr(e,"offer manifest");return this.print({updated:!0},()=>[{key:"manifest",value:"updated"}]),this.warn(n),0}},Pf=class extends io{static{o(this,"RoleWriteCommand")}dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"roleInstance key"});label=p.String("--label",{description:"Display label, German (required on add)"});labelEn=p.String("--label-en",{description:"Display label, English (required on add; on set, alone it re-translates the current German)"});customRoleId=p.String("--custom-role-id",{description:"Tenant custom-role this slot binds"});min=p.String("--min",{description:"cardinality min"});max=p.String("--max",{description:"cardinality max"});required=p.Boolean("--required",{description:"Required (or --no-required)"});legallyRelevant=p.Boolean("--legally-relevant",{description:"flag: legally relevant"});canSign=p.Boolean("--can-sign",{description:"flag: can sign contract"});requiresEvidence=p.Boolean("--requires-evidence",{description:"flag: requires evidence"});roleOpts(){return{key:this.key,...this.label!==void 0?{label:this.label}:{},...this.labelEn!==void 0?{labelEn:this.labelEn}:{},...this.customRoleId!==void 0?{customRoleId:this.customRoleId}:{},...this.min!==void 0?{min:Number(this.min)}:{},...this.max!==void 0?{max:Number(this.max)}:{},...this.required!==void 0?{required:this.required}:{},...this.legallyRelevant!==void 0?{legallyRelevant:this.legallyRelevant}:{},...this.canSign!==void 0?{canSignContract:this.canSign}:{},...this.requiresEvidence!==void 0?{requiresEvidence:this.requiresEvidence}:{}}}},Jw=class extends Pf{static{o(this,"OfferRoleAddCommand")}static paths=[["offer","role","add"]];static usage=I.Usage({category:"Offer",description:"Add a roleInstance to the manifest"});async execute(){let e=_e(this.dir);ZO(e,this.roleOpts());let n=hr(e,"offer manifest");return this.print({role:this.key},r=>[{key:"role added",value:r.role}]),this.warn(n),0}},Zw=class extends Pf{static{o(this,"OfferRoleSetCommand")}static paths=[["offer","role","set"]];static usage=I.Usage({category:"Offer",description:"Update a roleInstance"});async execute(){let e=_e(this.dir);XO(e,this.roleOpts());let n=hr(e,"offer manifest");return this.print({role:this.key},r=>[{key:"role updated",value:r.role}]),this.warn(n),0}},Xw=class extends io{static{o(this,"OfferRoleRemoveCommand")}static paths=[["offer","role","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a roleInstance from the manifest"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"roleInstance key to remove"});async execute(){let e=_e(this.dir);eC(e,this.key);let n=hr(e,"offer manifest");return this.print({removed:this.key},r=>[{key:"role removed",value:r.removed}]),this.warn(n),0}},ek=class extends Re{static{o(this,"OfferRoleListCommand")}static paths=[["offer","role","list"]];static usage=I.Usage({category:"Offer",description:"List the manifest's roleInstances"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});async execute(){let e=gf(_e(this.dir));return this.print(e,n=>n.length===0?[{key:"(none)",label:"",labelEn:"",customRoleId:"",cardinality:"",required:"",flags:""}]:n.map(r=>({key:r.key,label:r.label.de,labelEn:r.label.en,customRoleId:r.customRoleId,cardinality:r.cardinality,required:r.required?"yes":"",flags:r.flags}))),0}},tk=class extends io{static{o(this,"OfferLeistungAddCommand")}static paths=[["offer","leistung","add"]];static usage=I.Usage({category:"Offer",description:"Add a leistung to the manifest"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"leistung key"});label=p.String("--label",{required:!0,description:"Display label, German"});labelEn=p.String("--label-en",{required:!0,description:"Display label, English"});selectable=p.Boolean("--selectable-by-applicant",{description:"Applicant may select it"});assigned=p.Boolean("--assigned-by-provider",{description:"Provider assigns it"});async execute(){let e=_e(this.dir);tC(e,{key:this.key,label:this.label,labelEn:this.labelEn,...this.selectable!==void 0?{selectableByApplicant:this.selectable}:{},...this.assigned!==void 0?{assignedByProvider:this.assigned}:{}});let n=hr(e,"offer manifest");return this.print({leistung:this.key},r=>[{key:"leistung added",value:r.leistung}]),this.warn(n),0}},nk=class extends io{static{o(this,"OfferLeistungRemoveCommand")}static paths=[["offer","leistung","rm"]];static usage=I.Usage({category:"Offer",description:"Remove a leistung from the manifest"});dir=p.String("--dir",{required:!0,description:"Bundle directory"});key=p.String("--key",{required:!0,description:"leistung key to remove"});async execute(){let e=_e(this.dir);nC(e,this.key);let n=hr(e,"offer manifest");return this.print({removed:this.key},r=>[{key:"leistung removed",value:r.removed}]),this.warn(n),0}},iN=[Yw,Jw,Zw,Xw,ek,tk,nk];import{spawnSync as EG}from"node:child_process";import{existsSync as RG}from"node:fs";import oN from"node:path";var TG=o(t=>new Promise(e=>setTimeout(e,t)),"sleep");function IG(){let t=process.cwd();for(;;){if(RG(oN.join(t,"convex")))return t;let e=oN.dirname(t);if(e===t)throw new Error("plexus seed: no Convex project found above the current directory \u2014 run this from inside the worktree (e.g. the app/ dir).");t=e}}o(IG,"findConvexProjectDir");function sN(t,e,n=!1){let r=["convex","run",t];e!==void 0&&r.push(e),n&&r.push("--push");let i=EG("npx",r,{cwd:IG(),encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(i.status!==0){let d=(i.stderr??"").trim();throw new Error(d||`convex run ${t} exited ${i.status}`)}let s=(i.stdout??"").trim();if(s==="null")return null;let a=s.indexOf("{"),l=s.lastIndexOf("}");if(a<0||l<a)throw new Error(`convex run ${t}: no JSON in output:
|
|
448
|
+
${s}`);return JSON.parse(s.slice(a,l+1))}o(sN,"convexRun");var rk=class extends Re{static{o(this,"SeedCommand")}static paths=[["seed"]];static usage=I.Usage({category:"Operations",description:"Kick off the destructive local reseed and poll its run marker to completion.",details:"Fires init/seed:kickoffSeed (returns immediately, holds a run-lock) and polls init/seed:seedStatus, printing live phase progress. Exit 0 on completed, 1 on failed. The client disconnect can no longer masquerade as a failure \u2014 the seed_runs marker is the only source of truth. Runs `convex run` in the current worktree (admin key), so invoke it from the app dir.",examples:[["Reseed the current worktree and wait","plexus seed"],["Fire and return without waiting","plexus seed --no-wait"],["Skip the applicant drive (fastest)","plexus seed --applicants none"],["One applicant per engine path","plexus seed --applicants minimal"],["Drive only specific test cases","plexus seed --only vera-klein,eva-abgeschlossen"]]});applicants=p.String("--applicants","full",{description:"Applicant drive scope (the ~69%-of-runtime phase): none | minimal | full (default full). none skips the drive; minimal drives one per engine path."});only=p.String("--only",{description:"Drive ONLY these applicants (comma-separated case names, e.g. vera-klein,eva-abgeschlossen). Overrides --applicants; unknown or ambiguous names fail loud server-side."});ifNeeded=p.Boolean("--if-needed",!1,{description:"Push current code, initialize an empty local database, or preserve its completed seed. Failed seeds require an explicit rebuild."});financeShowcase=p.String("--finance-showcase","full",{description:"Finance showcase fixtures: full (requires converter) | none."});wait=p.Boolean("--wait",!0,{description:"Poll to completion (default). --no-wait fires and returns."});pollSeconds=p.String("--poll-interval","5",{description:"Seconds between status polls (default 5)."});timeoutSeconds=p.String("--timeout","1200",{description:"Max seconds to wait before giving up polling (default 1200)."});async execute(){if(this.applicants!=="none"&&this.applicants!=="minimal"&&this.applicants!=="full")throw new Error(`Unknown --applicants '${this.applicants}' (expected none|minimal|full).`);if(this.financeShowcase!=="full"&&this.financeShowcase!=="none")throw new Error(`Unknown --finance-showcase '${this.financeShowcase}' (expected full|none).`);let e=(this.only??"").split(",").map(u=>u.trim()).filter(u=>u.length>0),n=Math.max(1,Number.parseInt(this.pollSeconds,10)||5)*1e3,r=Math.max(1,Number.parseInt(this.timeoutSeconds,10)||1200)*1e3,i=this.context.stdout,s,a={};e.length>0?a.applicantKeys=e:a.applicants=this.applicants,a.financeShowcase=this.financeShowcase,this.ifNeeded&&(a.ifNeeded=!0);try{s=sN("init/seed:kickoffSeed",JSON.stringify(a),this.ifNeeded)}catch(u){return this.context.stderr.write(`plexus seed: could not start \u2014 ${Dn(u)}
|
|
449
|
+
`),1}if(s.disposition==="ready")return i.write(`Seed already completed (runId=${s.runId}); preserving local data. Use pnpm seed or pnpm seed:lean for an explicit rebuild.
|
|
450
|
+
`),0;let l=e.length>0?`only=${e.join(",")}`:`applicants=${this.applicants}`;if(i.write(`Seed ${s.disposition==="running"?"already running":"kicked off"} (${l}, runId=${s.runId}).
|
|
451
|
+
`),!this.wait)return this.print({started:!0,runId:s.runId,mode:s.mode},()=>[{started:"yes",runId:s.runId,mode:s.mode}],["started","runId","mode"]),0;let d=Date.now(),c="";for(;;){let u;try{u=sN("init/seed:seedStatus",JSON.stringify({runId:s.runId}))}catch{u=null}if(u&&u.phase&&u.phase!==c&&(c=u.phase,i.write(` \xB7 ${u.phase} (${Math.round(u.elapsedMs/1e3)}s)
|
|
452
|
+
`)),u&&u.status==="completed"){let f=Math.round(u.elapsedMs/1e3);return this.print({status:"completed",mode:u.mode,totalSeconds:f,accounts:u.accounts,applicants:u.applicants},()=>[{status:"completed",seconds:String(f),accounts:String(u.accounts),applicants:String(u.applicants)}],["status","seconds","accounts","applicants"]),0}if(u&&u.status==="failed")return this.context.stderr.write(`plexus seed: FAILED in phase "${u.phase??"?"}" after ${Math.round(u.elapsedMs/1e3)}s \u2014 ${u.error??"unknown error"}
|
|
453
|
+
`),1;if(Date.now()-d>r)return this.context.stderr.write(`plexus seed: timed out after ${Math.round(r/1e3)}s (seed may still be running \u2014 poll init/seed:seedStatus).
|
|
454
|
+
`),1;await TG(n)}}},aN=[rk];import{readFile as Un,writeFile as yd}from"node:fs/promises";import ok from"node:path";var Nf=1,$G=/^([a-z0-9][a-z0-9-]*)@([1-9][0-9]*)$/;function lN(t,e){let n=typeof t=="string"?$G.exec(t.trim()):null;if(n===null)throw new Error(`${e}: erwartet "<key>@<revision>" (z. B. "school-contract@2"), erhalten ${JSON.stringify(t)}.`);return{key:n[1],revision:Number(n[2])}}o(lN,"parseRevisionReference");function ik(t){return{formatVersion:Nf,kind:"combined",id:t.id,key:t.key,revision:t.revision,status:t.status,expectedSourceRevision:t.sourceRevision,name:t.name,description:t.description,inputSchema:t.inputSchema,parts:t.parts.map(e=>({partKey:e.partKey,generator:`${e.key}@${e.revision}`,inputs:e.inputs.map(n=>({...n})),...e.when!==null?{when:e.when}:{}}))}}o(ik,"combinedFileOf");function dN(t,e){let n=_t(t,"Datei",e);if(n.formatVersion!==Nf)throw new Error(`${e}: formatVersion muss ${Nf} sein \u2014 exportieren Sie mit \`generator combined export\`.`);if(n.kind!=="combined")throw new Error(`${e}: kind muss "combined" sein \u2014 ein Dokument-Generator wird mit \`generator export\` / \`generator apply\` bearbeitet.`);if(typeof n.key!="string"||n.key.trim()==="")throw new Error(`${e}: key fehlt.`);if(n.id!==void 0&&typeof n.id!="string")throw new Error(`${e}: id muss ein String sein.`);if(n.id!==void 0&&typeof n.expectedSourceRevision!="number")throw new Error(`${e}: expectedSourceRevision fehlt \u2014 sie geh\xF6rt zur exportierten Revision (id).`);let r=_t(n.inputSchema,"inputSchema",e),i=pn(r.fields,"inputSchema.fields",e),s=pn(n.parts,"parts",e).map((a,l)=>{let d=`parts[${l}]`,c=_t(a,d,e);if(typeof c.partKey!="string")throw new Error(`${e}: ${d}.partKey fehlt.`);let u=lN(c.generator,`${e}: ${d}.generator`);if(c.when!==void 0&&typeof c.when!="string")throw new Error(`${e}: ${d}.when muss ein Ausdruck (String) sein.`);return{partKey:c.partKey,generator:`${u.key}@${u.revision}`,inputs:pn(c.inputs,`${d}.inputs`,e),...c.when!==void 0?{when:c.when}:{}}});return{formatVersion:Nf,kind:"combined",...n.id!==void 0?{id:n.id,expectedSourceRevision:n.expectedSourceRevision}:{},key:n.key.trim(),name:Zt(n.name,"name",e,"Generatornamen"),description:_G(n.description)?{de:"",en:""}:Zt(n.description,"description",e,"Beschreibungen"),inputSchema:{...r,fields:i},parts:s}}o(dN,"parseCombinedFile");function _G(t){if(t===void 0)return!0;if(typeof t!="object"||t===null)return!1;let e=t;return Object.keys(e).every(n=>n==="de"||n==="en")&&e.de===""&&e.en===""}o(_G,"isBlankText");function OG(t){return t.parts.map(e=>({partKey:e.partKey,generator:lN(e.generator,`parts.${e.partKey}.generator`),inputs:e.inputs,...e.when!==void 0?{when:e.when}:{}}))}o(OG,"authoredParts");function CG(t,e){let n=ik(e),r=o(s=>Ue({inputSchema:s.inputSchema,parts:s.parts}),"declaration"),i=o(s=>Ue({name:s.name,description:s.description}),"texts");return{declaration:r(t)!==r(n),texts:i(t)!==i(n)}}o(CG,"combinedFileChanges");async function cN(t,e,n,r){let i=OG(r);if(r.id===void 0){let c=n.filter(f=>f.key===r.key).sort((f,h)=>h.revision-f.revision)[0];if(c!==void 0)throw new Error(`\u201E${r.key}\u201C gibt es schon (Revision ${c.revision}). Exportieren Sie die Revision, auf der Sie aufbauen (\`generator clone ${r.key}@${c.revision}\` f\xFCr einen neuen Entwurf, dann \`generator combined export\`), und speichern Sie diese Datei \u2014 eine Datei ohne id legt nur einen neuen Schl\xFCssel an.`);let{id:u}=await t.mutation(R.contractGenerators.createCombinedDraft,{client:e,key:r.key,name:r.name,description:r.description});try{let f=await t.mutation(R.contractGenerators.saveCombinedDraft,{client:e,id:u,expectedSourceRevision:0,inputSchema:r.inputSchema,parts:i});return{id:u,key:r.key,revision:1,outcome:"created",sourceRevision:f.sourceRevision}}catch(f){try{await t.mutation(R.contractGenerators.removeDraft,{client:e,id:u})}catch(h){throw new Error(`${f instanceof Error?f.message:String(f)}
|
|
455
|
+
(Der leere Entwurf ${u} konnte nicht entfernt werden: ${h instanceof Error?h.message:String(h)} \u2014 \`generator delete-draft ${u}\`.)`,{cause:h})}throw f}}let s=n.find(c=>c.id===r.id);if(s===void 0)throw new Error(`Die Revision ${r.id} gibt es in diesem Mandanten nicht \u2014 IDs geh\xF6ren zu ihrer Umgebung.`);if(s.kind!=="combined")throw new Error(`${s.key}@${s.revision} ist kein kombinierter Generator.`);if(s.key!==r.key)throw new Error(`Die Datei nennt key \u201E${r.key}\u201C, die Revision ${r.id} ist \u201E${s.key}@${s.revision}\u201C.`);let a=s,l=CG(r,a),d=a.sourceRevision;return l.declaration&&(d=(await t.mutation(R.contractGenerators.saveCombinedDraft,{client:e,id:a.id,expectedSourceRevision:r.expectedSourceRevision,inputSchema:r.inputSchema,parts:i})).sourceRevision),l.texts&&await t.mutation(R.contractGenerators.rename,{client:e,id:a.id,name:r.name,description:r.description}),{id:a.id,key:a.key,revision:a.revision,outcome:l.declaration?"saved":l.texts?"renamed":"unchanged",sourceRevision:d}}o(cN,"saveCombinedFile");var it=class extends V{static{o(this,"ResolverCommand")}async load(){let e=await this.caller(),n=this.requireTenant(e);return{caller:e,client:n,model:await e.query(R.contractGenerators.model,{client:n})}}find(e,n){let[r,i]=n.split("@",2),s=i===void 0?void 0:Number(i),a=e.resolvers.filter(l=>l.id===n||l.key===r&&(s===void 0||l.revision===s));if(a.length===0)throw new Error(`Contract generator "${n}" not found.`);return a.sort((l,d)=>d.revision-l.revision)[0]}};function uN(t,e,n){let r=`generator file ${e}`,i=t.name===void 0&&n!==void 0?n.name:Zt(t.name,"name",r,"Generatornamen"),s=t.description===void 0?n?.description??{de:"",en:""}:Zt(t.description,"description",r,"Beschreibungen");return{name:i,description:s}}o(uN,"resolverTexts");var sk=class extends it{static{o(this,"ResolverListCommand")}static paths=[["generator","list"]];static usage=I.Usage({category:"Contracts",description:"List contract generator revisions."});async execute(){let{model:e}=await this.load();return this.print(e.resolvers,n=>n.map(r=>({id:r.id,key:r.key,revision:String(r.revision),status:r.status,kind:r.kind,name:r.name.de,name_en:r.name.en,missing_anchors:r.signatureAnchors===null?"\u2014 (parts)":r.signatureAnchors.status==="read"?r.signatureAnchors.missing.join(" ")||"ok":{unpinned:"\u2014",unread:"unread",implementationMissing:"code missing",notDeclarable:"not declarable"}[r.signatureAnchors.status]})),["key","revision","status","kind","missing_anchors","name","name_en","id"]),0}},ak=class extends it{static{o(this,"ResolverShowCommand")}static paths=[["generator","show"]];reference=p.String({required:!0,name:"key[@revision]|id"});async execute(){let{model:e}=await this.load(),n=this.find(e,this.reference);return this.print({...n,usages:e.usages.filter(r=>r.contractResolverDefinitionId===n.id)}),0}},lk=class extends it{static{o(this,"ResolverImplementationsCommand")}static paths=[["generator","implementations"]];async execute(){let{model:e}=await this.load();return this.print(e.implementations,n=>n.map(r=>({key:r.key,name:r.name,checksum:r.checksum})),["key","name","checksum"]),0}},dk=class extends it{static{o(this,"ResolverCreateCommand")}static paths=[["generator","create"]];key=p.String("--key",{required:!0});name=p.String("--name",{required:!0,description:"Name (German)"});nameEn=p.String("--name-en",{required:!0,description:"Name (English) \u2014 every name is bilingual"});description=p.String("--description",{description:"Description (German); needs --description-en"});descriptionEn=p.String("--description-en",{description:"Description (English)"});implementation=p.String("--implementation",{description:"Copy an existing database implementation; omit for a blank generator"});contractTemplateId=p.String("--contract-template-id",{required:!0});config=p.String("--config",{description:"JSON config file"});async execute(){let{caller:e,client:n}=await this.load(),r=await e.mutation(R.contractGenerators.createDraft,{client:n,key:this.key,name:{de:this.name,en:this.nameEn},...this.description!==void 0||this.descriptionEn!==void 0?{description:{de:this.description??"",en:this.descriptionEn??""}}:{},...this.implementation===void 0?{}:{implementationKey:this.implementation},contractTemplateId:this.contractTemplateId,...this.config?{config:JSON.parse(await Un(this.config,"utf8"))}:{}});return this.print(r),0}},ck=class extends it{static{o(this,"ResolverUpdateCommand")}static paths=[["generator","update"]];reference=p.String({required:!0,name:"key[@revision]|id"});file=p.String("--file",{required:!0,description:'JSON with name / description ({ "de", "en" }), contractTemplateId, and config'});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference),s=JSON.parse(await Un(this.file,"utf8")),a=s.name!==void 0||s.description!==void 0?uN(s,this.file,i):null,d=s.config!==void 0||typeof s.contractTemplateId=="string"?await e.mutation(R.contractGenerators.updateDraft,{client:n,id:i.id,...s.config!==void 0?{config:s.config}:{},...typeof s.contractTemplateId=="string"?{contractTemplateId:s.contractTemplateId}:{}}):{id:i.id};return a!==null&&await e.mutation(R.contractGenerators.rename,{client:n,id:i.id,...a}),this.print(d),0}},oo=class extends it{static{o(this,"ResolverLifecycleCommand")}reference=p.String({required:!0,name:"key[@revision]|id"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);return this.print(await e.mutation(this.mutation,{client:n,id:i.id})),0}},uk=class extends oo{static{o(this,"ResolverSealCommand")}static paths=[["generator","seal"]];mutation=R.contractGenerators.seal},fk=class extends oo{static{o(this,"ResolverCloneCommand")}static paths=[["generator","clone"]];mutation=R.contractGenerators.cloneDraft},pk=class extends oo{static{o(this,"ResolverArchiveCommand")}static paths=[["generator","archive"]];mutation=R.contractGenerators.archive},mk=class extends oo{static{o(this,"ResolverRestoreCommand")}static paths=[["generator","restore"]];mutation=R.contractGenerators.restore},hk=class extends oo{static{o(this,"ResolverDeleteDraftCommand")}static paths=[["generator","delete-draft"]];mutation=R.contractGenerators.removeDraft},gk=class extends it{static{o(this,"ResolverTestCommand")}static paths=[["generator","test"]];reference=p.String({required:!0,name:"key[@revision]|id"});input=p.String("--input",{required:!0,description:"Input JSON file"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);return this.print(await e.query(R.contractGenerators.runPlayground,{client:n,id:i.id,input:JSON.parse(await Un(this.input,"utf8"))})),0}},yk=class extends it{static{o(this,"ResolverUsagesCommand")}static paths=[["generator","usages"]];reference=p.String({required:!0,name:"key[@revision]|id"});async execute(){let{model:e}=await this.load(),n=this.find(e,this.reference),r=e.usages.filter(i=>i.contractResolverDefinitionId===n.id);return this.print(r,i=>i.map(s=>({offer:`${s.offerKey}@${s.offerRevision}`,node:s.workflowNodeId,label:s.offerLabel.de})),["offer","node","label"]),0}},bk=class extends it{static{o(this,"ResolverRunsCommand")}static paths=[["generator","runs"]];static usage=I.Usage({category:"Contracts",description:"List contract generation runs with phase timings."});reference=p.String({required:!0,name:"key[@revision]|id"});limit=p.String("--limit","25",{description:"Maximum runs to show"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference),a=(await e.query(R.contractGenerators.listGenerationRuns,{client:n,id:i.id})).slice(0,Number(this.limit));return this.print(a,l=>l.map(d=>({status:d.status,file:d.document?.filename??"\u2014",total:d.durationMs===null?"\u2014":`${d.durationMs} ms`,render:d.timingsMs===null?"\u2014":`${d.timingsMs.render} ms`,convert:d.timingsMs===null?"\u2014":`${d.timingsMs.convert} ms`,store:d.timingsMs===null?"\u2014":`${d.timingsMs.store} ms`,error:d.error??""})),["status","file","total","render","convert","store","error"]),0}},wk=class extends it{static{o(this,"ResolverAssignCommand")}static paths=[["generator","assign"]];reference=p.String({required:!0,name:"key[@revision]|id"});offerVersionId=p.String("--offer-version-id",{required:!0});node=p.String("--node",{required:!0,description:"Id of the workflow node that uses the resolver"});prefill=p.String("--prefill",{description:"Prefill JSON file"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);return this.print(await e.mutation(R.contractGenerators.setUsage,{client:n,contractResolverDefinitionId:i.id,offerVersionId:this.offerVersionId,workflowNodeId:this.node,...this.prefill?{prefill:JSON.parse(await Un(this.prefill,"utf8"))}:{}})),0}},kk=class extends it{static{o(this,"ResolverExportCommand")}static paths=[["generator","export"]];reference=p.String({required:!0,name:"key[@revision]|id"});out=p.String("--out");async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);fN(i,"generator combined export");let s=await e.query(R.contractGeneratorAuthoring.source,{client:n,id:i.id});if(s.artifact===null)throw new Error(s.sourceMigrationRefusal??"The generator has no saved source.");let a=Dk({formatVersion:1,id:i.id,expectedSourceRevision:s.sourceRevision,source:s.artifact.source,billingItemDefinitionIds:i.billingItemDefinitionIds,grantTemplateIds:i.grantTemplateIds,scenarios:s.scenarios,feeGroups:s.feeGroups,key:i.key,name:i.name,description:i.description,implementationKey:i.implementationKey,contractTemplateId:i.contractTemplateId,config:i.config});return this.out?await yd(this.out,a,"utf8"):this.context.stdout.write(a),0}},vk=class extends it{static{o(this,"ResolverApplyCommand")}static paths=[["generator","apply"]];file=p.String({required:!0,name:"file"});async execute(){let e=JSON.parse(await Un(this.file,"utf8")),{caller:n,client:r,model:i}=await this.load(),s=String(e.key??"");if(typeof e.contractTemplateId!="string")throw new Error("Resolver file must contain contractTemplateId.");if(e.formatVersion!==1||typeof e.source!="string"||!Array.isArray(e.billingItemDefinitionIds)||!Array.isArray(e.grantTemplateIds)||!Array.isArray(e.scenarios))throw new Error("Export the generator again: formatVersion 1, source, article/grant manifests and reviewed scenarios are required.");let a=i.resolvers.find(f=>f.key===s&&f.status==="draft");if(a!==void 0&&(e.id!==a.id||e.expectedSourceRevision!==a.sourceRevision))throw new Error("The draft has changed. Export its current revision before applying edits.");let l=uN(e,this.file),d=a?.id??(await n.mutation(R.contractGenerators.createDraft,{client:r,key:s,...l,contractTemplateId:e.contractTemplateId,config:e.config??{}})).id;await n.mutation(R.contractGenerators.updateDraft,{client:r,id:d,...typeof e.contractTemplateId=="string"?{contractTemplateId:e.contractTemplateId}:{},config:e.config??{}}),await n.mutation(R.contractGenerators.rename,{client:r,id:d,...l});let c=await n.query(R.contractGeneratorAuthoring.source,{client:r,id:d}),u=await n.action(R.contractGeneratorAuthoringActions.saveSource,{client:r,id:d,expectedSourceRevision:c.sourceRevision,source:e.source,billingItemDefinitionIds:e.billingItemDefinitionIds,grantTemplateIds:e.grantTemplateIds,feeGroups:e.feeGroups??[]});if(u.diagnostics.length>0)throw new Error(u.diagnostics.join(`
|
|
456
|
+
`));return e.scenarios.length>0&&await n.mutation(R.contractGeneratorAuthoring.approveScenarios,{client:r,id:d,expectedSourceRevision:u.sourceRevision,artifactHash:u.artifactHash,scenarios:e.scenarios}),this.print({id:d,applied:!0,sourceRevision:u.sourceRevision,artifactHash:u.artifactHash,status:"draft"}),0}},Sk=class extends it{static{o(this,"ResolverScaffoldCommand")}static paths=[["generator","scaffold"]];key=p.String({required:!0,name:"implementation-key"});out=p.String("--out",{required:!0});async execute(){return await yd(this.out,`export default {
|
|
457
|
+
inputSchema: { fields: [] },
|
|
458
|
+
parties: [],
|
|
459
|
+
previewDocument(_config: unknown, _input: Record<string, unknown>) { return {}; },
|
|
460
|
+
signatureSpots(_config: unknown, _input: Record<string, unknown>) { return []; },
|
|
461
|
+
resolve(_config: unknown, _input: Record<string, unknown>) {
|
|
462
|
+
throw new Error("Implement the contract, articles, parties and payment allocation here.");
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
`,{encoding:"utf8",flag:"wx"}),this.print({created:this.out}),0}},Df=class extends V{static{o(this,"ContractTemplateCommand")}async contractTemplates(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.contractConfig.model,{client:n});return{caller:e,client:n,model:r}}},xk=class extends Df{static{o(this,"ResolverTemplateListCommand")}static paths=[["generator","template","list"]];static usage=I.Usage({category:"Contracts",description:"List contract templates and the DOCX attached to each."});async execute(){let{model:e}=await this.contractTemplates();return this.print(e.contractTemplates,n=>n.map(r=>({id:r.id,key:r.configKey??"\u2014",name:r.name.de,name_en:r.name.en,docx:r.documentFile?.filename??"\u2014 (kein DOCX)"})),["key","name","name_en","docx","id"]),0}},Ak=class extends Df{static{o(this,"ResolverTemplateUploadCommand")}static paths=[["generator","template","upload"]];static usage=I.Usage({category:"Contracts",description:"Create (or re-point) a contract template from a DOCX file and print its id. The template is found again by --key, never by its name."});key=p.String("--key",{required:!0,description:"Contract template key (kebab-case) \u2014 its stable identity; a rename never changes it"});name=p.String("--name",{required:!0,description:"Contract template name (German)"});nameEn=p.String("--name-en",{required:!0,description:"Contract template name (English) \u2014 every name is bilingual"});file=p.String("--file",{required:!0,description:"DOCX file to attach"});role=p.String("--role",{required:!0,description:"Leaf role key the document template is scoped to"});async execute(){let{caller:e,client:n,model:r}=await this.contractTemplates(),i=await Ai(this.file),s={de:this.name,en:this.nameEn},a=await ho(e,n,i,{name:s,role:this.role}),l=i.placeholders,d=r.contractTemplates.find(u=>u.configKey===this.key);if(d!==void 0&&d.name.de!==this.name)throw new Error(`generator template upload: Schl\xFCssel \u201E${this.key}\u201C geh\xF6rt der Vorlage \u201E${d.name.de}\u201C, nicht \u201E${this.name}\u201C. Anderen --key w\xE4hlen, oder die Vorlage zuerst umbenennen.`);let c=d?.id??(await e.mutation(R.contractConfig.createContractTemplate,{client:n,name:s,configKey:this.key})).id;return await e.mutation(R.contractConfig.updateContractTemplate,{client:n,id:c,name:s,documentTemplateId:a}),this.print({contractTemplateId:c,key:this.key,documentTemplateId:a,fileName:ok.basename(i.file),placeholders:l,reused:d!==void 0}),0}},Ff=class extends V{static{o(this,"ResolverSetupCommand")}file=p.String("--file",{required:!0,description:"contract/resolver-setup.json next to an offer bundle"});printRows(e){this.print(e,n=>n,["step","target","action","detail"])}},Ek=class extends Ff{static{o(this,"ResolverSetupPlanCommand")}static paths=[["generator","setup","plan"]];static usage=I.Usage({category:"Contracts",description:"Read-only: what `generator setup apply` would write (revenue account, articles, price versions, template, resolver revision)."});async execute(){let e=await this.caller(),n=await Ya(e,this.requireTenant(e),Gu(this.file));return this.printRows(n.rows),0}},Rk=class extends Ff{static{o(this,"ResolverSetupApplyCommand")}static paths=[["generator","setup","apply"]];static usage=I.Usage({category:"Contracts",description:"Bring a resolver setup file onto the environment by stable key; seals a new revision only when config, DOCX or code differ."});async execute(){let e=await this.caller(),n=await O$(e,this.requireTenant(e),Gu(this.file));return this.printRows([...n.rows,{step:"pin",target:`${n.pin.key}@${n.pin.revision}`,action:"=",detail:"diese Revision setzt `offer plan|apply` ein"}]),0}};function Dk(t){return`${JSON.stringify(t,null,2)}
|
|
466
|
+
`}o(Dk,"pretty");function fN(t,e){if(t.kind==="combined")throw new Error(`${t.key}@${t.revision} ist ein kombinierter Generator \u2014 verwenden Sie \`${e}\`.`)}o(fN,"refuseCombined");function pN(t){if(t.kind!=="combined")throw new Error(`${t.key}@${t.revision} ist ein Dokument-Generator \u2014 verwenden Sie \`generator export\` / \`generator source export\`.`);return t}o(pN,"combinedRow");var Tk=class extends it{static{o(this,"GeneratorCombinedCreateCommand")}static paths=[["generator","combined","create"]];static usage=I.Usage({category:"Contracts",description:"Create an empty combined generator draft (no mask, no parts); write its declaration with `generator combined save`."});key=p.String("--key",{required:!0});name=p.String("--name",{required:!0,description:"Name (German)"});nameEn=p.String("--name-en",{required:!0,description:"Name (English) \u2014 every name is bilingual"});description=p.String("--description",{description:"Description (German); needs --description-en"});descriptionEn=p.String("--description-en",{description:"Description (English)"});async execute(){let{caller:e,client:n}=await this.load();return this.print(await e.mutation(R.contractGenerators.createCombinedDraft,{client:n,key:this.key,name:{de:this.name,en:this.nameEn},...this.description!==void 0||this.descriptionEn!==void 0?{description:{de:this.description??"",en:this.descriptionEn??""}}:{}})),0}},Ik=class extends it{static{o(this,"GeneratorCombinedExportCommand")}static paths=[["generator","combined","export"]];static usage=I.Usage({category:"Contracts",description:"Write a combined revision's declaration file (mask, parts as key@revision, names) \u2014 `generator combined save` reads it back."});reference=p.String({required:!0,name:"key[@revision]|id"});out=p.String("--out",{description:"Output file (default: stdout)"});async execute(){let{model:e}=await this.load(),n=Dk(ik(pN(this.find(e,this.reference))));return this.out?await yd(this.out,n,"utf8"):this.context.stdout.write(n),0}},$k=class extends it{static{o(this,"GeneratorCombinedSaveCommand")}static paths=[["generator","combined","save"]];static usage=I.Usage({category:"Contracts",description:"Save a combined declaration file onto its draft (or create the draft of a new key). An unedited export writes nothing; the server refuses an incomplete declaration with every gap named."});file=p.String({required:!0,name:"file"});async execute(){let e=dN(JSON.parse(await Un(this.file,"utf8")),this.file),{caller:n,client:r,model:i}=await this.load();return this.print(await cN(n,r,i.resolvers,e)),0}},_k=class extends it{static{o(this,"GeneratorCombinedPlanCommand")}static paths=[["generator","combined","plan"]];static usage=I.Usage({category:"Contracts",description:"Sandbox: which parts run for a mask input, each with its own input check and positions (the workspace's \u201EPositionen\u201C tab)."});reference=p.String({required:!0,name:"key[@revision]|id"});input=p.String("--input",{required:!0,description:"Mask input JSON file"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=pN(this.find(r,this.reference)),s=await e.query(R.contractGenerators.combinedPlayground,{client:n,id:i.id,input:JSON.parse(await Un(this.input,"utf8"))});if(s.refusal!==null)throw new Error(s.refusal);return this.print(s,a=>[...a.parts.map(l=>({part:l.partKey,generator:`${l.key}@${l.revision}`,status:l.status,missing:l.positions?.missingFields.join(" ")??"",issues:[...l.rosterIssues,...l.positions?.refusal?[l.positions.refusal]:[]].join("; ")})),...a.missingFields.length>0?[{part:"(Maske)",generator:"",status:"missing",missing:a.missingFields.join(" "),issues:""}]:[]],["part","generator","status","missing","issues"]),0}},Ok=class extends it{static{o(this,"GeneratorSourceExportCommand")}static paths=[["generator","source","export"]];reference=p.String({required:!0,name:"key[@revision]|id"});out=p.String("--out",{required:!0,description:"TypeScript output file"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);fN(i,"generator combined export");let s=await e.query(R.contractGeneratorAuthoring.source,{client:n,id:i.id});if(s.artifact===null)throw new Error("The generator has no saved source.");return await yd(this.out,s.artifact.source,"utf8"),await yd(`${this.out}.json`,Dk({id:i.id,expectedSourceRevision:s.sourceRevision,artifactHash:s.artifact.artifactHash,billingItemDefinitionIds:i.billingItemDefinitionIds,grantTemplateIds:i.grantTemplateIds,scenarios:s.scenarios,feeGroups:s.feeGroups}),"utf8"),this.print({source:ok.resolve(this.out),manifest:ok.resolve(`${this.out}.json`)}),0}},Ck=class extends it{static{o(this,"GeneratorSourceSaveCommand")}static paths=[["generator","source","save"]];reference=p.String({required:!0,name:"key[@revision]|id"});file=p.String("--file",{required:!0});manifest=p.String("--manifest",{required:!0,description:"Exported source manifest with expectedSourceRevision and dependency IDs"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference),s=JSON.parse(await Un(this.manifest,"utf8"));if(s.id!==i.id)throw new Error("The source manifest belongs to a different generator.");let a=await e.action(R.contractGeneratorAuthoringActions.saveSource,{client:n,id:i.id,source:await Un(this.file,"utf8"),expectedSourceRevision:s.expectedSourceRevision,billingItemDefinitionIds:s.billingItemDefinitionIds,grantTemplateIds:s.grantTemplateIds,...s.feeGroups===void 0?{}:{feeGroups:s.feeGroups}});return this.print(a),a.diagnostics.length>0?1:0}},Pk=class extends it{static{o(this,"GeneratorScenarioTestCommand")}static paths=[["generator","scenarios","test"]];reference=p.String({required:!0,name:"key[@revision]|id"});input=p.String("--input",{required:!0});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference);return this.print(await e.query(R.contractGeneratorAuthoring.evaluateScenario,{client:n,id:i.id,input:JSON.parse(await Un(this.input,"utf8"))})),0}},Nk=class extends it{static{o(this,"GeneratorScenarioApproveCommand")}static paths=[["generator","scenarios","approve"]];reference=p.String({required:!0,name:"key[@revision]|id"});file=p.String("--file",{required:!0,description:"Reviewed source revision, artifactHash and scenarios with input/expected output"});async execute(){let{caller:e,client:n,model:r}=await this.load(),i=this.find(r,this.reference),s=JSON.parse(await Un(this.file,"utf8"));return this.print(await e.mutation(R.contractGeneratorAuthoring.approveScenarios,{client:n,id:i.id,...s})),0}},mN=[Ok,Ck,Pk,Nk,sk,ak,lk,dk,ck,gk,uk,fk,pk,mk,hk,yk,bk,wk,kk,vk,Sk,xk,Ak,Ek,Rk,Tk,Ik,$k,_k];var PG=50,NG=o(t=>new Date(t).toISOString().slice(0,10),"day");function Lf(t,e){return t.map(n=>({party:n.partyId,name:`${n.name??"(ohne Namen)"}${n.deleted?" (gel\xF6scht)":""}`,due:n.deadline===null?"\u2014":NG(n.deadline),test:n.testMode?"test":"",action:n.blockedReason===null?e:`blocked: ${n.blockedReason}`}))}o(Lf,"partyRetentionRows");async function Mf(t,e){let n=[],r=null;for(;;){let i=await t.query(R.partyRetention.planDue,{client:e,paginationOpts:{cursor:r,numItems:PG}});for(let s of i.page){let a=await t.query(R.partyRetention.checkDue,{client:e,partyId:s.partyId});n.push({...s,testMode:a.testMode,blockedReason:s.blockedReason??a.blockedReason})}if(i.isDone)break;r=i.continueCursor}return n}o(Mf,"planPartyRetention");async function hN(t,e,n){let r=await Mf(t,e),i=r.filter(a=>a.blockedReason===null);if(i.length!==n)throw new Error(`retention parties apply: ${i.length} Personen sind jetzt l\xF6schbar, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention parties plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let s=[];for(let a of i){try{await t.mutation(R.partyRetention.eraseDue,{client:e,partyId:a.partyId})}catch(l){throw new Error(`retention parties apply: ${a.partyId} nicht gel\xF6scht (${l instanceof Error?l.message:String(l)}); davor gel\xF6scht: ${s.length} von ${i.length}${s.length===0?"":` (${s.map(d=>d.partyId).join(", ")})`}.`,{cause:l})}s.push(a)}return r}o(hN,"applyPartyRetention");var gN=o(t=>new Date(t).toISOString().slice(0,10),"day");function qf(t,e){return t.map(n=>({application:n.applicationId,classification:n.deleted?`${n.classification} (gel\xF6scht)`:n.classification,ended:gN(n.endedAt),due:gN(n.dueAt),test:n.testMode?"test":"",action:e}))}o(qf,"retentionRows");async function Bf(t,e){return await t.query(R.retention.planDue,{client:e})}o(Bf,"planRetention");async function yN(t,e,n){let r=await Bf(t,e);if(r.length!==n)throw new Error(`retention apply: ${r.length} Anmeldungen sind jetzt f\xE4llig, erwartet waren ${n} \u2014 nichts gel\xF6scht. Erst \`retention plan\` erneut lesen, dann mit der neuen Zahl best\xE4tigen.`);let i=[];for(let s of r){try{await t.mutation(R.retention.eraseDue,{client:e,applicationId:s.applicationId})}catch(a){throw new Error(`retention apply: ${s.applicationId} nicht gel\xF6scht (${a instanceof Error?a.message:String(a)}); davor gel\xF6scht: ${i.length} von ${r.length}${i.length===0?"":` (${i.map(l=>l.applicationId).join(", ")})`}.`,{cause:a})}i.push(s)}return i}o(yN,"applyRetention");var Fk=["application","classification","ended","due","test","action"],Lk=class extends V{static{o(this,"RetentionPlanCommand")}static paths=[["retention","plan"]];static usage=I.Usage({category:"Admission",description:"Read-only: the tenant's applications whose retention period has ended (what `retention apply --confirm` would erase)."});async execute(){let e=await this.caller(),n=await Bf(e,this.requireTenant(e));return this.print(n,r=>qf(r,"would-erase"),Fk),0}},Mk=class extends V{static{o(this,"RetentionApplyCommand")}static paths=[["retention","apply"]];static usage=I.Usage({category:"Admission",description:"Erase (DSGVO redaction) every application of the tenant whose retention period has ended. Dry run unless --confirm; --confirm needs --expect <n>, the count `retention plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually erase (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many applications you reviewed in `retention plan`; a different count erases nothing"});async execute(){let e=await this.caller(),n=this.requireTenant(e);if(!this.confirm)return this.print(await Bf(e,n),r=>qf(r,"would-erase"),Fk),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention apply --confirm: --expect <n> fehlt \u2014 die Zahl der Anmeldungen, die `retention plan` gezeigt hat.");return this.print(await yN(e,n,Number(this.expect)),r=>qf(r,"erased"),Fk),0}},qk=["party","name","due","test","action"],Bk=class extends V{static{o(this,"RetentionPartiesPlanCommand")}static paths=[["retention","parties","plan"]];static usage=I.Usage({category:"Stammdaten",description:"Read-only: the tenant's persons past its deletion rule, each with whether the hard delete may run (what `retention parties apply --confirm` would delete; blocked ones are skipped)."});async execute(){let e=await this.caller(),n=await Mf(e,this.requireTenant(e));return this.print(n,r=>Lf(r,"would-erase"),qk),0}},Vk=class extends V{static{o(this,"RetentionPartiesApplyCommand")}static paths=[["retention","parties","apply"]];static usage=I.Usage({category:"Stammdaten",description:"Hard-delete (with history and files) every person past the tenant's deletion rule that nothing blocks. Dry run unless --confirm; --confirm needs --expect <n>, the would-erase count `retention parties plan` showed."});confirm=p.Boolean("--confirm",!1,{description:"Actually delete (default: dry run)"});expect=p.String("--expect",{description:"With --confirm: how many deletable persons you reviewed in `retention parties plan`; a different count deletes nothing"});async execute(){let e=await this.caller(),n=this.requireTenant(e);if(!this.confirm)return this.print(await Mf(e,n),r=>Lf(r,"would-erase"),qk),0;if(this.expect===void 0||!/^\d+$/.test(this.expect))throw new Error("retention parties apply --confirm: --expect <n> fehlt \u2014 die Zahl der l\xF6schbaren Personen, die `retention parties plan` gezeigt hat.");return this.print(await hN(e,n,Number(this.expect)),r=>Lf(r,"erased"),qk),0}},bN=[Lk,Mk,Bk,Vk];import{readFileSync as DG}from"node:fs";import FG from"node:path";async function LG(t){let e=[];for await(let n of t)e.push(typeof n=="string"?Buffer.from(n):n);return Buffer.concat(e).toString("utf8")}o(LG,"readStream");var wN=o(t=>({readStdin:o(()=>LG(t),"readStdin"),readFile:o(e=>DG(e,"utf8"),"readFile")}),"defaultSecretReaders");async function kN(t,e){if(t.stdin&&t.file!==void 0)throw new Error("Give the secret through --secret-stdin OR --secret-file, not both.");if(!t.stdin&&t.file===void 0)throw new Error("No secret source: pass --secret-stdin (pipe the value in) or --secret-file <path>.");let n;if(t.file!==void 0){let i=FG.resolve(t.file);try{n=e.readFile(i)}catch{throw new Error(`Secret file not readable: ${i}`)}}else n=await e.readStdin();let r=n.replace(/\r?\n$/,"");if(r.trim()==="")throw new Error(`The secret from ${t.file!==void 0?"--secret-file":"stdin"} is empty.`);return r}o(kN,"readSecret");var vN={docusign:"hmacKey",insign:"password"};function SN(t){switch(t.code){case"credentialsKeyMissing":return"SIGNING_CREDENTIALS_KEY ist auf dieser Installation nicht gesetzt";case"credentialsKeyInvalid":return"SIGNING_CREDENTIALS_KEY ist keine 32 Byte in base64";case"credentialsKeyPreviousInvalid":return"SIGNING_CREDENTIALS_KEY_PREVIOUS ist gesetzt, aber unbrauchbar (kein 32-Byte-Schl\xFCssel, gleich dem aktuellen oder ohne aktuellen)";case"sealedWithUnknownKey":return`das Geheimnis ist mit Schl\xFCssel ${t.detail??"?"} versiegelt, den weder SIGNING_CREDENTIALS_KEY noch SIGNING_CREDENTIALS_KEY_PREVIOUS tr\xE4gt \u2014 vorherigen Schl\xFCssel wieder setzen oder Geheimnis neu eingeben`;case"docusignPlatformMissing":return`${t.detail??"?"} fehlt auf dieser Installation`;case"environmentMismatch":return`das Konto wurde als ${t.detail??"?"} gespeichert, die Installation spricht inzwischen ein anderes an \u2014 neu speichern`;case"productionOutsideProd":return"Ein Produktivkonto wird nur auf der Produktionsumgebung verwendet.";case"redirectRequired":return"Ein Demo-/Sandbox-Konto braucht eine Umleitungsadresse \u2014 niemand darf aus einer Sandbox echte Familien anschreiben.";case"redirectForbidden":return"Ein Produktivkonto darf keine Umleitungsadresse tragen \u2014 sonst ginge jeder Vertrag an ein einziges Postfach.";case"secretMissing":return`das Geheimnis \u201E${t.detail??"?"}\u201C ist nicht hinterlegt`}}o(SN,"describeProblem");function jn(t){return t==null?"":new Date(t).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}o(jn,"ts");function MG(t){return t.map(e=>({id:e.id,contract:e.contractId,rev:String(e.revisionNumber),provider:e.provider,env:e.environment??"",status:e.status,ref:e.providerRef??"",signers:e.signers.map(n=>`${n.name}:${n.status}`).join(", "),sent:jn(e.sentAt),completed:jn(e.completedAt),reconciled:jn(e.lastReconciledAt),error:e.error??""}))}o(MG,"requestRows");var qG=["id","contract","rev","provider","env","status","ref","signers","sent","completed","reconciled","error"];function Vf(t){if(ui.includes(t))return t;throw new Error(`--provider must be one of ${ui.join(" | ")}, got "${t}"`)}o(Vf,"parseProvider");var Kk=class extends V{static{o(this,"SigningConnectionShowCommand")}static paths=[["signing","connection","show"]];static usage=I.Usage({category:"Signing",description:"The tenant's e-signature connections: which provider its contracts go out through (\u201EE-Signatur: \u2026\u201C), and per provider the state, what keeps it from `ready`, the non-secret settings and which secrets are held (name + fingerprint, never the value). No network call.",examples:[["Show","$0 signing connection show --env local --tenant test"]]});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.signingConnections.list,{client:n});return this.json||this.context.stdout.write(`E-Signatur: ${r.activeProvider===null?"keine":Wa[r.activeProvider]}
|
|
467
|
+
`),this.print(r,i=>i.providers.map(s=>{let a=s.connection,l=a===null?"":a.settings.provider==="docusign"?`userId=${a.settings.userId}${a.settings.accountId?` accountId=${a.settings.accountId}`:""}`:`baseUrl=${a.settings.baseUrl} username=${a.settings.username} ownerId=${a.settings.ownerId}`,d=[...s.platformProblems,...a?.problems??[]];return{provider:Wa[s.provider],state:a===null?"nicht eingerichtet":a.state,active:a?.active?"yes":"no",environment:a?.environment??"",settings:l,redirect:a?.settings.signerRedirectTo??"",secrets:a===null||a.secrets.names.length===0?"":`${a.secrets.names.join(", ")} \xB7 ${a.secrets.fingerprint??"?"} \xB7 ${jn(a.secrets.setAt)}${BG[a.secrets.sealedWith??"current"]}`,lastCheck:a?.lastCheck?`${a.lastCheck.ok?"ok":"FAILED"} ${jn(a.lastCheck.at)}${a.lastCheck.message?` \u2014 ${a.lastCheck.message}`:""}`:"",webhook:s.webhookConfigured?"configured":"none (poll only)",problems:[...new Set(d.map(SN))].join("; ")}})),0}},Uk=class extends V{static{o(this,"SigningConnectionSetCommand")}static paths=[["signing","connection","set"]];static usage=I.Usage({category:"Signing",description:"Set up or change the tenant's connection at ONE provider (platform right `_platform.config.manage`). Non-secret fields are written as given; the secret (DocuSign: Connect HMAC key, inSign: API password) comes ONLY from stdin or a file and is left unchanged when neither is given. A demo/sandbox account needs --redirect-to, a production account forbids it and is refused outside prod.",examples:[["inSign sandbox",'printf %s "$INSIGN_PASSWORD" | $0 signing connection set --provider insign --base-url https://sandbox.test.getinsign.show --username controller --owner-id plexus-dev --redirect-to admin@plexus.swop.schule --secret-stdin --env local --tenant test'],["DocuSign sender, HMAC key from a file","$0 signing connection set --provider docusign --user-id <GUID> --redirect-to admin@plexus.swop.schule --secret-file ./hmac.txt --env staging --tenant <slug>"],["Remove the HMAC key (poll only)","$0 signing connection set --provider docusign --user-id <GUID> --clear-secret hmacKey --env staging --tenant <slug>"]]});provider=p.String("--provider",{required:!0,description:ui.join(" | ")});userId=p.String("--user-id",{description:"DocuSign: the school's sender (API user id, GUID)."});baseUrl=p.String("--base-url",{description:"inSign: bare https origin of the account."});username=p.String("--username",{description:"inSign: API user."});ownerId=p.String("--owner-id",{description:"inSign: owner (`foruser`) of every session."});redirectTo=p.String("--redirect-to",{description:"Demo/sandbox only: every recipient address is replaced by this one. Omit on a production account."});secretStdin=p.Boolean("--secret-stdin",!1,{description:"Read the secret from stdin."});secretFile=p.String("--secret-file",{description:"Read the secret from this file."});clearSecret=p.String("--clear-secret",{description:"Remove the stored secret of this name (hmacKey | password)."});async execute(){let e=Vf(this.provider),r=this.secretStdin||this.secretFile!==void 0?await kN({stdin:this.secretStdin,file:this.secretFile},wN(this.context.stdin)):void 0,i=this.redirectTo!==void 0?{signerRedirectTo:this.redirectTo}:{},s;if(e==="docusign"){if(this.userId===void 0)throw new Error("--user-id is required for docusign");s={provider:e,userId:this.userId,...i}}else{if(this.baseUrl===void 0||this.username===void 0||this.ownerId===void 0)throw new Error("--base-url, --username and --owner-id are required for insign");s={provider:e,baseUrl:this.baseUrl,username:this.username,ownerId:this.ownerId,...i}}let a=await this.caller(),l=this.requireTenant(a),d=await a.action(R.signingConnections.save,{client:l,settings:s,...r!==void 0?{secrets:{[vN[e]]:r}}:{},...this.clearSecret!==void 0?{clearSecrets:[this.clearSecret]}:{}});return this.print(d,c=>[{connectionId:c.connectionId,next:"signing connection test --provider "+e}]),0}},jk=class extends V{static{o(this,"SigningConnectionTestCommand")}static paths=[["signing","connection","test"]];static usage=I.Usage({category:"Signing",description:"\u201EVerbindung testen\u201C: reach the school's account (DocuSign: JWT grant \u2192 token \u2192 userinfo; inSign: version + owner) and record the result on the connection. A DocuSign consent_required answer prints the URL the school's sender must open once. Exit 1 when the test fails.",examples:[["Test inSign","$0 signing connection test --provider insign --env local --tenant test"]]});provider=p.String("--provider",{required:!0,description:ui.join(" | ")});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.action(R.signingActions.testConnection,{client:n,provider:Vf(this.provider)});return this.print(r,i=>[{ok:i.ok?"yes":"NO",provider:i.provider,environment:i.environment,accountId:i.accountId??"",baseUri:i.baseUri??"",sender:i.sender?`${i.sender.email??i.sender.userId}${i.sender.name?` (${i.sender.name})`:""}`:"",error:i.error??"",consentUrl:i.consentUrl??""}]),r.ok?0:1}},BG={current:"",previous:" \xB7 mit vorherigem Schl\xFCssel versiegelt (signing connection reseal)",unknown:" \xB7 mit unbekanntem Schl\xFCssel versiegelt \u2014 nicht zu \xF6ffnen"},Gk=class extends V{static{o(this,"SigningConnectionResealCommand")}static paths=[["signing","connection","reseal"]];static usage=I.Usage({category:"Signing",description:"After a key rotation: seal every school's connection secrets that are still under SIGNING_CREDENTIALS_KEY_PREVIOUS anew under SIGNING_CREDENTIALS_KEY \u2014 same secrets, same binding to tenant, provider and target. Idempotent. Platform-wide, platform right `_platform.config.manage`. Runbook: docs/signing/operations.md \u2192 \u201ERotating the key\u201C.",examples:[["Reseal on staging","$0 signing connection reseal --env staging"]]});async execute(){let n=await(await this.caller()).action(R.signingConnections.reseal,{});return this.print(n,r=>[{resealed:String(r.resealed),changedMeanwhile:String(r.changedMeanwhile),remainingUnderPrevious:String(r.remainingUnderPrevious),underUnknownKey:String(r.underUnknownKey),previousRemovable:r.previousRemovable?"yes \u2014 SIGNING_CREDENTIALS_KEY_PREVIOUS can go":"no"}]),VG(n)?1:0}};function VG(t){return t.remainingUnderPrevious>0||t.underUnknownKey>0}o(VG,"resealLeftWork");var Wk=class extends V{static{o(this,"SigningStatusCommand")}static paths=[["signing","status"]];static usage=I.Usage({category:"Signing",description:"The installation's signing key slots: which key every school's secrets are sealed under (current / previous / unknown), and whether SIGNING_CREDENTIALS_KEY_PREVIOUS can be removed because nothing is sealed under it any more. Platform right `_platform.config.manage`.",examples:[["Key status on prod","$0 signing status --env prod"]]});async execute(){let n=await(await this.caller()).query(R.signingConnections.keyStatus,{});return this.print(n,r=>[{currentKey:r.currentKeyId??"\u2014 (SIGNING_CREDENTIALS_KEY unset)",previousKey:r.previousKeyId??"\u2014",sealedCurrent:String(r.sealed.current),sealedPrevious:String(r.sealed.previous),sealedUnknown:String(r.sealed.unknown),previousSlot:r.previousConfigured?r.previousRemovable?"nothing sealed under it \u2014 can be removed":"still in use \u2014 run `signing connection reseal`":"unset"}]),n.sealed.unknown>0?1:0}},zk=class extends V{static{o(this,"SigningConnectionActivateCommand")}static paths=[["signing","connection","activate"]];static usage=I.Usage({category:"Signing",description:"\u201EF\xFCr Vertr\xE4ge verwenden\u201C: make this provider the one the tenant's contracts go out through (any other connection is deactivated in the same step), or switch it off with --off. Open Vorg\xE4nge stay on the account they started on. Platform right `_platform.config.manage`.",examples:[["Activate inSign","$0 signing connection activate --provider insign --env local --tenant test"],["No provider any more","$0 signing connection activate --provider insign --off --env local --tenant test"]]});provider=p.String("--provider",{required:!0,description:ui.join(" | ")});off=p.Boolean("--off",!1,{description:"Deactivate instead."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=Vf(this.provider);return await e.mutation(R.signingConnections.setActive,{client:n,provider:r,active:!this.off}),this.print({provider:r,active:!this.off},i=>[{provider:i.provider,active:i.active?"yes":"no"}]),0}},Hk=class extends V{static{o(this,"SigningConnectionRemoveCommand")}static paths=[["signing","connection","remove"]];static usage=I.Usage({category:"Signing",description:"Delete the tenant's connection at ONE provider, secrets included. Refused while an open Vorgang talks through it. Dry-run unless --confirm. Platform right `_platform.config.manage`.",examples:[["Remove","$0 signing connection remove --provider docusign --confirm --env staging --tenant <slug>"]]});provider=p.String("--provider",{required:!0,description:ui.join(" | ")});confirm=p.Boolean("--confirm",!1,{description:"Actually delete (default: say what would go)."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=Vf(this.provider);return this.confirm?(await e.mutation(R.signingConnections.remove,{client:n,provider:r}),this.print({provider:r,removed:!0},i=>[{provider:i.provider,removed:"yes"}]),0):(this.context.stdout.write(`Would remove the ${Wa[r]} connection of ${n} (secrets included). Re-run with --confirm.
|
|
468
|
+
`),0)}},Qk=class extends V{static{o(this,"SigningListCommand")}static paths=[["signing","list"]];static usage=I.Usage({category:"Signing",description:"List Signaturvorg\xE4nge of a tenant (newest first), optionally for one contract or one status.",examples:[["Everything open","$0 signing list --env local --tenant test --status sent"],["One contract","$0 signing list --env local --tenant test --contract <contractId>"]]});contract=p.String("--contract",{description:"Contract id (contracts table)."});status=p.String("--status",{description:"pending | sent | partially_signed | completed | declined | voided | expired | failed"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=this.contract?await e.query(R.signing.listForContract,{client:n,contractId:this.contract}):await e.query(R.signing.listForTenant,{client:n,...this.status?{status:this.status}:{}});return this.print(r,MG,qG),0}},Yk=class extends V{static{o(this,"SigningStartCommand")}static paths=[["signing","start"]];static usage=I.Usage({category:"Signing",description:"Start a Signaturvorgang on a frozen contract revision (contract_snapshots id) through the tenant's ACTIVE connection (`signing connection show`) \u2014 there is no provider to choose. Inserts the request and schedules the provider call; follow with `signing show`.",examples:[["Start","$0 signing start --env local --tenant test --snapshot <contractSnapshotId>"]]});snapshot=p.String("--snapshot",{required:!0,description:"contract_snapshots id of the revision to sign."});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.mutation(R.signing.start,{client:n,contractSnapshotId:this.snapshot});return this.print(r,i=>[{signingRequestId:i.signingRequestId,next:"signing show <id> (the provider call runs async)"}]),0}},Jk=class extends V{static{o(this,"SigningShowCommand")}static paths=[["signing","show"]];static usage=I.Usage({category:"Signing",description:"One Signaturvorgang with its signers, artefact URLs and received provider callbacks.",examples:[["Show","$0 signing show <signingRequestId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.signing.get,{client:n,signingRequestId:this.id});return r===null?(this.context.stderr.write(`signing: request ${this.id} not found in tenant ${n}
|
|
469
|
+
`),1):(this.print(r,i=>{let s=i.request,a=[{key:"id",value:s.id},{key:"provider",value:s.provider},{key:"status",value:s.status},...s.environment!==null?[{key:"environment",value:s.environment}]:[],{key:"contract",value:s.contractId},{key:"snapshot",value:`${s.contractSnapshotId} (rev ${s.revisionNumber})`},...s.providerRef!==null?[{key:"providerRef",value:s.providerRef}]:[],{key:"created",value:jn(s.createdAt)},{key:"sent",value:jn(s.sentAt)},{key:"completed",value:jn(s.completedAt)},...s.lastReconciledAt!==null?[{key:"reconciled",value:jn(s.lastReconciledAt)}]:[],...s.note!==null?[{key:"note",value:s.note}]:[],...s.error!==null?[{key:"error",value:s.error}]:[],...s.voidedReason!==null?[{key:"voidedReason",value:s.voidedReason}]:[],...s.declinedReason!==null?[{key:"declinedReason",value:s.declinedReason}]:[],...s.certificateUrl!==null?[{key:"certificate",value:s.certificateUrl}]:[]],l=s.signedDocuments.map((u,f)=>({key:`signedDocument ${f+1}`,value:`${u.filename} sha256=${u.sha256} uploaded=${jn(u.uploadedAt)} signers=${u.signers.map(h=>h.role).join(", ")} url=${u.url??"-"}`})),d=s.signers.map(u=>({key:`signer ${u.recipientId??u.role}`,value:[u.name,...u.email!==void 0?[`<${u.email}>`]:[],...u.originalEmail!==void 0?[`(orig ${u.originalEmail})`]:[],`role=${u.role}`,...u.anchorKey!==void 0?[`anchor=${u.anchorKey}`]:[],`status=${u.status}`,...u.signedAt!==void 0?[`signedAt=${u.signedAt}`]:[],...u.declinedReason!==void 0?[`declined="${u.declinedReason}"`]:[]].join(" ")})),c=i.receipts.map(u=>({key:`receipt ${u.event}`,value:`generated=${u.generatedDateTime} retry=${u.retryCount} received=${jn(u.receivedAt)}`}));return[...a,...l,...d,...c]},["key","value"]),0)}},Zk=class extends V{static{o(this,"SigningVoidCommand")}static paths=[["signing","void"]];static usage=I.Usage({category:"Signing",description:"Withdraw the process at the provider (schedules the void; the request ends `voided`).",examples:[["Void",'$0 signing void <signingRequestId> --reason "Neuer Vertrag folgt" --env local --tenant test']]});id=p.String({required:!0,name:"signingRequestId"});reason=p.String("--reason",{required:!0,description:"Recorded on the request (and shown to the recipients where the provider supports it, e.g. DocuSign)."});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.signing.voidRequest,{client:n,signingRequestId:this.id,reason:this.reason}),this.print({ok:!0,signingRequestId:this.id},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId}]),0}},Xk=class extends V{static{o(this,"SigningResendCommand")}static paths=[["signing","resend"]];static usage=I.Usage({category:"Signing",description:"Re-notify one signer (by party id) of an open envelope.",examples:[["Resend","$0 signing resend <signingRequestId> --party <partyId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});party=p.String("--party",{required:!0,description:"parties id of the signer."});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.signing.resend,{client:n,signingRequestId:this.id,partyId:this.party}),this.print({ok:!0,signingRequestId:this.id,partyId:this.party},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,partyId:r.partyId}]),0}},ev=class extends V{static{o(this,"SigningReconcileCommand")}static paths=[["signing","reconcile"]];static usage=I.Usage({category:"Signing",description:"Re-read the process from its provider now and apply it (bypasses the 15-minute poll window on purpose \u2014 the local-dev return path without a webhook).",examples:[["Reconcile","$0 signing reconcile <signingRequestId> --env local --tenant test"]]});id=p.String({required:!0,name:"signingRequestId"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.signing.reconcileNow,{client:n,signingRequestId:this.id}),this.print({ok:!0,signingRequestId:this.id,next:"signing show <id> in a few seconds"},r=>[{ok:r.ok?"yes":"no",signingRequestId:r.signingRequestId,next:r.next}]),0}},xN=[Kk,Uk,jk,zk,Hk,Gk,Wk,Qk,Yk,Jk,Zk,Xk,ev];function Kf(t){return t==null||t===0?"":new Date(t).toISOString().replace("T"," ").replace(/\.\d+Z$/,"Z")}o(Kf,"ts");function tv(t){return t.reasons.length===0?t.status:`${t.status}: ${t.reasons.join(", ")}`}o(tv,"capability");var nv=class extends V{static{o(this,"StripeConnectionStatusCommand")}static paths=[["stripe","status"]];static usage=I.Usage({category:"Stripe",description:"What this school's Stripe connection can do: whose account its money goes to, whether the school consented, Stripe's capability verdicts (card, SEPA, payouts) and what Stripe still wants from it.",examples:[["Local demo tenant","$0 stripe status --env local --tenant test"]]});async execute(){let e=await this.caller(),n=this.requireTenant(e),r=await e.query(R.stripeConnect.connection,{client:n});return this.print(r,i=>[{state:i.state,account:i.accountId??"",mode:i.livemode===null?"":i.livemode?"live":"test",deployment:i.platformMode??"unconfigured",consented:i.enabled?"yes":"no",connectedBy:i.connectedBy===null?"":i.connectedBy.kind==="platform"?`platform ${Kf(i.connectedBy.at)}`:`${i.connectedBy.name??"(deleted user)"} ${Kf(i.connectedBy.at)}`,card:i.view===null?"":tv(i.view.cardPayments),sepa:i.view===null?"":tv(i.view.sepaDebitPayments)+(i.sepaInactive?" (!)":""),payouts:i.view===null?"":tv(i.view.payouts),due:i.view?.requirementsDue.join(", ")??"",email:i.view?.contactEmail??"",asked:Kf(i.view?.askedAt),error:i.refreshError===null?"":`${Kf(i.refreshError.at)} ${i.refreshError.message}`}]),0}},rv=class extends V{static{o(this,"StripeRefreshCommand")}static paths=[["stripe","refresh"]];static usage=I.Usage({category:"Stripe",description:"Ask Stripe what this school's account may do, now. The mirror is normally refreshed by the v2.core.account* events; this is the way out of a stale NO, which is the expensive direction \u2014 the school cannot collect although it may. A failed read shows in `stripe status` (error).",examples:[["Demo tenant","$0 stripe refresh --env local --tenant test"]]});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.stripeConnect.refreshNow,{client:n}),this.print({ok:!0,next:"stripe status in a moment"},r=>[{ok:r.ok?"yes":"no",next:r.next}]),0}},iv=class extends V{static{o(this,"StripeAllowCommand")}static paths=[["stripe","allow"]];static usage=I.Usage({category:"Stripe",description:"The school's own half of the decision: may Plexus collect in its name? Off until set, and never implied by Stripe having cleared the account.",examples:[["Allow","$0 stripe allow --env local --tenant test"],["Withdraw","$0 stripe allow --env local --tenant test --off"]]});off=p.Boolean("--off",!1,{description:"Withdraw the consent instead of giving it"});async execute(){let e=await this.caller(),n=this.requireTenant(e);return await e.mutation(R.stripeConnect.setEnabled,{client:n,enabled:!this.off}),this.print({tenant:n,enabled:!this.off},r=>[{tenant:r.tenant,consented:r.enabled?"yes":"no"}]),0}},AN=[nv,rv,iv];var EN=[...lA,...dA,...PA,...BA,...KA,...UA,...zA,...QA,...ZA,...XA,...eE,...tE,...TE,...vR,...SR,...xR,...ER,...IR,...OR,...GR,...zR,...rC,...UC,...rN,...iN,...aN,...mN,...bN,...xN,...AN,...yE];import{createHash as KG}from"node:crypto";import{existsSync as Uf,mkdirSync as sv,readFileSync as bd,readdirSync as IN,renameSync as UG,rmSync as ov,writeFileSync as $N}from"node:fs";import jG from"node:os";import Kt from"node:path";var av=".managed-by-plexus-cli",_N="plexus-cli";function ON(t,e=t){return IN(t,{withFileTypes:!0}).flatMap(n=>{let r=Kt.join(t,n.name);return n.isDirectory()?ON(r,e):[Kt.relative(e,r)]})}o(ON,"listFiles");function GG(t){let e=`name: ${_N}`;if(t.startsWith(`---
|
|
470
|
+
`)){let n=t.indexOf(`
|
|
471
|
+
---`,4);if(n>0){let r=t.slice(4,n).split(`
|
|
472
|
+
`).filter(i=>!i.startsWith("name:")&&!i.startsWith("disable-model-invocation:"));return`---
|
|
473
|
+
${[e,...r].join(`
|
|
474
|
+
`)}${t.slice(n)}`}}return`---
|
|
475
|
+
${e}
|
|
476
|
+
---
|
|
477
|
+
|
|
478
|
+
${t}`}o(GG,"enforceFrontmatter");function RN(t,e,n){let r=Kt.join(e,"skill-warnings"),i=KG("sha256").update(t).digest("hex"),s=[];try{s=bd(r,"utf8").split(`
|
|
479
|
+
`)}catch{}if(!s.includes(i)){n(`plexus-cli: ${t}
|
|
480
|
+
`);try{sv(e,{recursive:!0}),$N(r,[...s.filter(Boolean),i].join(`
|
|
481
|
+
`)+`
|
|
482
|
+
`)}catch{}}}o(RN,"warnOnce");var TN=".plexus-cli-skill-staging-";function WG(t,e,n,r,i){for(let a of IN(t))a.startsWith(TN)&&ov(Kt.join(t,a),{recursive:!0,force:!0});let s=Kt.join(t,`${TN}${process.pid}`);for(let a of n){let l=Kt.join(s,a);sv(Kt.dirname(l),{recursive:!0});let d=bd(Kt.join(e,a),"utf8");$N(l,a==="SKILL.md"?GG(d):d)}sv(Kt.dirname(r),{recursive:!0});try{ov(r,{recursive:!0,force:!0}),UG(s,r)}catch(a){if(bd(Kt.join(r,av),{encoding:"utf8",flag:"r"})!==i)throw a}finally{ov(s,{recursive:!0,force:!0})}}o(WG,"installInto");function CN(t){let e=t.home??jG.homedir(),n=t.cacheDir??Kt.join(process.env.XDG_CACHE_HOME??Kt.join(e,".cache"),"plexus-cli"),r=t.warn??(a=>process.stderr.write(a));if((t.env??process.env).PLEXUS_CLI_NO_SKILL==="1")return;let i=Kt.join(t.source,av);if(!Uf(i))return;let s=[{app:Kt.join(e,".claude"),label:"Claude Code"},{app:Kt.join(e,".codex"),label:"Codex"}];for(let a of s){if(!Uf(a.app))continue;let l=Kt.join(a.app,"skills",_N);try{let d=bd(i,"utf8"),c=Kt.join(l,av);if(Uf(c)){if(bd(c,"utf8")===d)continue}else if(Uf(l)){RN(`${l} exists and was not installed by plexus-cli \u2014 left untouched, so ${a.label} does not get the bundled skill. Remove or rename that directory to receive it.`,n,r);continue}WG(a.app,t.source,ON(t.source),l,d)}catch(d){RN(`could not install the agent skill for ${a.label} into ${l}: ${d instanceof Error?d.message:String(d)}`,n,r)}}}o(CN,"ensureSkillInstalled");var PN="0.1.0";var jf=new co({binaryLabel:"Plexus CLI",binaryName:"plexus-cli",binaryVersion:PN});jf.register(xs.HelpCommand);jf.register(xs.VersionCommand);for(let t of EN)jf.register(t);CN({source:zG.join(import.meta.dirname,"skill")});jf.runExit(Nv(process.argv.slice(2)));
|
|
483
|
+
//# sourceMappingURL=cli.mjs.map
|