@hyperscale0/cli 1.0.425 → 1.0.426
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/hyperscale.js +1 -1
- package/package.json +2 -2
package/hyperscale.js
CHANGED
|
@@ -63,7 +63,7 @@ ${i}`)}
|
|
|
63
63
|
${r}${d}`}finally{n.delete(e)}}function ys(e,t){throw new TypeError(`canonical JSON does not support ${e} at ${t}`)}function kr(e){return Qr(Vt(e))}function Qr(e){return Array.from((0,qx.hash)(new TextEncoder().encode(e)),t=>t.toString(16).padStart(2,"0")).join("")}var qx,gs=ve(()=>{"use strict";qx=f$(kx(),1)});function an(e){return e>=4?1e8:1e4}function qo(e,t){let n=t/100,r=Math.round(Math.log10(n)),a=String(e%n).padStart(r,"0").replace(/0+$/,"");return`${Math.floor(e/n)}${a?`.${a}`:""}%`}var hs=ve(()=>{"use strict"});function Mn(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function st(e){return typeof e=="string"?[e]:e}function Wa(e){return Object.hasOwn(Lo,e)?Lo[e]:void 0}var Lx,fe,jx,Rt,Va,bt,xt,zi,Lo,Ya=ve(()=>{"use strict";Fa();Lx=/^(0|[1-9][0-9]{0,17})$/,fe=Ce().regex(/^[a-z][a-zA-Z0-9_]*$/).max(80),jx=Ce().regex(/^[a-z][a-z0-9_]{2,79}$/,{error:"an object kind is 3 to 80 characters: a lowercase letter, then lowercase letters, digits or underscores"}),Rt=Ce().min(1).max(2048),Va=Ce().regex(Lx),bt=Gn().int().safe(),xt=Ce().regex(/^[a-z][a-zA-Z0-9_]*(?:\.[a-z][a-zA-Z0-9_]*)*$/).max(240),zi=e=>Lx.test(e);Lo={balance:"money",reserved:"money",iban:"text",reference:"text"}});function Ex(e){return[Y({...e,op:he("sum"),get values(){return Bp(vt)}}),Y({...e,op:he("minimum"),get values(){return Bp(vt)}}),Y({...e,op:he("maximum"),get values(){return Bp(vt)}}),Y({...e,op:he("subtract"),get base(){return vt},get subtract(){return Bp(vt)}}),Y({...e,op:he("multiply"),get amount(){return vt},get units(){return vt}}),Y({...e,op:he("divide"),get amount(){return vt},get divisor(){return vt},rounding:jo()}),Y({...e,op:he("rate"),get base(){return vt},get bps(){return vt},rounding:jo(),get days(){return Y({from:vt,to:vt,basis:Oe(Cx)}).optional()}}),Y({...e,op:he("between"),get from(){return vt},get to(){return vt},unit:Oe(Tk),rounding:jo()}),Y({...e,op:he("compound"),get amount(){return vt},get rate(){return vt},get periods(){return vt},rounding:jo()}),Y({...e,op:he("ratio"),get amount(){return vt},get numerator(){return vt},get denominator(){return vt},rounding:jo(),currency:Rn.optional()}),Y({...e,op:he("choose"),get when(){return fs},get then(){return vt},get otherwise(){return vt}})]}function Kk(e){let t=[],n=["instruments"],r=a=>{if(!(!a||typeof a!="object")){if(Array.isArray(a)){for(let i=0;i<a.length;i++)n.push(i),r(a[i]),n.pop();return}for(let i of Object.keys(a)){let s=a[i];(i==="family"||i==="targetFamily")&&s&&typeof s=="object"?t.push([[...n,i],s]):i!=="examples"&&(n.push(i),r(s),n.pop())}}};return r(e),t}function Fx(e,t){for(let[n,r]of e.instruments.entries()){for(let[a,i]of r.fields.entries())i.type==="digest"&&t.addIssue({code:"custom",path:["instruments",n,"fields",a,"type"],message:"a digest field needs UDL format 3"});for(let[a,i]of Object.entries(r.actions))for(let[s,o]of i.input.entries())o.type==="digest"&&t.addIssue({code:"custom",path:["instruments",n,"actions",a,"input",s,"type"],message:"a digest field needs UDL format 3"})}}function jm(e,t){let n=(r,a)=>{if(!r||typeof r!="object")return;if(Array.isArray(r)){r.forEach((d,p)=>n(d,[...a,p]));return}let i=r,s=typeof i.type=="string"||typeof i.op=="string",o=s&&"currency"in i?"currency":s&&"normal"in i?"normal":i.op==="annuity"&&i.part==="profit"?"part":i.purpose==="memorandum"&&"sourceParty"in i?"purpose":void 0;o&&t.addIssue({code:"custom",path:[...a,o],message:`${o==="part"?"the profit part":o==="purpose"?"the memorandum purpose":`\`${o}\``} needs UDL format 4`});for(let[d,p]of Object.entries(i))d!=="reports"&&d!=="examples"&&n(p,[...a,d])};n(e.objects,["objects"]),n(e.instruments,["instruments"])}function Kx(e){return{...e.onboarding?{onboarding:[...e.onboarding]}:{},provider:e.provider,capability:e.capability,operation:e.operation,...e.apiVersion?{apiVersion:{header:e.apiVersion.header,value:e.apiVersion.value}}:{},requirements:[...e.requirements]}}function Qa(e,t){let n=r=>Vt(Object.fromEntries(Object.entries(r).filter(([a,i])=>!["name","label","description","optional"].includes(a)&&i!==void 0)));return n(e)===n(t)}var er,ki,Ao,Fp,Sx,Ja,Zx,Kp,vm,R7,C7,$m,bk,xk,Xp,qr,vk,$k,Vp,Tx,Oo,wk,_s,Ik,zk,kk,qk,Lk,jk,Ak,Pk,Ok,Sk,Ga,Zk,Ct,Dx,Rx,wm,jo,Cx,Tk,Bp,vt,Hx,Nx,Ax,Mx,fs,Dk,Rk,Ck,Ek,Hk,un,Nk,Im,zm,Po,So,Px,Mk,Wp,Bx,Zo,Up,km,To,Bk,Uk,Ox,tr,Do,bs,Yp,Fk,qm,Ux,Jp,Lm,Am,Pm,Om,E7,xs=ve(()=>{"use strict";Fa();ko();bm();gs();hs();Ya();er=4,ki=8192,Ao=1e3,Fp=253,Sx=rn([Ce(),bt,Ir()]),Ja=fe.meta({"x-udl-reference":"instrument"}),Zx=fe.meta({"x-udl-reference":"object"}),Kp=jx,vm=Ce().min(1).max(160),R7=Ce().min(1).max(2048),C7=bt.positive(),$m=Y({kind:Oe(["person","business","staff"]),role:fe.optional()}),bk=Y({module:fe,exportPath:xt,digest:Ce().regex(/^[a-f0-9]{64}$/)}),xk=Y({module:fe,exportPath:xt,revision:bt.positive()}),Xp=rn([bk,xk]),qr={name:fe,label:Rt.optional(),optional:he(!0).optional(),description:Rt.optional(),sensitive:he(!0).optional()},vk=Y({...qr,type:he("ref"),targetKind:Oe(["instrument","object"]),targetFamily:Xp.optional(),target:rn([fe,ye(fe).min(1)]),sharedParty:fe.optional()}),$k=Y({...qr,type:he("list"),item:Oe(["money","date","text","integer","ref"]),targetKind:Oe(["instrument","object"]).optional(),targetFamily:Xp.optional(),target:fe.optional(),maxItems:bt.min(1).max(366)}),Vp=["document","message","thread","note","count","event","judgement","extract"],Tx="record",Oo=/^[a-f0-9]{64}$/,wk=Y({...qr,type:he("digest"),kind:Oe(Vp),value:Ce().regex(Oo).optional()}),_s=zr("type",[Y({...qr,type:he("money"),currency:Rn.optional(),value:Va.optional(),minimum:Va.optional(),maximum:Va.optional()}),Y({...qr,type:he("account"),owner:rn([fe,Y({adapter:fe})]),key:fe.optional(),book:Oe(["cash","claim"]).default("cash"),contra:he(!0).optional(),currency:Rn.optional(),normal:he("debit").optional()}),vk,Y({...qr,type:he("date"),value:Qn.datetime({offset:!0}).optional()}),Y({...qr,type:he("duration"),value:bt.nonnegative().optional()}),Y({...qr,type:he("text"),value:Rt.optional(),minLength:bt.positive().max(2048).optional(),maxLength:bt.positive().max(2048).optional(),pattern:Ce().regex(/^\^\[[A-Za-z0-9-]+\]\{[1-9][0-9]{0,3}\}\$$/).optional()}),Y({...qr,type:he("integer"),value:bt.optional(),minimum:bt.optional(),maximum:bt.optional()}),Y({...qr,type:he("percent"),value:bt.min(0).max(an(er)).optional()}),Y({...qr,type:he("boolean"),value:Ir().optional()}),Y({...qr,type:he("enum"),values:ye(fe).min(1).max(64),value:fe.optional()}),$k,wk]),[Ik,,zk,kk,qk,Lk,jk,Ak,Pk,Ok,Sk]=_s.options,Ga=zr("type",[Ik,zk,kk,qk,Lk,jk,Ak,Pk,Ok,Sk]),Zk=rn([Y({literal:Sx}),Y({field:xt})]),Ct=Zk,Dx=Oe(["==","!=","<","<=",">",">="]),Rx=["floor","ceiling","half_even","half_up"],wm=Oe(Rx),jo=()=>Oe(Rx),Cx=["actual/365","actual/360","30/360"],Tk=["milliseconds","days","months"],Bp=e=>ye(e).min(1).max(256);vt=rn([Y({literal:Sx}),Y({field:xt}),zr("op",Ex({}))]),Hx=Y({kind:he("compare"),left:vt,operator:Dx,right:vt}),Nx=Y({kind:he("state"),reference:xt,states:ye(fe).min(1).max(64)}),Ax=()=>ye(fs).min(2).max(32),Mx=[Y({kind:he("all"),get of(){return Ax()}}),Y({kind:he("any"),get of(){return Ax()}}),Y({kind:he("not"),get condition(){return fs}})],fs=zr("kind",[Hx,Nx,...Mx]),Dk=Y({kind:he("compare"),left:Ct,operator:Dx,right:Ct}),Rk=ye(ye(Y({instrument:Ja,action:fe,guard:Dk,valueType:Oe(["money","date"]).optional()})).min(1).max(32)).min(1).max(128),Ck=Y({field:Ga,objectField:fe.optional(),when:Rk.optional()}),Ek=Y({onboarding:ye(Oe(["person","organization"])).min(1).max(2).optional(),provider:Rt,capability:Rt,operation:Rt,apiVersion:Y({header:Rt,value:Rt}).optional(),declarationDigest:Ce().regex(/^[a-f0-9]{64}$/),requirements:ye(Ga).max(128)}),Hk=Y({requirements:ye(Ck).max(128),adapters:ye(Y({binding:fe,snapshot:Ek.nullable(),renames:gn(fe,fe).optional()})).max(16)}),un=["owner","actor","operator"],Nk=rn([Y({role:Oe(un)}),Y({party:fe})]),Im=Y({name:fe,title:Rt.optional(),parent:fe.optional(),instrument:Ja,parties:gn(fe,Nk)}),zm=Y({entryActions:ye(fe).min(1).max(128).optional(),id:Zx,title:Rt,authoredFields:ye(fe).max(256),attachments:ye(Im).max(256),fields:ye(Ga).max(256),columns:ye(fe).max(8)}),Po=Y({family:Xp.optional(),instrument:rn([Ja,ye(Ja).min(1).max(16)]),reference:fe,anchor:xt,states:ye(fe).min(1).max(64),limit:bt.min(1).max(ki),batch:he(!0).optional(),order:ye(xt).min(1).max(4).optional(),window:Y({field:fe,milliseconds:bt.positive()}).optional(),overlaps:Y({start:fe,end:fe,from:Ct,until:Ct}).optional(),where:gn(xt,Ct).refine(e=>Object.keys(e).length<=8,"at most eight selection filters").meta({maxProperties:8}).optional()}),So=zr("op",[Y({target:fe,op:he("at"),list:xt,position:Ct}),Y({target:fe,op:he("aggregate"),selection:Po,measure:rn([he("count"),Y({sum:xt})])}),...Ex({target:fe}),Y({target:fe,op:he("annuity"),amount:Ct,rate:Ct,periods:Ct,position:Ct,part:Oe(["principal","interest","profit"])}),Y({target:fe,op:he("shift"),date:Ct,milliseconds:Ct,direction:Oe(["before","after"])}),Y({target:fe,op:he("step"),date:Ct,period:Ct,times:Ct}),Y({target:fe,op:he("banking"),date:Ct,days:Ct}),Y({target:fe,op:he("rate_of"),advance:Y({amount:Ct,date:Ct}),selection:Po,payment:Y({amount:xt,date:xt}),basis:Oe(Cx),otherwise:Ct})]),Px=Y({amount:Va,currency:Rn}),Mk=Y({kind:he("approval"),policy:xt.optional(),by:ye(fe).min(1).max(8).optional(),count:bt.min(1).max(16).optional(),within:bt.positive().max(366*864e5).optional(),band:Y({from:Px.optional(),below:Px.optional()}).optional(),amount:xt.optional()}),Wp=zr("kind",[Y({kind:he("hours"),at:xt,start:bt.min(0).max(23),end:bt.min(0).max(23),timezone:Rt}),Hx,Nx,...Mx,Y({kind:he("unique"),namespace:fe,fields:ye(xt).min(1).max(8)}),Y({kind:he("aggregate"),selection:Po,measure:rn([he("count"),Y({sum:xt})]),operator:Oe(["==","<=",">=","<",">"]),value:Ct}),Y({kind:he("evidence"),instruction:xt.optional(),subject:xt,family:fe,check:fe,result:fe,maxAge:bt.positive()}),Mk]),Bx=Oe(["internal_transfer.create","internal_transfer.reserve","internal_transfer.post","internal_transfer.void"]),Zo=["earning","principal","participant_payout","internal","prepaid_credit","pass_through","memorandum"],Up=Y({purpose:Oe(Zo),sourceParty:fe,reversalOf:xt.optional(),taxOn:fe.optional()}),km=zr("operation",[Y({key:fe,operation:he("internal_transfer.create"),economics:Up.optional(),capture:fe.optional(),amount:vt,from:xt,to:xt}),Y({key:fe,operation:he("internal_transfer.reserve"),economics:Up.optional(),boundary:Y({adapter:fe,operation:Oe(["authorize","refund"]).optional(),refundOf:xt.optional(),items:Po.refine(e=>e.limit<=Ao,{message:`a batch carries at most ${Ao} items`}).optional()}).optional(),amount:vt,from:xt,to:xt,capture:fe}),Y({key:fe,operation:he("internal_transfer.post"),economics:Up.optional(),capture:fe.optional(),transfer:xt,boundary:Y({adapter:fe,operation:Oe(["capture","account.post"]),amount:Ct.optional()}).optional()}),Y({key:fe,operation:he("internal_transfer.void"),economics:Up.optional(),capture:fe.optional(),transfer:xt,boundary:Y({adapter:fe,operation:he("void")}).optional()})]),To=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Bk=Y({adapter:fe,kind:Ce().regex(To),fields:gn(fe,Ct).refine(e=>Object.keys(e).length>0,"a message has fields").refine(e=>Object.keys(e).length<=64,"a message has at most 64 fields")}),Uk=Y({operation:he("bill.enquire"),adapter:fe,fields:Y({biller:Ct,number:Ct}),sets:gn(fe,Ce().regex(/^[a-z][a-zA-Z0-9_]{0,79}$/)).refine(e=>Object.keys(e).length>0,"a read sets a field").refine(e=>Object.keys(e).length<=32,"a read sets at most 32 fields")}),Ox=Y({at:xt,offset:bt.optional(),localDay:Y({days:bt.min(0).max(366),direction:Oe(["before","after"]),hour:bt.min(0).max(23),timezone:Rt,banking:he(!0).optional()}).optional()}),tr=Y({allowZero:he(!0).optional(),singleHanded:he(!0).optional(),purpose:Oe(["obligation","option"]).optional(),summary:Rt.optional(),title:Rt.optional(),publicAction:fe.optional(),expansionLimit:he(8192).optional(),reminder:Y({installment:xt,recipient:xt,dueAt:xt,channel:he("email"),template:Ce().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/).max(80),beforeDays:bt.min(0).max(366),overdueDays:bt.min(1).max(366),maxPerDay:bt.min(1).max(10),startHour:bt.min(0).max(23),endHour:bt.min(1).max(24),timezone:Rt}).optional(),event:Rt,actor:rn([he("caller"),he("clock"),he("observation"),Y({party:fe}),Y({parent:rn([Ja,ye(Ja).min(1).max(16)])})]),subject:Hk.optional(),follows:fe.optional(),input:ye(_s).max(128),requires:ye(Wp).max(128),due:Ox.optional(),deadline:Ox.optional(),set:gn(fe,vt).optional(),calculate:ye(So).max(128).optional(),moves:ye(km).max(256),send:Bk.optional(),read:Uk.optional(),invoke:ye(rn([Y({instrument:Ja,action:he("create"),input:gn(fe,vt),guard:fs.optional(),range:Y({count:Ct,maximum:bt.min(1).max(ki),bind:fe}).optional()}),Y({reference:xt,action:fe,input:gn(fe,vt),guard:fs.optional()}),Y({selection:Po,action:fe,input:gn(fe,vt),guard:fs.optional()})])).max(ki).optional()}),Do=Y({states:ye(fe).min(1).max(64),labels:gn(fe,Rt).optional(),initial:fe,ends:ye(fe).min(1).max(64).optional(),transitions:gn(fe,Y({from:ye(fe).min(1).max(64),to:fe}))}),bs=["moves_balance","states_have_exits","terminal_states_empty","holds_released","clocks_owned","rounding_named","stranded_balance"],Yp=Y({accepts:ye(Oe(bs)).min(1).max(7).optional(),scope:he("product").optional(),reports:ye(Ii).optional(),revisioned:he(!0).optional(),oncePerRecord:Y({reopenOn:ye(fe).min(1).max(64)}).optional(),persons:ye(Y({name:fe,optional:he(!0).optional()})).min(1).max(8).optional(),family:Xp.optional(),id:Ja,subject:Zx.optional(),template:fe.optional(),title:Rt.optional(),summary:Rt.optional(),fields:ye(_s).max(256),calculate:ye(So).max(128),lifecycle:Do,actions:gn(fe,tr),actionOrder:ye(fe).min(1).max(128),invariants:ye(Wp).max(128).optional()}),Fk=Yp.extend({reports:ye(_m).max(16).optional(),examples:ye(Y({name:Rt,input:fx()})).max(16).optional()}),qm={version:bt.positive(),product:fe,title:Rt,currency:Rn,parties:gn(fe,$m),objects:ye(zm).max(256),instruments:ye(Yp).max(256)},Ux={...qm,instruments:ye(Fk).max(256)};Jp=e=>(t,n)=>{for(let[r,a]of Kk(t.instruments))e in a||n.addIssue({code:"custom",path:r,message:`a format ${e==="digest"?"2 or 3":"1"} family names its ${e}`})},Lm=Y({udl:he(er),...qm}).superRefine(Jp("digest"));Am=Y({udl:he(3),...qm}).superRefine(Jp("digest")).superRefine(jm),Pm=Y({udl:he(2),...Ux}).superRefine(Jp("digest")).superRefine(Fx).superRefine(jm),Om=Y({udl:he(1),...Ux}).superRefine(Jp("revision")).superRefine(Fx).superRefine(jm),E7=zr("udl",[Lm,Am,Pm,Om])});function Sm(e){let t=Xk.exec(e);if(!t)return null;let[,n,r,,a,i,s]=t,o=p=>p?Number.parseInt(p,10):0,d=o(n)*6048e5+o(r)*864e5+o(a)*36e5+o(i)*6e4+o(s)*1e3;return Number.isSafeInteger(d)&&d<=8e15?d:null}function Zm(e){let t=Vk.exec(e);if(!t)return null;let[,n,r,a,i,s,o,d]=t.map(u=>u?Number.parseInt(u,10):0),p={months:n*12+r,milliseconds:a*6048e5+i*864e5+s*36e5+o*6e4+d*1e3};return p.months+p.milliseconds>0?p:null}var Xk,Vk,Tm=ve(()=>{"use strict";Xk=/^P(?!$)(\d{1,7}W)?(\d{1,7}D)?(T(?!$)(\d{1,7}H)?(\d{1,7}M)?(\d{1,7}S)?)?$/;Vk=/^P(?!$)(?:(\d{1,4})Y)?(?:(\d{1,4})M)?(?:(\d{1,4})W)?(?:(\d{1,5})D)?(?:T(?!$)(?:(\d{1,6})H)?(?:(\d{1,7})M)?(?:(\d{1,7})S)?)?$/});function Dm(e){return Math.ceil(Math.log2(2*e))}function Yk(e){let t=Xx(e,e),n=e,r=0n;for(let a=1n;n>0n;a+=2n)r+=n/a,n=Xx(n,t);return 2n*r}var Vx,Wk,Xx,M7,Wx=ve(()=>{"use strict";Vx=128n,Wk=1n<<Vx,Xx=(e,t)=>e*t>>Vx;M7=Yk(Wk/3n)});function $n(e,t,n){return{code:e,path:t,message:n,fix:Jk[e],category:Qk(e)}}function Qk(e){return Gk[e]??(e==="UDL1003"?"invalid_shape":e==="UDL1004"?"resource_limit":"invalid_semantics")}var Jk,Gk,Gp=ve(()=>{"use strict";Jk={economic_party_unbound:"Bind sourceParty to a money party retained by this attachment.",economic_move_invalid:"Declare a cash purpose on a cash transfer or its posting and memorandum on a claim transfer; use internal for other non-cash accounting.",economic_reservation_conflict:"Keep the reservation's economics on its posting.",economic_tax_base_unknown:"Name the key of another move in the same action, one with economics, whose amount the tax is on.",subject_field_conflict:"Rename the field or use matching types and constraints.",subject_field_unknown:"Name a declared subject requirement or object field.",subject_requirement_missing:"Supply the required action field.",subject_adapter_unbound:"Bind the required adapter declaration.",subject_party_unbound:"Bind the parameter to a subject role or declared party.",party_name_reserved:"Choose a party name other than owner, actor or operator.",party_kind_mismatch:"Use a business or subject role for money.",staff_role_missing:"Name the role the staff party acts as: party checker: staff role trade_checker.",staff_move_unapproved:"Add requires approval by [<another staff party>] to the action, or declare singleHanded: true when one person may move this money alone.",approval_unfrozen:"Freeze what the approval decides: move the record to a state no other action changes, such as submit to submitted, and approve from there.",product_party_invalid:"Bind a business participant in the same tenant and environment.",udl_format_unknown:"Run the document on an Arc release that ships a reader for its format.",udl_format_not_current:"Recompile the HSX program, which emits the current UDL format.",boundary_operation_invalid:"Name an operation the move can take: authorize or refund on a reserve, capture or account.post on a post, void on a void. Run a capture or void in an action of its own, and account.post legs beside each other only, with no amount and on a hold no provider authorized; refundOf names an authorization, or on a single payout the payout it reverses.",boundary_capture_unauthorized:"Capture or void only a hold an earlier action authorized, on every path to this action.",boundary_refund_exceeds_capture:"Refund no more than the authorization can capture.",boundary_void_after_capture:"Void before the full capture, or capture an amount so a remainder is left.",boundary_partial_capture:"Capture the whole hold when the adapter's capture is partial none, and part of it in one action when it is once.",message_send_invalid:"Send through an adapter the action binds whose declaration has a message.send operation, name the message kind (letters, digits, dots, dashes, up to 64), and give each message field a literal or a field that is neither an account nor sensitive. A report column and an object column carry no sensitive field either.",read_invalid:"Read through an adapter the action binds whose declaration has the read's operation, give the biller and number a literal or a text field that is not sensitive, and set only instrument money, text or integer fields no capture, value or calculation writes.",currency_mismatch:"Keep one currency per move and per calculation: convert with a ratio that names the amount's currency into an account of the target's currency, as two moves through position accounts.",UDL1003:"Use the UDL 1 typed grammar.",UDL1004:"Reduce the declared structure or expansion.",UDL2001:"Give each declaration a distinct name.",UDL2002:"Repair the named type or declaration.",UDL2010:"Remove the invocation cycle or reduce its expansion.",UDL3001:"Declare reachable states and one transition per action.",UDL3002:"Add an action from the state toward an end state, such as a clock action that closes or refunds it, or name the states that end the record in lifecycle ends.",UDL3003:"Add a clock action due at the deadline, or an action whose requirements read it, so something acts when it passes.",UDL3004:"Add a check step for each exposed action the warning names, and expect the state or refusal it leaves.",UDL4001:"Fund owned accounts before spending and close them with zero balances.",UDL5001:"Use a declared reference of the required type."};Gk={UDL3002:"no_terminal_path",UDL3003:"deadline_unowned",UDL3004:"check_missing"}});function ft(e){return"op"in e}function ln(e){switch(e.op){case"sum":case"minimum":case"maximum":return e.values;case"subtract":return[e.base,...e.subtract];case"multiply":return[e.amount,e.units];case"divide":return[e.amount,e.divisor];case"rate":return[e.base,e.bps,...e.days?[e.days.from,e.days.to]:[]];case"between":return[e.from,e.to];case"compound":return[e.amount,e.rate,e.periods];case"ratio":return[e.amount,e.numerator,e.denominator];case"choose":return[e.then,e.otherwise]}}function Li(e){return ft(e)?[...e.op==="choose"?Qp(e.when):[],...ln(e).flatMap(Li)]:[e]}function Qp(e){switch(e.kind){case"compare":return[...Li(e.left),...Li(e.right)];case"state":return[{field:e.reference}];case"all":case"any":return e.of.flatMap(Qp);case"not":return Qp(e.condition)}}function Cm(e){switch(e.op){case"aggregate":return[{field:e.selection.anchor},...Object.values(e.selection.where??{})];case"at":return[{field:e.list},e.position];case"annuity":return[e.amount,e.rate,e.periods,e.position];case"shift":return[e.date,e.milliseconds];case"banking":return[e.date,e.days];case"step":return[e.date,e.period,e.times];case"rate_of":return[e.advance.amount,e.advance.date,{field:e.selection.anchor},...Object.values(e.selection.where??{}),e.otherwise];default:return Li(e)}}function $a(e){return ft(e)?[e,...e.op==="choose"?vs(e.when):[],...ln(e).flatMap($a)]:[]}function vs(e){switch(e.kind){case"compare":return[...$a(e.left),...$a(e.right)];case"state":return[];case"all":case"any":return e.of.flatMap(vs);case"not":return vs(e.condition)}}function Ro(e){return e.flatMap(t=>t.kind==="state"?[t]:t.kind==="all"?Ro(t.of):[])}function ei(e){return ft(e)?Yx(e)+1:0}function Yx(e){return(e.op==="choose"?ji(e.when)+1:0)+ln(e).reduce((t,n)=>t+ei(n),0)}function ji(e){switch(e.kind){case"compare":return ei(e.left)+ei(e.right);case"state":return 0;case"all":case"any":return e.of.reduce((t,n)=>t+ji(n)+1,0);case"not":return ji(e.condition)+1}}function nr(e){return!eq.includes(e.op)}function tc(e){return nr(e)?Yx(e):0}function qi(e){switch(e.kind){case"compare":return`${bn(e.left)} ${e.operator} ${bn(e.right)}`;case"state":return`${e.reference} in [${e.states.join(", ")}]`;case"all":case"any":return e.of.map(t=>t.kind==="all"||t.kind==="any"?`(${qi(t)})`:qi(t)).join(e.kind==="all"?" and ":" or ");case"not":return`not (${qi(e.condition)})`}}function bn(e){if(!ft(e))return"field"in e?e.field.replace(/^(self|subject|input)\./,""):String(e.literal);let t=n=>ft(n)&&n.op!=="choose"?`(${bn(n)})`:bn(n);switch(e.op){case"sum":case"subtract":return ln(e).map(t).join(tq[e.op]);case"multiply":return`${t(e.amount)} * ${t(e.units)}`;case"divide":return`${t(e.amount)} / ${t(e.divisor)}`;case"choose":return`${t(e.then)} when ${qi(e.when)} otherwise ${t(e.otherwise)}`;case"between":return e.unit==="milliseconds"?`${t(e.to)} - ${t(e.from)}`:`${e.unit} between(${bn(e.from)}, ${bn(e.to)})`;default:return`${e.op}(${ln(e).map(bn).join(", ")})`}}var ec,Rm,eq,tq,$s=ve(()=>{"use strict";ec=["money","integer","percent","duration"],Rm=["money","integer","duration"];eq=["aggregate","at","annuity","shift","step","banking","rate_of"];tq={sum:" + ",subtract:" - "}});function Jx(e,{resolveField:t,accountKey:n}){let r=[],a=(o,d)=>r.push($n("currency_mismatch",o,d)),i=new Map,s=(o,d,p)=>o.forEach((u,m)=>{let c=`${d}[${m}]`;if((u.type==="money"||u.type==="account")&&u.currency===e.currency&&a(c,`${u.name} names ${u.currency}, the document's currency; leave it out`),u.type!=="account")return;u.normal&&u.contra&&a(c,`${u.name} is contra; a contra account takes no normal`);let l=u.currency??e.currency;typeof u.owner=="string"&&u.owner!=="self"&&u.key===void 0&&l!==e.currency&&a(c,`${u.name} holds ${l} in party ${u.owner}'s ${e.currency} balance; name the account with a key`);let h=`${typeof u.owner=="string"?u.owner==="self"?`self:${p?.id??""}`:`party:${u.owner}`:`adapter:${u.owner.adapter}`}|${u.book}|${n(u)}`,b=i.get(h),A=u.normal??"credit";b?(b.currency!==l||b.normal!==A)&&a(c,`${u.name} is ${l} ${A}-normal; the same account is ${b.currency} ${b.normal}-normal elsewhere`):i.set(h,{currency:l,normal:A})});return e.objects.forEach((o,d)=>s(o.fields,`$.objects[${d}].fields`)),e.instruments.forEach((o,d)=>{let p=`$.instruments[${d}]`;s(o.fields,`${p}.fields`,o);let u=(f,z=[],P)=>{let T=t(e,o,f,z,P);return T?.type==="money"||T?.type==="account"?T.currency??e.currency:void 0},m=(f,z=[],P)=>f&&"field"in f?u(f.field,z,P):void 0,c=(f,z,P,T)=>{P&&T&&P!==T&&a(f,`${z}: ${P} meets ${T}`)},l=(f,z,P)=>{if(!f)return;if(!ft(f))return m(f,z,P);let T=$=>$.map(q=>l(q,z,P)).find(q=>q!==void 0);switch(f.op){case"sum":case"minimum":case"maximum":return T(f.values);case"subtract":return T([f.base,...f.subtract]);case"rate":return l(f.base,z,P);case"compound":return l(f.amount,z,P);case"between":return;case"multiply":case"divide":return l(f.amount,z,P);case"ratio":return f.currency===void 0?l(f.amount,z,P):void 0;case"choose":return T([f.then,f.otherwise])}},y=(f,z,P,T,$,q)=>{if(!f)return;if(!ft(f)){c(P,T,z,m(f,$,q));return}let R=(H,x=z)=>H.forEach(w=>y(w,x,P,T,$,q));switch(f.op){case"sum":case"minimum":case"maximum":R(f.values);break;case"subtract":R([f.base,...f.subtract]);break;case"rate":R([f.base]);break;case"compound":R([f.amount]);break;case"between":break;case"multiply":case"divide":R([f.amount]);break;case"ratio":h(f,z,P,T,$,q);break;case"choose":A(f.when,P,$,q),R([f.then,f.otherwise]);break}},h=(f,z,P,T,$,q)=>{f.currency!==void 0&&f.currency===z&&a(P,`ratio ${T} names ${f.currency}, its target's currency; leave it out`),y(f.amount,f.currency??z,P,`${T} converts from`,$,q),c(P,`${T} weights`,l(f.numerator,$,q),l(f.denominator,$,q))},b=(f,z,P,T,$)=>{let q=l(f,T,$)??l(z,T,$);y(f,q,P,"a compare",T,$),y(z,q,P,"a compare",T,$)},A=(f,z,P,T)=>{f.kind==="compare"?b(f.left,f.right,z,P,T):f.kind==="all"||f.kind==="any"?f.of.forEach($=>A($,z,P,T)):f.kind==="not"&&A(f.condition,z,P,T)},Z=(f,z,P=[],T)=>f.forEach(($,q)=>{let R=`${z}[${q}]`,H=u(`self.${$.target}`,P,T);switch($.op){case"annuity":y($.amount,H,R,$.target,P,T);break;case"at":t(e,o,$.list,P,T)?.type==="list"&&c(R,$.target,H,e.currency);break;case"aggregate":if($.measure!=="count")for(let x of st($.selection.instrument)){let w=e.instruments.find(L=>L.id===x),v=w&&t(e,w,`self.${$.measure.sum}`);c(R,`${$.target} sums ${x}.${$.measure.sum}`,H,v?.type==="money"?v.currency??e.currency:void 0)}break;case"rate_of":{let x=l($.advance.amount,P,T);for(let w of st($.selection.instrument)){let v=e.instruments.find(j=>j.id===w),L=v&&t(e,v,`self.${$.payment.amount}`);c(R,`${$.target} pays ${w}.${$.payment.amount}`,x,L?.type==="money"?L.currency??e.currency:void 0)}break}case"shift":case"step":case"banking":break;default:y($,H,R,$.target,P,T)}}),k=(f,z,P=[],T)=>f.forEach(($,q)=>{let R=`${z}[${q}]`;if($.kind==="compare")b($.left,$.right,R,P,T);else if($.kind==="all"||$.kind==="any")k($.of,`${R}.of`,P,T);else if($.kind==="not")k([$.condition],`${R}.condition`,P,T);else if($.kind==="approval"&&$.amount)for(let H of[$.band?.from,$.band?.below])H&&!/^0+$/.test(H.amount)&&c(R,"an approval band",u($.amount,P,T),H.currency)});Z(o.calculate,`${p}.calculate`),k(o.invariants??[],`${p}.invariants`);for(let[f,z]of Object.entries(o.actions)){let P=`${p}.actions.${f}`;s(z.input,`${P}.input`,o),f==="create"&&z.input.forEach((T,$)=>{let q=o.fields.find(R=>R.name===T.name);T.type==="money"&&q?.type==="money"&&c(`${P}.input[${$}]`,T.name,q.currency??e.currency,T.currency??e.currency)}),Z(z.calculate??[],`${P}.calculate`,z.input,z),k(z.requires,`${P}.requires`,z.input,z);for(let[T,$]of Object.entries(z.set??{}))y($,u(`self.${T}`,z.input,z),`${P}.set.${T}`,T,z.input,z);z.moves.forEach((T,$)=>{let q=`${P}.moves[${$}]`;if("amount"in T){let R=u(T.from,z.input,z),H=u(T.to,z.input,z);c(q,`${T.key} joins ${T.from} and ${T.to}`,R,H),y(T.amount,R,q,`${T.key} moves its amount`,z.input,z)}else if(T.operation==="internal_transfer.post"&&T.boundary?.amount)for(let R of Object.values(o.actions).flatMap(H=>H.moves.map(x=>({reserve:x,item:H}))))R.reserve.operation==="internal_transfer.reserve"&&`self.${R.reserve.capture}`===T.transfer&&c(q,`${T.key} captures`,u(R.reserve.from,R.item.input,R.item),m(T.boundary.amount,z.input,z))});for(let[T,$]of(z.invoke??[]).entries()){$.guard&&k([$.guard],`${P}.invoke[${T}]`,z.input,z);let q="instrument"in $?[$.instrument]:"selection"in $?st($.selection.instrument):(()=>{let R=t(e,o,$.reference,z.input,z);return R?.type==="ref"&&R.targetKind==="instrument"?st(R.target):[]})();for(let R of q){let x=e.instruments.find(w=>w.id===R)?.actions[$.action]?.input??[];for(let[w,v]of Object.entries($.input)){let L=x.find(j=>j.name===w);L?.type==="money"&&y(v,L.currency??e.currency,`${P}.invoke[${T}].input.${w}`,`${R}.${$.action} ${w}`,z.input,z)}}}}}),r}var Gx=ve(()=>{"use strict";Gp();$s();Ya()});function Qx(e,t){return Object.entries(e.lifecycle.transitions).filter(([,n])=>n.from.includes(t)&&n.to!=="preserve"&&n.to!==t)}function e9(e){let{initial:t,states:n}=e.lifecycle;return n.filter(r=>Qx(e,r).every(([,a])=>r!==t&&a.to===t))}function Hm(e){return e.lifecycle.ends??e9(e)}function t9(e){let{initial:t,states:n,transitions:r}=e.lifecycle,a=Object.values(r).filter(o=>o.to!=="preserve"),i=new Set([t]),s=new Set(Hm(e));for(let o=0;o<n.length;o++)for(let d of a)if(d.from.some(p=>i.has(p))&&i.add(d.to),s.has(d.to))for(let p of d.from)s.add(p);return n.filter(o=>i.has(o)&&!s.has(o))}function Em(e,t=new Set){if(typeof e=="string")t.add(e);else if(Array.isArray(e))for(let n of e)Em(n,t);else if(e&&typeof e=="object")for(let n of Object.values(e))Em(n,t);return t}function n9(e){let t=new Map;for(let r of e.actionOrder){let a=e.actions[r]?.deadline?.at;a&&t.set(a,[...t.get(a)??[],r])}let n=(r,a)=>a.due?.at===r||a.deadline?.at!==r&&Em([a.requires,a.invoke?.map(i=>i.guard)]).has(r);return[...t].flatMap(([r,a])=>{if(Object.values(e.actions).some(s=>n(r,s)))return[];let i=e.lifecycle.states.filter(s=>{let o=Qx(e,s);return o.length>0&&o.every(([d])=>a.includes(d))});return i.length?[{field:r,actions:a,states:i}]:[]})}function Nm(e){return e.instruments.flatMap((t,n)=>{let r=`$.instruments[${n}]`,a=Hm(t),i=t.lifecycle.ends?"declared ":"",s=t9(t).map(d=>$n("UDL3002",`${r}.lifecycle.states[${t.lifecycle.states.indexOf(d)}]`,a.length?`state ${d} of ${t.id} reaches no ${i}end state (${a.join(", ")})`:`state ${d} of ${t.id} reaches no end state; every state leads to another and the lifecycle declares no ends`)),o=n9(t).map(({field:d,actions:p,states:u})=>$n("UDL3003",`${r}.actions.${p[0]}.deadline`,`deadline ${d} of ${t.id} closes ${p.join(", ")}, the only way out of ${u.join(", ")}, and no clock action, exposed action or requirement reads it`));return[...s,...o]})}var r9=ve(()=>{"use strict";Gp()});function Ai(e,t){return e!==void 0&&e.module===t.module&&e.exportPath===t.exportPath&&(!("digest"in e)||!("digest"in t)||e.digest===t.digest)}function nc(e){let t=e!==null&&typeof e=="object"?e.udl:void 0;return typeof t=="number"&&Co.has(t)?t:void 0}var Co,Mm=ve(()=>{"use strict";xs();Co=new Map([[1,{schema:Om}],[2,{schema:Pm}],[3,{schema:Am}],[er,{schema:Lm}]])});function rr(e,t){let n=e.get(t);if(!n)throw new Error(`Unknown reporting field or expression ${t}`);return n}function Ge(e,t){if(!e)throw new Error(t)}function Bm(e,t){let n=new Map(t);for(let r of e){Ge(!n.has(r.id),`Duplicate expression ${r.id}`);let a=s=>rr(n,s),i;switch(r.op){case"parameter":i=rq;break;case"literal":{i=r.type;let s=r.value;Ge(i.kind==="money"?typeof s=="string"&&zi(s):i.kind==="integer"?typeof s=="number"&&Number.isSafeInteger(s):i.kind==="boolean"?typeof s=="boolean":i.kind==="date"?typeof s=="string"&&Number.isFinite(Date.parse(s)):typeof s=="string",`Invalid literal ${r.id}`);break}case"choose":{Ge(a(r.condition).kind==="boolean","choose requires boolean"),i=a(r.yes),Ge(Pi(i,a(r.no)),"choose branches must have matching types and currencies");break}case"bucket":{Ge(a(r.value).kind==="integer","bucket requires an integer"),Ge(r.bounds.every((s,o)=>o===0||r.bounds[o-1]<s),"bucket bounds must ascend"),i={kind:"text"};break}case"ratio":{let s=a(r.numerator),o=a(r.denominator);Ge(Pi(s,o)&&["money","integer"].includes(s.kind),"ratio needs matching numeric measures"),i=Um;break}default:{let s=a(r.left),o=a(r.right);Ge(Pi(s,o),`Mismatched types or currencies in ${r.id}`),["equal","less","atMost"].includes(r.op)?i=a9:r.op==="and"||r.op==="or"?(Ge(s.kind==="boolean","Boolean operation requires booleans"),i=a9):r.op==="daysBetween"?(Ge(s.kind==="date","daysBetween requires dates"),i=Um):(Ge(["money","integer"].includes(s.kind),"Arithmetic requires numeric measures"),i=s)}}n.set(r.id,i)}return n}function i9(e,t,n){for(let r of e){Ge(!n.has(r.name),`Duplicate aggregate ${r.name}`);let a=r.op==="count"?Um:rr(t,r.value??"");Ge(!["sum","average"].includes(r.op)||["money","integer"].includes(a.kind),"sum requires numeric values"),Ge(r.op!=="count"||r.value===void 0,"count has no value field"),Ge(r.op==="average"?r.rounding!==void 0:r.rounding===void 0,"Only average requires an explicit rounding policy"),n.set(r.name,a)}}function s9(e,t){Ge(e.scope.currency===t.currency,"Report currency differs from Product currency");let n=new Map;for(let d of e.datasets){Ge(!n.has(d.id),`Duplicate dataset ${d.id}`);let p=new Map;for(let m of d.columns){if(Ge(!p.has(m.name),`Duplicate column ${m.name}`),m.type.kind==="money"&&Ge(m.type.currency===e.scope.currency,"Mismatched dataset currency"),d.source==="instrument"){Ge(e.scope.kind==="product","Company instrument reports require cross-Build bindings"),Ge(d.instruments.length>0,"Instrument source requires declared instruments");for(let c of d.instruments){let l=t.instruments.find(Z=>Z.id===c);Ge(l,`Unknown report instrument ${c}`);let y=m.field.split("."),h=l.fields.find(Z=>Z.name===y[0]),b=nq.get(m.field),A=y.length===2&&h?.type==="account"?y[1]==="reserved"?void 0:Wa(y[1]):y.length===1?b??(h&&["ref","account","enum"].includes(h.type)?"text":h?.type):void 0;Ge(A===m.type.kind,`Unknown or mistyped report field ${c}.${m.field}`)}}else Ge(d.instruments.length===0,"Only instrument sources bind instruments"),Ge({account:{id:"text",ownerParticipantId:"text",currency:"text",role:"text",status:"text",createdAt:"date",balance:"money",iban:"text",externalReference:"text"},identity:{id:"text",entityId:"text",participantId:"text",status:"text",createdAt:"date"},operation:{id:"text",name:"text",status:"text",createdAt:"date"},posting:{id:"text",operationId:"text",transferId:"text",productId:"text",amount:"money",reversal:"boolean",purpose:"text",classification:"text",debitAccountId:"text",creditAccountId:"text",debitRole:"text",creditRole:"text",debitBinding:"text",creditBinding:"text",valueAt:"date",move:"text",taxOn:"text"}}[d.source]?.[m.field]===m.type.kind||d.source==="posting"&&/^agreement\.[a-z][a-zA-Z0-9_]*$/.test(m.field),`Unknown or mistyped ${d.source} field ${m.field}`);p.set(m.name,m.type)}Ge(rr(p,d.rowKey).kind==="text","Row key must be text");let u=Bm(d.expressions,p);d.selection&&Ge(rr(u,d.selection).kind==="boolean","Selection must be boolean"),d.selection&&Fm(d,d.selection),n.set(d.id,u)}let r=[...e.calculation.joins.flatMap(d=>d.aggregates),...e.calculation.aggregates].map(d=>d.name);Ge(new Set(r).size===r.length,"Aggregate names must be unique across stages for null accounting");let a=n.get(e.selection.dataset);Ge(a,"Unknown primary dataset");let i=new Map(a),s=new Set;for(let d of e.calculation.joins){Ge(!s.has(d.dataset),"Duplicate join requires a distinct dataset alias"),Ge(d.dataset!==e.selection.dataset,"Self joins require a distinct dataset alias"),s.add(d.dataset);let p=n.get(d.dataset);Ge(p,`Unknown joined dataset ${d.dataset}`),Fm(e.datasets.find(u=>u.id===d.dataset),d.foreign),Ge(Pi(rr(i,d.local),rr(p,d.foreign)),"Join keys have mismatched types"),Ge(d.aggregates.length>0,"Joins must declare aggregates; implicit row multiplication is forbidden"),i9(d.aggregates,p,i)}i=Bm(e.calculation.expressions,i),e.selection.predicate&&Ge(rr(i,e.selection.predicate).kind==="boolean","Selection must be boolean");for(let d of e.validation.required)rr(i,d);for(let d of e.validation.rowReconcile)Ge(Pi(rr(i,d.left),rr(i,d.right)),"Row reconciliation requires matching measures");if(e.calculation.aggregates.length){let d=new Map(e.calculation.groupBy.map(p=>[p,rr(i,p)]));i9(e.calculation.aggregates,i,d),i=d}else Ge(e.calculation.groupBy.length===0,"Grouping requires aggregates");i=Bm(e.calculation.resultExpressions,i);for(let d of e.validation.reconcile)Ge(Pi(rr(i,d.left),rr(i,d.right)),"Reconciliation requires matching measures");let o=new Set;for(let d of e.output.columns)Ge(!o.has(d.name),"Duplicate output column"),o.add(d.name),Ge(Pi(rr(i,d.name),d.type),`Output type differs for ${d.name}`);for(let d of e.output.sort)Ge(o.has(d),`Sort key ${d} must be an output column`)}function Fm(e,t,n=new Set){if(n.has(t))return;n.add(t);let r=e.columns.find(s=>s.name===t);if(r){Ge(r.field!=="balance"&&!r.field.includes("."),"Source selection and join keys cannot depend on account reads");return}let a=e.expressions.find(s=>s.id===t);Ge(a,`Unknown source key ${t}`),Ge(a.op!=="ratio"&&a.op!=="bucket","Ratios and buckets belong after source selection");let i=s=>Fm(e,s,n);a.op==="choose"?(i(a.condition),i(a.yes),i(a.no)):"left"in a&&(i(a.left),i(a.right))}var nq,Um,a9,rq,Pi,o9=ve(()=>{"use strict";Ya();nq=new Map([["id","text"],["status","text"],["createdAt","date"]]),Um={kind:"integer"},a9={kind:"boolean"},rq={kind:"date"},Pi=(e,t)=>e.kind===t.kind&&(e.kind!=="money"||t.kind==="money"&&e.currency===t.currency)});function Oi(e){return(e.invoke??[]).flatMap(t=>"reference"in t&&t.reference==="self.id"&&!t.guard?[t.action]:[])}function rc(e){let t=Object.values(e.actions).flatMap(n=>n.invoke??[]);return new Set(Object.entries(e.actions).filter(([n,r])=>{let a=r.actor;if(typeof a!="object"||!("parent"in a))return!1;let i=[a.parent].flat(),s=t.filter(o=>o.action===n);return i.length===1&&i[0]===e.id&&s.length>0&&s.every(o=>"reference"in o&&o.reference==="self.id"&&!o.guard)}).map(([n])=>n))}function Km(e){return e.moves.flatMap(t=>!("amount"in t)&&t.boundary?.operation==="account.post"?[t.transfer]:[])}function Eo(e,t){let n=new Set(e.fields.filter($=>$.type==="account"&&$.owner==="self").map($=>`self.${$.name}`)),r=$=>{if(!$.endsWith(".balance"))return;let q=$.slice(0,-8);return n.has(q)?q:void 0},a=new Set;for(let $ of t?.instruments??[])if($.id!==e.id){for(let q of Object.values($.actions))for(let R of q.moves)if("amount"in R)for(let H of[R.from,R.to]){let x=H.split(".");if(x.shift()!=="self")continue;let w=[$];for(;x.length>1;){let v=x.shift();w=w.flatMap(L=>{let j=L.fields.find(I=>I.name===v);if(j?.type!=="ref")return[];let g=st(j.target);return t?.instruments.filter(I=>g.includes(I.id))??[]})}x.length===1&&w.some(v=>v.id===e.id)&&n.has(`self.${x[0]}`)&&a.add(`self.${x[0]}`)}}let i=[],s=$=>i.push({path:".actions",message:$}),o=new Set(Object.values(e.actions).flatMap($=>[...Object.keys($.set??{}),...Object.keys($.read?.sets??{})].map(q=>`self.${q}`))),d=$=>JSON.stringify($).match(/"field":"[^"]+"/g)?.map(q=>q.slice(9,-1))??[],p=$=>{let q=new Set;for(let R=!0;R;){R=!1;for(let H of e.calculate){let x=`self.${H.target}`;q.has(x)||d(H).some(w=>$(w)||q.has(w))&&(q.add(x),R=!0)}}return q},u=p($=>$.endsWith(".balance")||$.endsWith(".reserved")),m=new Map;for(let $ of e.fields)$.type==="money"&&$.value!==void 0&&!o.has(`self.${$.name}`)&&m.set(`self.${$.name}`,new Map([["#",BigInt($.value)]]));for(let $ of e.calculate)if($.op==="sum"||$.op==="subtract"){let q=$.op==="sum"?$.values.map(H=>[H,1n]):[[$.base,1n],...$.subtract.map(H=>[H,-1n])],R=new Map;for(let[H,x]of q)R=ea(R,c(H,"create"),x);m.set(`self.${$.target}`,R)}function c($,q){return ft($)?$.op==="sum"||$.op==="subtract"?ln($).reduce((R,H,x)=>ea(R,c(H,q),$.op==="subtract"&&x>0?-1n:1n),new Map):new Map([[`${q}:${Vt($)}`,1n]]):"field"in $?new Map([[$.field.startsWith("input.")?`${q}:${$.field}`:$.field,1n]]):new Map([["#",BigInt(String($.literal))]])}function l($,q=new Set){let R=new Map;for(let[H,x]of $){let w=m.get(H);R=ea(R,w&&!q.has(H)?l(w,new Set([...q,H])):new Map([[H,1n]]),x)}return R}let y=(t?.instruments??[]).some($=>Object.values($.actions).some(q=>(q.invoke??[]).some(R=>"instrument"in R&&R.instrument===e.id&&R.action==="create"))),h=0,b=($,q,R)=>{let H=`${R}#${h++}`,x=`${H}:opening:`;for(let[W,G]of $.balances)G===null&&$.balances.set(W,new Map([[`${x}${W}`,1n]]));let w=new Map($.balances),v=new Set(Object.keys(q.set??{}).map(W=>`self.${W}`)),L=p(W=>v.has(W)),j=new Set,g=new Set(R==="create"&&!y?[]:(q.subject?.requirements??[]).map(W=>`subject.${W.field.name}`)),I=new Set([...g,...p(W=>g.has(W))]),O=0,D=W=>W.endsWith(".reserved")||W.endsWith(".balance")&&r(W)===void 0,_=W=>{let G=new Map;for(let[se,B]of W){let te=r(se),Q=u.has(se)||j.has(se)||I.has(se)||D(se),le=te!==void 0?w.get(te)??null:new Map([[Q?`${H}:${se}`:se,1n]]);G=ea(G,le,B)}return G},S=new Map,C=new Map((q.calculate??[]).map(W=>[`self.${W.target}`,W])),E=(W,G=new Set)=>{if(ft(W)&&(W.op==="sum"||W.op==="subtract"))return ln(W).reduce((se,B,te)=>ea(se,E(B,G),W.op==="subtract"&&te>0?-1n:1n),new Map);if("field"in W){if(S.has(W.field))return S.get(W.field);let se=r(W.field);if(se!==void 0)return $.balances.get(se)??null;if(D(W.field))return new Map([[`${H}:${O++}:${W.field}`,1n]]);let B=C.get(W.field);if(B&&!G.has(W.field)){let te=new Set([...G,W.field]);return B.op==="sum"?B.values.reduce((Q,le)=>ea(Q,E(le,te)),new Map):B.op==="subtract"?B.subtract.reduce((Q,le)=>ea(Q,E(le,te),-1n),E(B.base,te)):new Map([[`${H}:${W.field}`,1n]])}}return _(l(c(W,H)))};for(let W of q.requires)if(W.kind==="compare"&&W.operator==="==")for(let[G,se]of[[W.left,W.right],[W.right,W.left]]){let B="field"in G?r(G.field):void 0;B!==void 0&&$.balances.set(B,E(se))}for(let W of C.keys())S.set(W,E({field:W}));let F=(W,G)=>{n.has(W)&&$.balances.set(W,ea($.balances.has(W)?$.balances.get(W):new Map,G,-1n))},X=(W,G)=>{n.has(W)&&$.balances.set(W,ea($.balances.has(W)?$.balances.get(W):new Map,G))};j=new Set([...v,...L]);for(let W of q.moves)if("amount"in W){let G=E(W.amount);if(F(W.from,G),W.operation==="internal_transfer.reserve"){let se=`self.${W.capture}`;$.holds.has(se)&&s(`${W.capture} overwrites a live reservation`),$.holds.set(se,{from:W.from,to:W.to,amount:G})}else X(W.to,G)}else{let G=$.holds.get(W.transfer);if(!G){s(`${W.key} consumes a missing reservation ${W.transfer}`);continue}if(W.operation==="internal_transfer.post"&&W.boundary?.amount){let se=E(W.boundary.amount);X(G.to,se),G.amount=ea(G.amount,se,-1n);continue}X(W.operation==="internal_transfer.post"?G.to:G.from,G.amount),$.holds.delete(W.transfer)}let ae=W=>W===null||[...W.keys()].some(G=>G.startsWith(x)||j.has(G))?null:new Map([...W].map(([G,se])=>{let B=G.slice(H.length+1);return G.startsWith(`${H}:`)&&j.has(B)&&!u.has(B)?[B,se]:[G,se]}));for(let[W,G]of $.balances)$.balances.set(W,ae(G));for(let W of $.holds.values())W.amount=ae(W.amount)},A={status:e.lifecycle.initial,actions:[],paths:new Map,balances:new Map([...n].map($=>[$,new Map])),holds:new Map};if(e.actions.create){b(A,e.actions.create,"create");for(let[$,q]of A.balances)(q===null||q.size)&&A.paths.set($,["create"])}let Z=($,q,R=0)=>{let H=e.actions[q],x=e.lifecycle.transitions[q];if(!H||!x||!x.from.includes($.status))return[];let w=P($);x.to!=="preserve"&&(w.status=x.to),b(w,H,q),w.actions.push(q);for(let[L,j]of w.balances)j!==null&&!j.size?w.paths.delete(L):w.paths.set(L,[...$.paths.get(L)??$.actions,q]);let v=[w];for(let L of R<8?Oi(H):[])v=v.flatMap(j=>{let g=Z(j,L,R+1);return g.length?g:[j]});return v},k=rc(e),f=[A],z=new Map,P=$=>({status:$.status,actions:[...$.actions],paths:new Map($.paths),balances:new Map($.balances),holds:new Map([...$.holds].map(([q,R])=>[q,{...R}]))}),T=0;for(;f.length&&!i.length;){if(++T>4096){s("owned proof exceeds its finite work budget");break}let $=f.pop(),q=JSON.stringify([$.status,[...$.holds.keys()].sort()]),R=z.get(q);if(R){let x=P(R),w=!1;for(let v of n){let L=R.balances.has(v)?R.balances.get(v):new Map,j=$.balances.has(v)?$.balances.get(v):new Map;L!==null&&!p9(L,j)&&(x.balances.set(v,null),!L.size&&$.paths.has(v)&&x.paths.set(v,$.paths.get(v)),w=!0)}for(let[v,L]of x.holds){let j=$.holds.get(v);if(L.from!==j.from||L.to!==j.to){s(`${v} changes reservation endpoints across paths`);break}L.amount!==null&&!p9(L.amount,j.amount)&&(L.amount=null,w=!0)}if(!w)continue;$=x}if(z.size>=256&&!R){s("owned proof exceeds 256 state and reservation combinations");break}z.set(q,P($));let H=Object.entries(e.lifecycle.transitions).filter(([,x])=>x.from.includes($.status));!H.length&&([...$.balances].some(([x,w])=>!a.has(x)&&(w===null||w.size>0))||$.holds.size)&&i.push({path:".actions",message:`terminal state ${$.status} may strand owned money or an open reservation`,stranded:{state:$.status,accounts:[...$.balances].filter(([x,w])=>!a.has(x)&&(w===null||w.size>0)).map(([x])=>x.slice(5)),actions:$.actions,paths:Object.fromEntries([...$.paths].map(([x,w])=>[x.slice(5),w]))}});for(let[x]of H)k.has(x)||f.push(...Z($,x))}return i}var ea,d9,p9,Xm=ve(()=>{"use strict";gs();$s();Ya();ea=(e,t,n=1n)=>{if(e===null||t===null)return null;let r=new Map(e);for(let[a,i]of t){let s=(r.get(a)??0n)+i*n;s?r.set(a,s):r.delete(a)}return r},d9=e=>e===null?"unknown":JSON.stringify([...e].sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,String(n)])),p9=(e,t)=>d9(e)===d9(t)});var Si,c9=ve(()=>{"use strict";Si=Object.freeze({maxDepth:32,maxKeyLength:240,maxNodes:1e5,maxTotalStringLength:1048576})});function Zi(e,t){let n;switch(e.type){case"money":n=Va.refine(r=>zi(r)&&(e.minimum===void 0||BigInt(r)>=BigInt(e.minimum))&&(e.maximum===void 0||BigInt(r)<=BigInt(e.maximum)),"Money is outside its declared bounds").meta({...e.minimum!==void 0?{"x-udl-minimum":e.minimum}:{},...e.maximum!==void 0?{"x-udl-maximum":e.maximum}:{}});break;case"account":n=Rt;break;case"ref":n=e.targetKind==="object"?vm:Rt;break;case"date":n=u9;break;case"duration":n=bt.nonnegative();break;case"text":{let r=Ce().min(e.minLength??1).max(e.maxLength??2048);e.pattern&&(r=r.regex(new RegExp(e.pattern))),n=r;break}case"integer":{let r=bt;e.minimum!==void 0&&(r=r.min(e.minimum)),e.maximum!==void 0&&(r=r.max(e.maximum)),n=r;break}case"percent":n=Gn().int().min(0).max(an(t));break;case"boolean":n=Ir();break;case"enum":n=Oe(e.values);break;case"digest":n=Ce().regex(Oo,"A digest is the SHA-256 of a record: 64 lowercase hex characters");break;case"list":{let r=e.item==="money"?Va:e.item==="date"?u9:e.item==="integer"?bt:e.item==="ref"&&e.targetKind==="object"?vm:Rt;n=ye(r).max(e.maxItems);break}}return"value"in e&&e.value!==void 0&&(n=he(e.value)),e.description&&(n=n.describe(e.description)),n}var u9,Vm=ve(()=>{"use strict";Fa();hs();xs();Ya();u9=Qn.datetime({offset:!0,error:"A date field takes an ISO 8601 date-time with an offset, such as 2026-12-01T00:00:00Z"})});function ti(e,t,n){return y9(e,t,n)||(t?.persons?.some(r=>r.name===n)??!1)}function aq(e,t,n){return ti(e,t,n)&&Mn(e.parties,n)?.kind!=="staff"}function y9(e,t,n){return Mn(e.parties,n)?!0:t?.subject?e.objects.find(r=>r.id===t.subject)?.attachments.some(r=>(r.instrument===t.id||t.id.startsWith(`${r.instrument}_`))&&Object.values(r.parties).some(a=>"role"in a?a.role===n:a.party===n))??!1:!1}function ac(e,t,n){return t?.persons?.some(r=>r.name===n)?t.fields.some(r=>r.type==="account"&&r.owner===n):ti(e,t,n)&&(Mn(e.parties,n)?.kind==="business"||!Mn(e.parties,n)&&!!t?.subject||!t?.subject&&Mn(e.parties,n)?.kind==="person")}function iq(e){let t=new Set,n=new TextEncoder,r=0,a=0,i=o=>o.length>Si.maxTotalStringLength?!1:(a+=n.encode(o).byteLength,a<=Si.maxTotalStringLength),s=(o,d)=>{if(++r>Si.maxNodes||d>Si.maxDepth)return!1;if(typeof o=="string")return i(o);if(o===null||typeof o=="boolean")return!0;if(typeof o=="number")return Number.isSafeInteger(o);if(typeof o!="object"||t.has(o))return!1;let p=Array.isArray(o);if(!p&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null)return!1;let u=Reflect.ownKeys(o);if(p&&(o.length>Si.maxNodes||u.length!==o.length+1))return!1;t.add(o);for(let m of u){if(p&&m==="length")continue;if(typeof m!="string"||m==="__proto__"||m.length>Si.maxKeyLength||!i(m)||p&&(!/^(0|[1-9][0-9]*)$/.test(m)||Number(m)>=o.length))return!1;let c=Object.getOwnPropertyDescriptor(o,m);if(!c?.enumerable||!("value"in c)||!s(c.value,d+1))return!1}return t.delete(o),!0};try{return s(e,0)}catch{return!1}}function g9(e){let t=e[0];if(!t||e.some(r=>!r||r.type!==t.type||r.optional!==t.optional))return;let n=e.some(r=>r&&"sensitive"in r&&r.sensitive===!0);if(t.type==="ref"){if(e.some(a=>a?.type!=="ref"||a.targetKind!==t.targetKind||JSON.stringify(a.targetFamily)!==JSON.stringify(t.targetFamily)))return;let r=[...new Set(e.flatMap(a=>a?.type==="ref"?st(a.target):[]))];return{...t,targetKind:t.targetKind,target:r.length===1?r[0]:r,...t.targetFamily?{targetFamily:t.targetFamily}:{},...n?{sensitive:!0}:{}}}if(!(t.type==="account"&&e.some(r=>r?.type!=="account"||r.book!==t.book||JSON.stringify(r.owner)!==JSON.stringify(t.owner)||r.key!==t.key||r.contra!==t.contra||r.currency!==t.currency||r.normal!==t.normal))&&!(t.type==="money"&&e.some(r=>r?.type!=="money"||r.currency!==t.currency))&&!(t.type==="enum"&&e.some(r=>r?.type!=="enum"||r.values.length!==t.values.length||r.values.some(a=>!t.values.includes(a))))&&!(t.type==="list"&&e.some(r=>r?.type!=="list"||r.item!==t.item||r.targetKind!==t.targetKind||r.target!==t.target)))return n?{...t,sensitive:!0}:t}function mt(e,t,n,r=[],a){return _9(e,t,n,r,new Map,a)}function oc(e,t,n,r,a=[],i){let s=mt(e,t,n,a,i),o=mt(e,t,r,a,i),d=(p,u)=>{if(typeof p.owner=="string")return`party:${p.owner}`;let m=p.owner.adapter,c=u===`self.${p.name}`?Object.values(t.actions).flatMap(l=>l.subject?.adapters??[]).find(l=>l.binding===m&&l.snapshot)?.snapshot?.provider:void 0;return c?`provider:${c}`:`binding:${m}`};return n===r||s?.type==="account"&&o?.type==="account"&&(s.owner!=="self"||n===`self.${s.name}`&&r===`self.${o.name}`)&&d(s,n)===d(o,r)&&s.book===o.book&&ic(s)===ic(o)}function ic(e){return e.key??(e.owner==="self"?e.name:"balance")}function h9(e,t,n){return(n?"requirements"in n?n.requirements:n.subject?.requirements:Object.values(e.actions).flatMap(a=>a.subject?.requirements??[]))?.find(a=>a.field.name===t)}function f9(e,t,n,r){return g9(st(t.target).map(a=>{let i=`${t.targetKind}:${a}:${n}`;if(!r.has(i)){let s=t.targetKind==="object"&&e.objects.find(d=>d.id===a),o=t.targetKind==="instrument"&&e.instruments.find(d=>d.id===a);r.set(i,s?Wm(e,s,n,r):o?_9(e,o,`self.${n}`,[],r):void 0)}return r.get(i)}))}function Wm(e,t,n,r){let a=n.split("."),i=a.shift();if(!i)return;let s=t.fields.find(o=>o.name===i);if(s){if(a.length===0)return s;if(s.type==="ref")return f9(e,s,a.join("."),r)}}function _9(e,t,n,r,a,i){let s=n.split("."),o=s.shift(),d=s.shift();if(!d&&o==="actor")return{name:"actor",type:"text"};if(!d)return o==="self"?{name:"id",type:"ref",targetKind:"instrument",target:t.id}:void 0;if(o==="party"){if(!ac(e,t,d))return;if(s.length===0)return{name:d,type:"account",owner:d,book:"cash"};let m=s.length===1?Wa(s[0]):void 0;return m?{name:s[0],type:m}:void 0}if(o==="self"&&d==="subject"&&t.subject){if(s.length===0)return{name:"subject",type:"ref",targetKind:"object",target:t.subject};let m=e.objects.find(y=>y.id===t.subject);if(!m)return;let c=s.join("."),l=`obj:${t.subject}:${c}`;return a.has(l)||a.set(l,Wm(e,m,c,a)),a.get(l)}if(o==="self"&&s.length===0){if(d==="id")return{name:d,type:"ref",targetKind:"instrument",target:t.id};if(d==="now"||d==="createdAt")return{name:d,type:"date"};if(d==="productRevision")return{name:d,type:"text"};if(d==="status")return{name:d,type:"enum",values:t.lifecycle.states}}if(o==="subject"){let m=h9(t,d,i);if(!m)return;if(s.length===0&&!m.objectField)return m.field;if(!t.subject)return;let c=e.objects.find(l=>l.id===t.subject);return c?Wm(e,c,[m.objectField??m.field.name,...s].join("."),a):void 0}let p=t,u=(o==="self"?t.fields:o==="input"?r:[]).find(m=>m.name===d);for(let[m,c]of s.entries()){let l=u?.type==="account"&&m===s.length-1?Wa(c):void 0;return l==="text"?{name:c,type:l}:l==="money"?{name:c,type:l,...u?.type==="account"&&u.currency?{currency:u.currency}:{}}:u?.type==="text"&&c==="status"&&m===s.length-1&&Object.values(p.actions).some(y=>y.moves.some(h=>"capture"in h&&h.capture===u?.name))?{name:c,type:"enum",values:["reserved","posted","settled","reversed","voided"]}:u?.type!=="ref"?void 0:f9(e,u,s.slice(m).join("."),a)}return u}function b9(e,t,n=0){let r=e.actions[t];return r?r.moves.length?!0:n<8&&Oi(r).some(a=>b9(e,a,n+1)):!1}function sq(e){let t=[];return e.objects.forEach((n,r)=>{for(let a of n.columns)n.fields.find(i=>i.name===a)?.sensitive&&t.push($n("message_send_invalid",`$.objects[${r}].columns`,`column ${a} is a sensitive field; an object list shows no sensitive value`))}),e.instruments.forEach((n,r)=>(n.reports??[]).forEach((a,i)=>a.datasets.forEach((s,o)=>s.columns.forEach((d,p)=>{let u=s.source==="instrument"?d.field.split(".")[0]:s.source==="posting"?/^agreement\.(\w+)$/.exec(d.field)?.[1]:void 0;if(!u)return;e.instruments.filter(c=>s.instruments.length?s.instruments.includes(c.id):s.source==="posting").some(c=>c.fields.find(l=>l.name===u)?.sensitive)&&t.push($n("message_send_invalid",`$.instruments[${r}].reports[${i}].datasets[${o}].columns[${p}]`,`${d.field} is a sensitive field; a report key or sum carries no sensitive value`))})))),t}function Ym(e){let t=[];return e.objects.forEach((n,r)=>{let a=Kp.safeParse(n.id);a.success||t.push($n("UDL2002",`$.objects[${r}].id`,`object ${n.id}: ${a.error.issues[0].message}`))}),e.instruments.forEach((n,r)=>{for(let[a,i]of Object.entries(n.actions)){let s=typeof i.actor=="object"&&"party"in i.actor?i.actor.party:void 0;s&&e.parties[s]?.kind==="staff"&&b9(n,a)&&!i.singleHanded&&!i.requires.some(o=>o.kind==="approval")&&t.push($n("staff_move_unapproved",`$.instruments[${r}].actions.${a}`,`${n.id}.${a} moves money on one ${s} call with no approval`))}}),t.push(...oq(e)),t.push(...sq(e)),e.instruments.forEach((n,r)=>{let a=new Map;for(let[i,s]of Object.entries(n.actions))for(let o of s.calculate??[])a.has(o.target)||a.set(o.target,i);for(let[i,s]of Object.entries(n.actions))for(let o of Object.keys(s.set??{})){let d=a.get(o);d!==void 0&&t.push($n("UDL2002",`$.instruments[${r}].actions.${i}.set.${o}`,`cannot write immutable field ${o}: action ${d} of ${n.id} calculates it`))}}),t}function oq(e){let t=[],n=(r,a)=>{if(typeof r=="string"){let i=/^self\.(\w+)$/.exec(r);i&&a.add(i[1])}else if(Array.isArray(r))for(let i of r)n(i,a);else if(r&&typeof r=="object")for(let i of Object.values(r))n(i,a)};return e.instruments.forEach((r,a)=>{for(let[i,s]of Object.entries(r.actions)){if(!s.requires.some(c=>c.kind==="approval"))continue;let o=r.lifecycle.transitions[i]?.from??[],d=new Set;n([s.requires,s.calculate,s.moves,s.send,s.read,s.invoke],d);for(let c of s.calculate??[])d.delete(c.target);for(let c of d)r.fields.find(l=>l.name===c)?.type!=="money"&&d.delete(c);let p=[...s.calculate??[],...s.requires].flatMap(c=>"selection"in c&&c.selection.anchor==="self.id"&&typeof c.measure=="object"?[c.selection]:[]),u=`$.instruments[${a}].actions.${i}`,m=(c,l,y)=>t.push($n("approval_unfrozen",u,`${r.id}.${i} waits for approval reading ${c}, which ${l} can change in ${y} while it waits`));for(let[c,l]of Object.entries(r.actions)){let y=r.lifecycle.transitions[c];if(c===i||!y||l.requires.some(Z=>Z.kind==="approval"))continue;let h=y.from.find(Z=>o.includes(Z)&&(y.to==="preserve"||o.includes(y.to)));if(!h)continue;let b=[...Object.keys(l.set??{}),...Object.keys(l.read?.sets??{}),...(l.calculate??[]).map(Z=>Z.target)].find(Z=>d.has(Z));b&&m(b,c,h);let A=(l.invoke??[]).find(Z=>Z.action==="create"&&"instrument"in Z&&p.some(k=>[k.instrument].flat().includes(Z.instrument)));A&&"instrument"in A&&m(`the ${A.instrument} rows`,c,h)}for(let c of p)for(let l of[c.instrument].flat()){let y=e.instruments.find(A=>A.id===l)?.actions.create;if(!y||typeof y.actor=="object"&&"parent"in y.actor)continue;let h=y.requires.filter(A=>A.kind==="state"&&A.reference===`self.${c.reference}`),b=h.length?o.find(A=>h.every(Z=>Z.kind==="state"&&Z.states.includes(A))):o[0];b&&m(`the ${l} rows`,`${l}.create`,b)}}}),t}function Jm(e){let t=Mo(e);if(!t.ok)return t;let n=dc(t.document);return n.length?{ok:!1,issues:n}:t}function Mo(e){if(!iq(e))return{ok:!1,issues:[$n("UDL1004","$","document exceeds structural limits or is not finite JSON")]};let t=nc(e);if(t===void 0)return{ok:!1,issues:[$n("udl_format_unknown","$.udl",`UDL format ${String(e.udl)} has no reader in this Arc release`)]};let n=Co.get(t),r=n.schema.safeParse(e),a=r.data;for(;r.success&&n.upgrade;){let i=n.upgrade(r.data);if(t=nc(i),t===void 0)throw new Error("a UDL upgrade step produced a format with no reader");n=Co.get(t),r=n.schema.safeParse(i)}return r.success?{ok:!0,stored:a,document:r.data}:{ok:!1,issues:r.error.issues.map(i=>$n("UDL1003","$"+i.path.map(s=>typeof s=="number"?`[${s}]`:`.${String(s)}`).join(""),i.message))}}function dc(e){let t=[],n=(c,l,y="UDL2002")=>t.push($n(y,c,l)),r=(c,l)=>{let y=new Set;for(let h of c)y.has(h)&&n(l,`duplicate ${h}`,"UDL2001"),y.add(h)};e.objects.length===0&&e.instruments.length===0&&n("$","document requires at least one object or instrument","UDL2002"),r(e.objects.map(c=>c.id),"$.objects"),r(e.instruments.map(c=>c.id),"$.instruments");for(let c of un)Mn(e.parties,c)&&n(`$.parties.${c}`,`${c} is a reserved subject role`,"party_name_reserved");for(let[c,l]of Object.entries(e.parties))l.kind==="staff"&&!l.role&&n(`$.parties.${c}.role`,`staff ${c} names no role`,"staff_role_missing");let a=new Map(e.objects.map(c=>[c.id,c])),i=new Map(e.instruments.map(c=>[c.id,c])),s=(c,l,y=!1,h)=>{r(c.map(b=>b.name),l);for(let b of c){if(y)Ho.has(b.name)&&n(l,`${b.name} is a reserved object name`);else{if(b.type==="account"&&b.contra&&b.book!=="claim"&&n(l,"contra accounts require the claim book"),["id","status","createdAt","now","productRevision"].includes(b.name)&&n(l,`${b.name} is a sealed instance field`),b.type==="account"&&typeof b.owner=="object"){let A=b.owner.adapter,Z=Object.values(h?.actions??{}).flatMap(f=>f.subject?.adapters??[]).filter(f=>f.binding===A);Z.length||n(l,`${b.name} needs adapter declaration ${A}`,"subject_adapter_unbound"),new Set(Z.flatMap(f=>f.snapshot?[f.snapshot.provider]:[])).size>1&&n(l,`${A} names conflicting providers`,"subject_adapter_unbound")}b.type==="account"&&typeof b.owner=="string"&&b.owner!=="self"&&!ac(e,h,b.owner)&&n(l,`${b.name} needs an eligible money party as owner`,ti(e,h,b.owner)?"party_kind_mismatch":"subject_party_unbound")}if(b.type==="text"&&((b.minLength??1)>(b.maxLength??2048)&&n(l,"text minimum exceeds maximum"),b.pattern))try{new RegExp(b.pattern)}catch{n(l,"invalid text character class")}if(b.type==="text"&&b.value!==void 0)try{Zi({...b,value:void 0},e.udl).safeParse(b.value).success||n(l,`${b.name} constant violates its text constraints`)}catch{}if(b.type==="ref"){r(st(b.target),l);for(let A of st(b.target))(b.targetKind==="object"?a.has(A):i.has(A))||n(l,`unknown reference target ${A}`,"UDL5001");if(b.sharedParty!==void 0){let A=b.sharedParty;if(b.targetKind!=="instrument")n(l,"sharedParty requires an instrument reference target","UDL5001");else for(let Z of[h,...st(b.target).map(k=>i.get(k))])Z&&!aq(e,Z,A)&&n(l,`${b.name} shares party ${A}, which ${Z.id} does not bind on each record`,"UDL5001")}if(b.targetFamily)if(b.targetKind!=="instrument")n(l,"targetFamily requires an instrument reference target","UDL5001");else for(let A of st(b.target)){let Z=i.get(A);Z&&!Ai(Z.family,b.targetFamily)&&n(l,`targetFamily does not match target instrument ${A} family`,"UDL5001")}}if(b.type==="enum"&&(r(b.values,l),b.value!==void 0&&!b.values.includes(b.value)&&n(l,`${b.name} constant is outside its enum`)),b.type==="list"){let A=b.item==="ref"&&b.targetKind&&(b.targetKind==="object"?a.has(b.target??""):i.has(b.target??"")),Z=b.item!=="ref"&&(b.targetKind!==void 0||b.target!==void 0);if(!A&&(b.item==="ref"||Z)&&n(l,`${b.name} needs a target exactly when its items are references`),b.targetFamily){if(b.item!=="ref"||b.targetKind!=="instrument")n(l,"targetFamily requires an instrument reference target","UDL5001");else if(b.target){let k=i.get(b.target);k&&!Ai(k.family,b.targetFamily)&&n(l,`targetFamily does not match target instrument ${b.target} family`,"UDL5001")}}}(b.type==="integer"||b.type==="money")&&b.minimum!==void 0&&b.maximum!==void 0&&BigInt(b.minimum)>BigInt(b.maximum)&&n(l,`${b.name} minimum exceeds maximum`),(b.type==="integer"||b.type==="money")&&b.value!==void 0&&(b.minimum!==void 0&&BigInt(b.value)<BigInt(b.minimum)||b.maximum!==void 0&&BigInt(b.value)>BigInt(b.maximum))&&n(l,`${b.name} constant violates its bounds`)}};for(let[c,l]of e.objects.entries()){let y=`$.objects[${c}]`;Ho.has(l.id)&&n(y,`${l.id} is a reserved object name`),r(l.attachments.map(b=>b.name),`${y}.attachments`),r(l.attachments.map(b=>b.instrument),`${y}.attachments`);for(let[b,A]of l.attachments.entries()){for(let[Z,k]of Object.entries(A.parties))"party"in k&&!Mn(e.parties,k.party)&&n(`${y}.attachments[${b}].parties.${Z}`,`unknown declared party ${k.party}`,"subject_party_unbound");i.get(A.instrument)?.subject!==l.id&&n(`${y}.attachments`,`${A.instrument} must attach to ${l.id}`)}r(l.authoredFields,`${y}.authoredFields`),r(l.columns,`${y}.columns`),s(l.fields,`${y}.fields`,!0);for(let b=0;b<l.authoredFields.length;b++){let A=l.authoredFields[b];Ho.has(A)&&n(`${y}.authoredFields`,`${A} is a reserved object name`),l.fields.some(Z=>Z.name===A)||n(`${y}.authoredFields`,`authored field ${A} is not in declared fields`,"subject_field_unknown"),l.fields[b]?.name!==A&&n(y,`authored field ${A} must precede attached requirements in fields`)}for(let b of l.columns)Ho.has(b)&&n(`${y}.columns`,`${b} is a reserved object name`),l.fields.find(Z=>Z.name===b)||n(`${y}.columns`,`column ${b} is not a declared field`,"subject_field_unknown");let h=e.instruments.filter(b=>b.subject===l.id).flatMap(b=>Object.values(b.actions).flatMap(A=>A.publicAction?[A.publicAction]:[]));r(h,`$.objects.${l.id}.publicActions`)}let o=new Set;for(let[c,l]of e.instruments.entries())for(let[y,h]of(l.reports??[]).entries()){let b=`$.instruments[${c}].reports[${y}]`;o.has(h.identity.id)&&n(b,`duplicate report ${h.identity.id}`,"UDL2001"),o.add(h.identity.id);try{s9(h,e)}catch(A){n(b,A instanceof Error?A.message:"Invalid report definition")}}let d=new Map;for(let[c,l]of e.instruments.entries()){let y=`$.instruments[${c}]`;l.subject&&!a.has(l.subject)&&n(y,`unknown subject object ${l.subject}`),l.subject&&Object.values(l.actions).some(x=>x.publicAction)&&!a.get(l.subject)?.attachments.some(x=>x.instrument===l.id)&&n(`${y}.subject`,"public subject actions require an object attachment","UDL5001");let h=(x,w=[],v)=>mt(e,l,x,w,v),b=(x,w,v,L=[],j)=>{let g=x.startsWith("party.")?x.split(".")[1]:void 0;g&&!ac(e,l,g)&&n(v,`${g} cannot supply a money account`,ti(e,l,g)?"party_kind_mismatch":"subject_party_unbound");let I=h(x,L,j);return I?.type!==w&&n(v,`${x} must name a ${w} field`,"UDL5001"),I},A=(x,w,v,L=[],j)=>{if("field"in x){b(x.field,w,v,L,j);return}(w==="money"?typeof x.literal=="string"&&zi(x.literal):w==="integer"||w==="percent"||w==="duration"?typeof x.literal=="number"&&Number.isSafeInteger(x.literal)&&(w!=="percent"||x.literal>=0&&x.literal<=an(e.udl))&&(w!=="duration"||x.literal>=0):w==="date"?Zi({name:"literal",type:"date"},e.udl).safeParse(x.literal).success:w==="boolean"?typeof x.literal=="boolean":w==="digest"?typeof x.literal=="string"&&Oo.test(x.literal):typeof x.literal=="string")||n(v,`literal must have type ${w}`)},Z=(x,w=[],v)=>{if(!ft(x))return"field"in x?h(x.field,w,v)?.type:void 0;switch(x.op){case"rate":case"ratio":case"compound":return"money";case"between":return x.unit==="milliseconds"?"duration":"integer";case"multiply":case"divide":return Z(x.amount,w,v);default:for(let L of ln(x)){let j=Z(L,w,v);if(j)return j}}},k=(x,w,v,L=[],j)=>{if(!ft(x)){A(x,w,v,L,j);return}let g=(O,D,_)=>{"literal"in O&&(typeof O.literal=="number"||typeof O.literal=="string"&&zi(O.literal))&&(D?BigInt(O.literal)<=0n:BigInt(O.literal)<0n)&&n(v,_)},I=O=>O.includes(w)?!0:(n(v,`${x.op} yields ${O.join(" or ")}, not ${w}`),!1);switch(x.op){case"sum":case"subtract":case"minimum":case"maximum":if(I(ec))for(let O of ln(x))k(O,w,v,L,j);return;case"multiply":case"divide":{if(!I(Rm))return;k(x.amount,w,v,L,j);let O=x.op==="multiply"?x.units:x.divisor;k(O,"integer",v,L,j),g(O,x.op==="divide","money multiplier must be nonnegative and divisor must be positive");return}case"rate":if(!I(["money"]))return;k(x.base,"money",v,L,j),k(x.bps,"percent",v,L,j),x.days&&(k(x.days.from,"date",v,L,j),k(x.days.to,"date",v,L,j));return;case"between":if(!I([x.unit==="milliseconds"?"duration":"integer"]))return;k(x.from,"date",v,L,j),k(x.to,"date",v,L,j);return;case"compound":if(!I(["money"]))return;k(x.amount,"money",v,L,j),k(x.rate,"percent",v,L,j),k(x.periods,"integer",v,L,j),"literal"in x.periods&&typeof x.periods.literal=="number"&&(x.periods.literal<0||x.periods.literal>1200)&&n(v,"compound periods must be from 0 to 1200");return;case"ratio":{if(!I(["money"]))return;k(x.amount,"money",v,L,j);let O=Z(x.numerator,L,j)??Z(x.denominator,L,j)??("literal"in x.numerator&&typeof x.numerator.literal=="string"?"money":"integer");["integer","money","percent"].includes(O)?(k(x.numerator,O,v,L,j),k(x.denominator,O,v,L,j)):n(v,"ratio weights must share a numeric type"),g(x.numerator,!1,"ratio numerator must be nonnegative and denominator positive"),g(x.denominator,!0,"ratio numerator must be nonnegative and denominator positive");return}case"choose":H([x.when],v,L,j),k(x.then,w,v,L,j),k(x.otherwise,w,v,L,j)}},f=x=>ft(x)&&x.op==="choose"?[...f(x.then),...f(x.otherwise)]:[x],z=(x,w,v,L)=>{k(x,w.type,v,L.input,L);for(let j of f(x))if("literal"in j)try{Zi(w,e.udl).safeParse(j.literal).success||n(v,`literal violates constraints of ${w.name}`)}catch{}};s(l.fields,`${y}.fields`,!1,l);let P=new Set(Object.values(l.actions).flatMap(x=>[...x.moves.flatMap(w=>"capture"in w&&w.capture?[w.capture]:[])]));for(let x of P){let w=l.fields.find(v=>v.name===x);(w?.type!=="text"||w.value!==void 0)&&n(y,`${x} must be a text field reserved for an executor receipt`)}let T=(x,w,v=[])=>{let L=st(x.instrument);r(L,w);let j=L.flatMap(D=>{let _=i.get(D);return _||n(w,`unknown selected instrument ${D}`),_?[_]:[]}),g=(D,_)=>D&&_&&D.type===_.type&&(D.type!=="ref"||_.type==="ref"&&D.targetKind===_.targetKind&&l9(D.target,_.target)),I=h(x.anchor,v);for(let D of x.states)j.length&&!j.some(_=>_.lifecycle.states.includes(D))&&n(w,`selection names an undeclared state: ${D}`);for(let D of j){x.family&&!Ai(D.family,x.family)&&n(w,`selection family does not match target instrument ${D.id} family`,"UDL5001"),x.window&&D.fields.find(S=>S.name===x.window.field)?.type!=="date"&&n(w,"selection window requires a date field on every selected instrument"),x.overlaps&&[x.overlaps.start,x.overlaps.end].some(S=>D.fields.find(C=>C.name===S)?.type!=="date")&&n(w,"selection overlaps requires start and end date fields on every selected instrument");let _=D.fields.find(S=>S.name===x.reference);g(_,I)||n(w,"selection reference and anchor must have the same declared type");for(let S of x.order??[]){let C=mt(e,D,`self.${S}`);(!C||["account","ref","list"].includes(C.type))&&n(w,`selection order needs a scalar path: ${S}`)}for(let[S,C]of Object.entries(x.where??{})){let E=mt(e,D,S.startsWith("self.")?S:`self.${S}`);E?"field"in C?g(E,h(C.field,v))||n(w,`selection filter ${S} has mismatched operands`):A(C,E.type,w,v):n(w,`unknown selected field ${S}`)}}x.overlaps&&(A(x.overlaps.from,"date",w,v),A(x.overlaps.until,"date",w,v));let O=j[0];if(O)return{...O,fields:O.fields.flatMap(D=>{let _=g9(j.map(S=>S.fields.find(C=>C.name===D.name)));return _?[_]:[]})}},$=(x,w,v=[],L)=>{r(x.map(D=>D.target),w);let j=new Map;for(let[D,_]of x.entries()){let S=`${w}[${D}]`,C=!nr(_),E=C?_.op==="at"?(()=>{let X=h(_.list,v,L);return X?.type==="list"?X.item:"text"})():_.op==="aggregate"&&_.measure==="count"?"integer":_.op==="shift"||_.op==="step"||_.op==="banking"?"date":_.op==="rate_of"?"percent":"money":h(`self.${_.target}`)?.type??"money",F=b(`self.${_.target}`,E,w);if(F&&"value"in F&&F.value!==void 0&&n(w,`calculation cannot replace constant ${_.target}`),C||k(_,E,w,v,L),_.op==="at"){let X=b(_.list,"list",w,v,L);F?.type==="ref"&&X?.type==="list"&&(F.targetKind!==X.targetKind||F.target!==X.target)&&n(S,"list extraction requires the same reference target","UDL5001"),A(_.position,"integer",w,v,L),"literal"in _.position&&Number(_.position.literal)<1&&n(w,"list positions start at one")}if(_.op==="aggregate"){let X=T(_.selection,w,v);_.measure!=="count"&&(!X||mt(e,X,`self.${_.measure.sum}`)?.type!=="money")&&n(w,"aggregate calculation needs a typed money path")}if(_.op==="rate_of"){A(_.advance.amount,"money",w,v,L),A(_.advance.date,"date",w,v,L),A(_.otherwise,"percent",w,v,L);let X=T(_.selection,w,v);_.selection.batch&&n(w,"rate_of selection cannot batch: a rate needs every flow");let ae=W=>X&&mt(e,X,`self.${W}`)?.type;ae(_.payment.amount)!=="money"&&n(w,"rate_of payment amount needs a typed money path"),ae(_.payment.date)!=="date"&&n(w,"rate_of payment date needs a typed date path")}_.op==="annuity"&&(A(_.amount,"money",w,v,L),A(_.rate,"percent",w,v,L),A(_.periods,"integer",w,v,L),A(_.position,"integer",w,v,L)),_.op==="shift"&&(A(_.date,"date",w,v,L),A(_.milliseconds,"literal"in _.milliseconds?"integer":"duration",w,v,L),"literal"in _.milliseconds&&typeof _.milliseconds.literal=="number"&&_.milliseconds.literal<0&&n(w,"shift milliseconds must be nonnegative")),_.op==="banking"&&(A(_.date,"date",w,v,L),A(_.days,"integer",w,v,L),"literal"in _.days&&typeof _.days.literal=="number"&&(_.days.literal<0||_.days.literal>366)&&n(w,"banking days must be from 0 to 366")),_.op==="step"&&(A(_.date,"date",w,v,L),(!("literal"in _.period)||typeof _.period.literal!="string"||!Zm(_.period.literal))&&n(w,"step period must be a literal ISO-8601 period such as P1M"),A(_.times,"integer",w,v,L),"literal"in _.times&&typeof _.times.literal=="number"&&_.times.literal<0&&n(w,"step times must be nonnegative")),j.set(_.target,Cm(_).flatMap(X=>"field"in X&&X.field.startsWith("self.")&&!(L&&X.field===`self.${_.target}`&&!l.calculate.some(ae=>ae.target===_.target))?[X.field.slice(5)]:[]))}let g=new Set,I=new Set,O=D=>{if(g.has(D)){n(w,`calculation cycle at ${D}`);return}if(!I.has(D)){g.add(D),I.add(D);for(let _ of j.get(D)??[])O(_);g.delete(D)}};for(let D of j.keys())O(D)};$(l.calculate,`${y}.calculate`);let q=new Set(l.lifecycle.states);q.has("preserve")&&n(y,"preserve is a reserved transition destination","UDL3001"),r(l.lifecycle.states,`${y}.lifecycle.states`),(!q.has(l.lifecycle.initial)||!l.actions.create)&&n(y,"declare create and a declared initial state","UDL3001"),l.lifecycle.ends&&(r(l.lifecycle.ends,`${y}.lifecycle.ends`),l.lifecycle.ends.some(x=>!q.has(x))&&n(`${y}.lifecycle.ends`,"lifecycle ends name an undeclared state","UDL3001")),r(l.actionOrder,`${y}.actionOrder`),(l.actionOrder.length!==Object.keys(l.actions).length||l.actionOrder.some(x=>!Mn(l.actions,x)))&&n(y,"actionOrder must list every action once");let R=new Set([l.lifecycle.initial]);for(let[x,w]of Object.entries(l.lifecycle.transitions))(!Mn(l.actions,x)||x==="create"||w.to!=="preserve"&&!q.has(w.to)||w.from.some(v=>!q.has(v)))&&n(y,`invalid transition ${x}`,"UDL3001");for(let x=0;x<q.size;x++)for(let w of Object.values(l.lifecycle.transitions))w.to!=="preserve"&&w.from.some(v=>R.has(v))&&R.add(w.to);for(let x of q)R.has(x)||n(y,`unreachable state ${x}`,"UDL3001");if(dq(l,y,n),l.oncePerRecord){let x=l.oncePerRecord.reopenOn;r(x,`${y}.oncePerRecord.reopenOn`),x.some(w=>!q.has(w))&&n(`${y}.oncePerRecord`,"oncePerRecord reopens on an undeclared state","UDL3001"),x.includes(l.lifecycle.initial)&&n(`${y}.oncePerRecord`,"a started agreement holds its record, so reopenOn excludes the initial state","UDL3001")}if(l.accepts&&r(l.accepts,`${y}.accepts`),l.persons){let x=l.persons.map(v=>v.name);r(x,`${y}.persons`),l.subject||n(`${y}.persons`,"persons bind at an attached instrument's create","subject_party_unbound");for(let v of x)(["self","owner","actor","operator"].includes(v)||y9(e,l,v))&&n(`${y}.persons`,`person ${v} names a party the instrument already binds`);let w=new Map(l.fields.flatMap(v=>v.type==="account"&&typeof v.owner=="string"&&x.includes(v.owner)?[[`self.${v.name}`,v.owner]]:[]));for(let[v,L]of Object.entries(l.actions))for(let j of L.moves??[]){let g="from"in j?String(j.from):"",I=w.get(g);I===void 0||typeof L.actor=="object"&&"party"in L.actor&&L.actor.party===I||L.requires.some(O=>"check"in O&&O.check==="signed_by"&&O.result===I)||n(`${y}.actions.${v}.moves`,`${g} belongs to person ${I}, so ${v} needs ${I} as its actor or a requirement signed by ${I}`)}}let H=(x,w,v=[],L)=>{for(let j of x??[])if(j.kind==="all"||j.kind==="any")H(j.of,w,v,L);else if(j.kind==="not")H([j.condition],w,v,L);else if(j.kind==="compare"&&(ft(j.left)||ft(j.right))){let g=Z(j.left,v,L)??Z(j.right,v,L);!g||!ec.includes(g)?n(w,"a comparison with arithmetic compares two numbers"):(k(j.left,g,w,v,L),k(j.right,g,w,v,L))}else if(j.kind==="compare"){let g="field"in j.left?h(j.left.field,v,L):void 0,I="field"in j.right?h(j.right.field,v,L):void 0;("field"in j.left&&!g||"field"in j.right&&!I)&&n(w,"comparison refers to an undeclared field"),g&&I&&(g.type!==I.type||g.type==="ref"&&I.type==="ref"&&(g.targetKind!==I.targetKind||!l9(g.target,I.target)))&&n(w,"comparison operands have different types"),(g?.type==="digest"||I?.type==="digest")&&j.operator!=="=="&&j.operator!=="!="&&n(w,"a digest compares only with == or !="),g&&"literal"in j.right&&(A(j.right,g.type,w,v,L),g.type==="enum"&&!g.values.includes(String(j.right.literal))&&n(w,"comparison names an undeclared enum value")),I&&"literal"in j.left&&(A(j.left,I.type,w,v,L),I.type==="enum"&&!I.values.includes(String(j.left.literal))&&n(w,"comparison names an undeclared enum value"))}else if(j.kind==="state"){let g=b(j.reference,"ref",w,v,L);g?.type==="ref"&&g.targetKind!=="instrument"&&n(w,"state gates require an instrument reference","UDL5001"),g?.type==="ref"&&g.targetKind==="instrument"&&j.states.some(I=>st(g.target).some(O=>!i.get(O)?.lifecycle.states.includes(I)))&&n(w,"reference gate names an undeclared state")}else if(j.kind==="unique")for(let g of j.fields)h(g,v,L)||n(w,`unknown identity field ${g}`);else if(j.kind==="evidence"){j.instruction&&(b(j.instruction,"text",w,v,L),["confirmed","rejected"].includes(j.result)||n(w,"instruction evidence requires a terminal outcome"));let g=h(j.subject,v,L);j.family===Tx?(j.instruction&&n(w,"record evidence names no instruction"),g?.type!=="digest"&&n(w,"record evidence needs a digest field subject"),j.check==="exists"?j.result!=="stored"&&n(w,"record exists evidence has the result stored"):j.check==="signed_by"?ti(e,l,j.result)?e.parties[j.result]?.kind==="staff"&&n(w,"record signed_by names a customer or business party, not staff"):n(w,`record signed_by names ${j.result}, which is not a party of this instrument`,"subject_party_unbound"):n(w,"record evidence checks exists or signed_by")):(!g||!["account","text",...j.instruction?["ref"]:[]].includes(g.type))&&n(w,"evidence subject must be an account or text subject id")}else if(j.kind==="approval"){!L||L.actor==="clock"||typeof L.actor=="object"&&"parent"in L.actor?n(w,"approval belongs to an action a caller or party runs"):L.requires.findIndex(g=>g.kind==="approval")!==L.requires.indexOf(j)&&n(w,"an action names at most one approval"),j.policy===void 0==(j.by===void 0)&&n(w,"approval names a policy or a by row, not both"),j.policy!==void 0&&(j.count!==void 0||j.within!==void 0||j.band!==void 0)&&n(w,"count, within and band belong to a by row");for(let g of j.by??[])ti(e,l,g)||n(w,`approval by names an undeclared party ${g}`);if(j.band){let{from:g,below:I}=j.band;g===void 0&&I===void 0&&n(w,"band names from, below or both"),g!==void 0&&I!==void 0&&BigInt(g.amount)>=BigInt(I.amount)&&n(w,"band from must be less than below")}j.band===void 0!=(j.amount===void 0)&&j.by&&n(w,"an inline band and its amount come together"),j.amount&&b(j.amount,"money",w,v,L)}else if(j.kind==="hours"){b(j.at,"date",w,v,L);try{new Intl.DateTimeFormat("en",{timeZone:j.timezone})}catch{n(w,"hours requires an IANA timezone")}j.start===j.end&&n(w,"hours interval admits no time")}else{let g=T(j.selection,w,v);if(j.kind==="aggregate"){let I=j.measure;typeof I!="string"&&(g&&mt(e,g,`self.${I.sum}`)?.type)!=="money"&&n(w,"aggregate sum requires a money field"),A(j.value,j.measure==="count"?"integer":"money",w,v,L)}}};H(l.invariants,`${y}.invariants`);for(let[x,w]of Object.entries(l.actions)){let v=`${y}.actions.${x}`;if(x!=="create"&&!Mn(l.lifecycle.transitions,x)&&n(v,"action needs a lifecycle transition","UDL3001"),w.subject){let g=`${v}.subject`;s(w.subject.requirements.map(I=>({...I.field,name:I.objectField??I.field.name})),`${g}.requirements`,!0),r(w.subject.requirements.map(I=>I.field.name),`${g}.requirements`);for(let[I,O]of w.subject.requirements.entries()){for(let _ of(O.when??[]).flat()){let S=i.get(_.instrument);Mn(S?.actions,_.action)||n(`${g}.requirements[${I}].when`,"subject condition needs a declared instrument action","UDL5001")}O.field.optional&&n(`${g}.requirements`,`subject requirement ${O.field.name} cannot be optional`,"UDL2002");let D=O.objectField??O.field.name;if(Ho.has(D)&&n(g,`${D} is a reserved object name`),l.subject){let _=a.get(l.subject)?.fields.find(S=>S.name===D);(!_||!Qa(_,O.field))&&n(g,`object field ${D} must match requirement ${O.field.name}`,_?"subject_field_conflict":"subject_field_unknown")}}r(w.subject.adapters.map(I=>I.binding),`${g}.adapters`);for(let I of w.subject.adapters)if(I.snapshot){s(I.snapshot.requirements,`${g}.adapters.${I.binding}.requirements`,!0);for(let O of I.snapshot.requirements){let D=Mn(I.renames,O.name)??O.name;w.subject.requirements.find(S=>(S.objectField??S.field.name)===D&&Qa(S.field,O))||n(g,`adapter ${I.binding} requirement ${O.name} is absent from the action`),O.optional&&n(`${g}.adapters.${I.binding}`,`adapter requirement ${O.name} cannot be optional`,"UDL2002")}}}if(s(w.input,`${v}.input`,!1,l),w.reminder){b(w.reminder.installment,"ref",v,w.input,w),b(w.reminder.recipient,"account",v,w.input,w),b(w.reminder.dueAt,"date",v,w.input,w),w.reminder.startHour>=w.reminder.endHour&&n(v,"reminder sending window is empty");try{new Intl.DateTimeFormat("en",{timeZone:w.reminder.timezone})}catch{n(v,"reminder requires an IANA timezone")}}for(let g of w.input){g.type==="account"&&n(v,"account bindings cannot be caller inputs");let I=l.fields.find(D=>D.name===g.name),O=[...l.calculate,...Object.values(l.actions).flatMap(D=>D.calculate??[])].some(D=>D.target===g.name);x==="create"&&(O||I&&"value"in I&&I.value!==void 0)&&n(v,`${g.name} is fixed by the contract and cannot be an input`),P.has(g.name)&&n(v,`${g.name} is an executor-owned receipt and cannot be an input`)}if($(w.calculate??[],`${v}.calculate`,w.input,w),H(w.requires,`${v}.requires`,w.input,w),typeof w.actor=="object"&&"party"in w.actor&&!ti(e,l,w.actor.party)&&n(v,"actor names an undeclared party"),typeof w.actor=="object"&&"parent"in w.actor&&st(w.actor.parent).some(g=>!i.has(g))&&n(v,"actor names an undeclared parent"),w.actor==="clock"&&!w.due&&n(v,"clock action needs a due instant"),w.actor==="observation"){let[g,...I]=w.input;(x==="create"||g?.name!=="amount"||g.type!=="money"||I.length||w.due||w.follows!==void 0)&&n(v,"an observation action is a transition with one input, amount: money, and no due or follows")}w.follows!==void 0&&(w.subject?.requirements.some(g=>g.field.name===w.follows)||n(v,`follows names no subject requirement ${w.follows}`),(x==="create"||w.actor!=="caller")&&n(v,"a follow action is a caller transition, not create"),(w.input.length||w.moves.length||w.invoke?.length)&&n(v,"a follow action takes no input, moves and invokes"));for(let g of[w.due,w.deadline])if(g&&(b(g.at,"date",v,w.input,w),g.localDay)){try{new Intl.DateTimeFormat("en",{timeZone:g.localDay.timezone}).format(0)}catch{n(v,"clock timezone must be an IANA timezone")}g.localDay.banking&&g.localDay.direction!=="after"&&n(v,"banking days count forward: direction is after")}for(let g of w.moves){if(g.economics){let D=`${v}.moves[${w.moves.indexOf(g)}].economics`,_=g.economics.taxOn;_!==void 0&&(_===g.key||!w.moves.some(C=>C.key===_&&C.economics))&&n(D,`taxOn ${_} names no other move with economics in this action`,"economic_tax_base_unknown"),ac(e,l,g.economics.sourceParty)||n(D,`economic source party ${g.economics.sourceParty} is not bound to money`,"economic_party_unbound");let S="amount"in g?[{move:g,action:w}]:Object.values(l.actions).flatMap(C=>C.moves.map(E=>({move:E,action:C}))).filter(({move:C})=>C.operation==="internal_transfer.reserve"&&`self.${C.capture}`===g.transfer);(g.operation==="internal_transfer.void"||!S.length||g.economics.purpose!=="internal"&&S.some(({move:C,action:E})=>"from"in C?[C.from,C.to].some(F=>{let X=h(F,E.input,E);return X?.type!=="account"||X.book!==(g.economics.purpose==="memorandum"?"claim":"cash")}):!0))&&n(D,g.economics.purpose==="memorandum"?"a memorandum purpose requires a move between claim accounts":"economic purpose requires a move that carries cash","economic_move_invalid"),g.operation==="internal_transfer.post"&&S.some(({move:C})=>C.economics&&(C.economics.purpose!==g.economics.purpose||C.economics.sourceParty!==g.economics.sourceParty||C.economics.reversalOf!==g.economics.reversalOf||C.economics.taxOn!==g.economics.taxOn))&&n(D,"posting economics conflict with the reservation","economic_reservation_conflict")}let I="boundary"in g?g.boundary:void 0;I&&!w.subject?.adapters.some(D=>D.binding===I.adapter&&D.snapshot)&&n(v,g.operation==="internal_transfer.reserve"?"boundary reservation requires a retained adapter binding":`boundary ${I.operation} requires a retained adapter binding`);let O=g.operation==="internal_transfer.reserve"?g.boundary?.items:void 0;if(O){let D=`${v}.boundary.items`;g.operation==="internal_transfer.reserve"&&g.boundary?.operation&&n(D,"only a payout carries items","boundary_operation_invalid");let _=T(O,D,w.input);for(let[S,C]of[["reference","text"],["payee","text"],["amount","money"]])_&&_.fields.find(E=>E.name===S)?.type!==C&&n(D,`a batch item reads its ${S} from the ${C} field ${S}, and ${_.id} has none`,"boundary_operation_invalid")}if(g.operation==="internal_transfer.post"&&g.boundary?.amount&&A(g.boundary.amount,"money",v,w.input,w),"amount"in g){k(g.amount,"money",v,w.input,w);let D=b(g.from,"account",v,w.input,w),_=b(g.to,"account",v,w.input,w);D?.type==="account"&&_?.type==="account"&&D.book!==_.book&&n(v,"moves cannot cross account books","UDL4001"),oc(e,l,g.from,g.to,w.input,w)&&n(v,"a transfer needs distinct accounts","UDL4001")}else b(g.transfer,"text",v,w.input,w)}r(w.moves.flatMap(g=>"capture"in g&&g.capture?[g.capture]:[]),`${v}.captures`),r(w.moves.map(g=>g.key),`${v}.moves`);for(let[g,I]of Object.entries(w.set??{})){let O=l.fields.find(D=>D.name===g);!O||P.has(g)||"value"in O&&O.value!==void 0||O.type==="account"||O.type==="ref"||l.calculate.some(D=>D.target===g)?n(v,`cannot write immutable field ${g}`):z(I,O,`${v}.set.${g}`,w)}if(w.send){let g=w.send,I=`${v}.send`,O=w.subject?.adapters.find(D=>D.binding===g.adapter);O?.snapshot?.capability!=="boundary"?n(I,`send requires a retained boundary adapter binding ${g.adapter}`,"message_send_invalid"):O.snapshot.operation!=="message.send"&&n(I,`${g.adapter} is bound for ${O.snapshot.operation}, not message.send`,"boundary_operation_invalid");for(let[D,_]of Object.entries(g.fields)){if(!("field"in _))continue;let S=h(_.field,w.input,w);(!S||S.type==="account"||S.sensitive)&&n(`${I}.fields.${D}`,`${_.field} must name a field the message can carry, not an account or a sensitive field`,"message_send_invalid")}}if(w.read){let g=w.read,I=`${v}.read`,O=w.subject?.adapters.find(D=>D.binding===g.adapter);O?.snapshot?.capability!=="boundary"?n(I,`read requires a retained boundary adapter binding ${g.adapter}`,"read_invalid"):O.snapshot.operation!==g.operation&&n(I,`${g.adapter} is bound for ${O.snapshot.operation}, not ${g.operation}`,"boundary_operation_invalid");for(let[D,_]of Object.entries(g.fields)){if(!("field"in _))continue;let S=h(_.field,w.input,w);(!S||S.type!=="text"||S.sensitive)&&n(`${I}.fields.${D}`,`${_.field} must name a text field that is not sensitive`,"read_invalid")}for(let D of Object.keys(g.sets)){let _=l.fields.find(S=>S.name===D);(!_||P.has(D)||"value"in _&&_.value!==void 0||!["money","text","integer"].includes(_.type)||l.calculate.some(S=>S.target===D))&&n(`${I}.sets.${D}`,`${D} must be an instrument money, text or integer field no capture, value or calculation writes`,"read_invalid")}}let L=(g,I,O,D)=>{let _=g?Mn(i.get(g)?.actions,I):void 0;if(_){for(let S of _.input)!S.optional&&!("value"in S&&S.value!==void 0)&&!Object.hasOwn(O,S.name)&&n(v,`missing target input ${S.name}`);for(let[S,C]of Object.entries(O)){let E=_.input.find(F=>F.name===S);if(!E){n(v,`unknown target input ${S}`);continue}if(D&&"field"in C&&C.field===D){E.type!=="integer"&&n(v,"range binding requires an integer target input");continue}if(z(C,E,v,w),E.type==="ref"&&"field"in C){let F=h(C.field,w.input,w);(F?.type!=="ref"||F.targetKind!==E.targetKind||!st(F.target).every(X=>st(E.target).includes(X)))&&n(v,`target input ${S} has the wrong reference type`)}}}},j=[];for(let g of w.invoke??[]){g.guard&&H([g.guard],v,w.input,w);let I="instrument"in g?g.range:void 0;I&&(A(I.count,"integer",v,w.input,w),["self","input","party","subject"].includes(I.bind)&&n(v,"range binding cannot shadow a reserved scope"),"literal"in I.count&&(typeof I.count.literal!="number"||I.count.literal<1||I.count.literal>I.maximum)&&n(v,"range count must be between one and its maximum")),"selection"in g&&T(g.selection,v,w.input);let O="reference"in g?h(g.reference,w.input,w):void 0,D="instrument"in g?g.instrument:"selection"in g?g.selection.instrument:O?.type==="ref"&&O.targetKind==="instrument"?O.target:void 0,_=Array.isArray(D)?D:D?[D]:[];_.length||n(v,"invocation needs a declared target");for(let S of _){L(S,g.action,g.input,I?.bind),g.action==="create"&&!("instrument"in g)&&n(v,"invocation references an existing instance and cannot create it again");let C=i.get(S),E=Mn(C?.actions,g.action);if(!C||!E)n(v,"invocation target must name a declared action");else if(!g.guard&&l.subject&&C.subject&&l.subject===C.subject){let F=w.subject?.requirements??[];for(let X of E.subject?.requirements??[]){let ae=X.objectField??X.field.name;F.some(G=>(G.objectField??G.field.name)===ae)||n(`${v}.invoke`,`mandatory invocation of ${S}.${g.action} requires subject field ${X.field.name}`,"UDL2002")}}}j.push(..._.map(S=>`${S}.${g.action}`))}d.set(`${l.id}.${x}`,j)}t.some(x=>x.path.startsWith(y))||t.push(...Eo(l,e).map(x=>({...$n("UDL4001",y+x.path,x.message),...x.stranded?{stranded:x.stranded}:{}})))}let p=new Set,u=new Set,m=c=>{if(p.has(c)){n("$.instruments",`invocation cycle at ${c}`,"UDL2010");return}if(!u.has(c)){p.add(c);for(let l of d.get(c)??[])m(l);p.delete(c),u.add(c)}};for(let c of d.keys())m(c);return t.push(...Jx(e,{resolveField:mt,accountKey:ic})),t}function m9(e){let t=e?.literal,n=typeof t=="number"?String(t):t;if(typeof n!="string")return;let r=/^(\d{1,18})(?:\.(\d{1,2}))?$/.exec(n);if(r)return BigInt(r[1])*100n+BigInt((r[2]??"").padEnd(2,"0"))}function dq(e,t,n){let r=e.lifecycle.transitions,a=new Map,i=Object.entries(e.actions).flatMap(([u,m])=>m.moves.map(c=>({name:u,action:m,move:c}))),s=new Map;for(let{name:u,move:m}of i)m.operation==="internal_transfer.reserve"&&m.boundary?.operation==="authorize"?a.set(`self.${m.capture}`,{action:u,adapter:m.boundary.adapter,amount:m.amount}):m.operation==="internal_transfer.reserve"&&m.boundary&&!m.boundary.operation&&!m.boundary.items&&!m.boundary.refundOf&&m.capture&&s.set(`self.${m.capture}`,m.boundary.adapter);let o=(u,m)=>{let c=new Set(m);for(let l=0;l<=e.lifecycle.states.length;l++)for(let[y,h]of Object.entries(r))!u.has(y)&&h.to!=="preserve"&&h.from.some(b=>c.has(b))&&c.add(h.to);return c},d=u=>u==="create"?[]:r[u]?.from??[],p=u=>new Set([...a.entries()].filter(([m])=>m===u).map(([,m])=>m.action));for(let{name:u,action:m,move:c}of i){let l=`${t}.actions.${u}.moves.${c.key}`,y="boundary"in c?c.boundary:void 0;if(!y)continue;if(c.operation==="internal_transfer.reserve"){let $=!y.operation&&!c.boundary?.items&&c.boundary?.refundOf!==void 0;if(!$&&y.operation==="refund"!=(c.boundary?.refundOf!==void 0)&&n(l,"a refund names the authorization it returns money from with refundOf, and only a refund or a single payout does","boundary_operation_invalid"),$&&s.get(c.boundary.refundOf)!==y.adapter&&n(l,`refundOf ${c.boundary.refundOf} is not a payout this instrument sends through ${y.adapter}`,"boundary_operation_invalid"),y.operation!=="refund"||!c.boundary?.refundOf)continue;let q=a.get(c.boundary.refundOf);if(!q||q.adapter!==y.adapter){n(l,`refundOf ${c.boundary.refundOf} is not a hold this instrument authorizes through ${y.adapter}`,"boundary_capture_unauthorized");continue}let R=m9(c.amount),H=m9(q.amount);R!==void 0&&H!==void 0&&R>H&&n(l,`the refund of ${c.amount&&JSON.stringify(c.amount.literal)} is more than the ${JSON.stringify(q.amount.literal)} ${q.action} authorizes, so it is over any total the authorization can capture`,"boundary_refund_exceeds_capture");continue}let h=c.transfer,b=y.operation==="account.post",A=$=>b&&"boundary"in $&&$.boundary?.operation==="account.post",Z=$=>b&&($.operation==="internal_transfer.create"||$.operation==="internal_transfer.reserve"),k=[m.moves.some($=>$!==c&&!A($)&&!Z($))&&"other moves",!b&&Object.keys(m.set??{}).length>0&&"set",!b&&(m.calculate?.length??0)>0&&"calculate",(m.invoke?.length??0)>0&&"invoke",m.reminder!==void 0&&"a reminder",!b&&m.send!==void 0&&"a send",m.read!==void 0&&"a read"].filter($=>typeof $=="string");if(k.length&&n(l,b?`${u} asks the provider to account.post and also has ${k.join(", ")}; a refused posting returns the agreement to where ${u} found it and takes back only its plain moves and holds, so the account.post runs beside other account.post legs, plain moves and holds only`:`${u} asks the provider to ${y.operation} and also has ${k.join(", ")}; a declined or duplicate answer returns the agreement to where ${u} found it and undoes nothing else, so the ${y.operation} runs in an action of its own`,"boundary_operation_invalid"),b){y.amount!==void 0&&n(l,"an account.post books the whole remaining hold, so it names no amount","boundary_operation_invalid"),i.some(({move:q})=>q.operation==="internal_transfer.reserve"&&`self.${q.capture}`===h&&q.boundary!==void 0)&&n(l,`this account.post acts on ${h}, which a provider holds; a bank posting mirrors only a plain hold`,"boundary_operation_invalid");continue}let f=c.operation==="internal_transfer.post"?"capture":"void",z=a.get(h);if(!z||z.adapter!==y.adapter){n(l,`this ${f} acts on ${h}, which no action authorizes through ${y.adapter}`,"boundary_capture_unauthorized");continue}if(z.action===u){n(l,`${u} authorizes and ${f}s the same hold, and the provider answers the authorization only after the action commits`,"boundary_capture_unauthorized");continue}if(z.action==="create")continue;let P=o(p(h),[e.lifecycle.initial]),T=d(u).filter($=>P.has($));T.length&&n(l,`${u} can ${f} from ${T.join(", ")}, which a path reaches without ${z.action} authorizing ${h}`,"boundary_capture_unauthorized")}for(let{name:u,move:m}of i){if(m.operation!=="internal_transfer.post"||m.boundary?.operation!=="capture"||m.boundary.amount!==void 0)continue;let c=r[u],l=o(p(m.transfer),c?c.to==="preserve"?c.from:[c.to]:[e.lifecycle.initial]);for(let{name:y,move:h}of i)h.operation==="internal_transfer.void"&&h.transfer===m.transfer&&d(y).some(b=>l.has(b))&&n(`${t}.actions.${y}.moves.${h.key}`,`${y} voids ${m.transfer} from a state ${u} reaches after capturing all of it`,"boundary_void_after_capture")}}var sc,Ho,No,l9,Gm=ve(()=>{"use strict";hs();xs();Gx();Gp();Mm();o9();Xm();c9();Tm();Vm();Ya();$s();sc=["objectId","externalId","revision","kind","tenantId","productId"],Ho=new Set(sc);No=class extends Error{constructor(n){super(n.map(r=>`${r.path}: ${r.message}`).join(`
|
|
64
64
|
`));this.issues=n;this.name="UdlError"}issues};l9=(e,t)=>st(e).some(n=>st(t).includes(n))});function x9(e){let t=Jm(e);if(!t.ok)throw new No(t.issues);return`${xm(t.stored)}
|
|
65
65
|
`}function ws(e){return Qr(x9(e))}function Qm(e){return Qr(`${xm(e)}
|
|
66
|
-
`)}var v9=ve(()=>{"use strict";Gm();gs()});function ay(e){return kr(e)}function iy(e,t){let n=[];sy=t.currency,Ti={before:an(e.udl),after:an(t.udl)},cq(n,e,t),uq(n,e,t),lq(n,e,t),bq(n,e,t);let r=Iq(n,e,t),a=i=>uc.indexOf(i.class);return r.map((i,s)=>({change:i,index:s})).sort((i,s)=>a(i.change)-a(s.change)||i.index-s.index).map(({change:i})=>i)}function jt(e,t){let n=t.before?t.after?"changed":"removed":"added";e.push({kind:n,class:t.class,subject:t.subject,key:t.key,at:{...t.before?{before:t.before.path}:{},...t.after?{after:t.after.path}:{}},...t.instrument===void 0?{}:{instrument:t.instrument},...t.before?{before:ta(t.before.value)}:{},...t.after?{after:ta(t.after.value)}:{},sentence:t.sentence})}function ta(e){return e===void 0?null:JSON.parse(JSON.stringify(e))}function na(...e){return[...new Set(e.flatMap(t=>t?Object.keys(t):[]))].sort()}function $9(e,t){return new Map((e??[]).map((n,r)=>[t(n),{item:n,index:r}]))}function Ci(e,t,n){let r=$9(e,n),a=$9(t,n);return na(Object.fromEntries(r),Object.fromEntries(a)).map(i=>({name:i,before:r.get(i),after:a.get(i)}))}function Di(e,t){let n=t.before.value??[],r=t.after.value??[];Qt(n,r)||!t.independent&&!Qt([...n].sort(),[...r].sort())||jt(e,{class:t.class,subject:"order",key:`${t.key}/order`,instrument:t.instrument,before:t.before,after:t.after,sentence:t.sentence(r)})}function pq(e,t){let n=new Map;(t??[]).forEach((s,o)=>{let d=Vt(ta(s));n.set(d,[...n.get(d)??[],o])});let r=[];(e??[]).forEach((s,o)=>{let d=Vt(ta(s)),p=n.get(d);p?.length?p.shift():r.push([s,o])});let a=new Set([...n.values()].flat()),i=(t??[]).flatMap((s,o)=>a.has(o)?[[s,o]]:[]);return{removed:r,added:i}}function Ri(e,t){let n=t.before.value,r=t.after.value;for(let a of na(n,r))t.handled.includes(a)||Qt(n[a],r[a])||jt(e,{class:"control",subject:"document",key:`${t.key}/${a}`,instrument:t.instrument,before:n[a]===void 0?void 0:{path:`${t.before.path}.${a}`,value:n[a]},after:r[a]===void 0?void 0:{path:`${t.after.path}.${a}`,value:r[a]},sentence:`${pe(a)} ${t.owner} changed.`})}function I9(e,t=sy){let n=Dn(t);if(n===0)return`${e} ${t}`;let r=e.padStart(n+1,"0");return`${r.slice(0,-n)}.${r.slice(-n)} ${t}`}function oy(e){let t=[[864e5,"day"],[36e5,"hour"],[6e4,"minute"],[1e3,"second"]];for(let[n,r]of t)if(e%n===0){let a=e/n;return`${a} ${r}${a===1?"":"s"}`}return`${e} milliseconds`}function ra(e,t=!1){if(!e)return"nothing";if(ft(e))return pe(bn(e));if("field"in e)return pe(e.field);let n=e.literal;return t&&typeof n=="string"&&/^[0-9]+$/.test(n)?I9(n):pe(String(n))}function xn(e){return e?.length?e.map(pe).join(", "):"none"}function wn(e){return pe(Vt(ta(e)))}function wa(e){if(e&&typeof e=="object"){let t=e;if(typeof t.role=="string")return`the ${pe(t.role)} role`;if(typeof t.party=="string")return`party ${pe(t.party)}`;if(typeof t.adapter=="string")return`adapter ${pe(t.adapter)}`}return typeof e=="string"?pe(e):wn(e)}function ty(e){if(e===void 0)return"nobody";if(e==="caller")return"the caller";if(e==="clock")return"the clock";if(e==="observation")return"an observed credit";if(typeof e!="object")return pe(String(e));if("party"in e)return`party ${pe(e.party)}`;let t=typeof e.parent=="string"?[e.parent]:e.parent;return`a parent ${xn(t)}`}function z9(e){switch(e.kind){case"compare":return`${ra(e.left)} ${e.operator} ${ra(e.right)}`;case"state":return`${pe(e.reference)} is in ${xn(e.states)}`;case"hours":return`${pe(e.at)} falls between ${e.start}:00 and ${e.end}:00 ${e.timezone}`;case"unique":return`${xn(e.fields)} is unique in ${pe(e.namespace)}`;case"aggregate":return`${e.measure==="count"?"the count":`the sum of ${pe(e.measure.sum)}`} of ${xn(typeof e.selection.instrument=="string"?[e.selection.instrument]:e.selection.instrument)} in ${xn(e.selection.states)} ${e.operator} ${ra(e.value)}`;case"evidence":return`evidence ${pe(`${e.family}.${e.check}`)} on ${pe(e.subject)} reads ${pe(e.result)} within ${oy(e.maxAge)}`;case"approval":return`approval ${wn(e)}`;case"all":case"any":case"not":return pe(qi(e))}}function pc(e){if(!e)return"no time";let t=e,n=t.offset===void 0||t.offset===0?"":` ${t.offset<0?"minus":"plus"} ${oy(Math.abs(t.offset))}`,r=t.localDay?`, at ${t.localDay.hour}:00 ${t.localDay.timezone} ${t.localDay.days}${t.localDay.banking?" banking":""} days ${t.localDay.direction}`:"";return`${pe(t.at)}${n}${r}`}function cc(e){let{target:t,op:n,...r}=e,a=Object.keys(r).sort().map(i=>{let s=r[i];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s;if("field"in o||"literal"in o)return`${i} ${ra(o)}`}return`${i} ${typeof s=="string"?pe(s):wn(s)}`});return`${String(n)}(${a.join(", ")})`}function cq(e,t,n){let r=[["udl","control",s=>`format ${String(s)}`,"The document is now in UDL"],["product","surface",s=>pe(String(s)),"The product id is now"],["title","surface",s=>pe(String(s)),"The product title is now"],["version","surface",s=>String(s),"The product version is now"],["currency","money",s=>String(s),"The product currency is now"]],a=t,i=n;for(let[s,o,d,p]of r)Qt(a[s],i[s])||jt(e,{class:o,subject:"document",key:`document/${s}`,before:{path:`$.${s}`,value:a[s]},after:{path:`$.${s}`,value:i[s]},sentence:`${p} ${d(i[s])} instead of ${d(a[s])}.`});Ri(e,{key:"document",owner:"on the document",before:{path:"$",value:t},after:{path:"$",value:n},handled:[...r.map(([s])=>s),"parties","objects","instruments"]})}function uq(e,t,n){for(let r of na(t.parties,n.parties)){let a=t.parties[r],i=n.parties[r];if(Qt(a,i))continue;let s=o=>`a ${o.kind}${o.role?` in role ${pe(o.role)}`:""}`;jt(e,{class:"money",subject:"party",key:`parties/${r}`,before:a&&{path:`$.parties.${r}`,value:a},after:i&&{path:`$.parties.${r}`,value:i},sentence:a?i?`Party ${pe(r)} is now ${s(i)} instead of ${s(a)}.`:`Party ${pe(r)} is removed; it was ${s(a)}.`:`Party ${pe(r)} is added as ${s(i)}.`})}}function lq(e,t,n){for(let r of Ci(t.objects,n.objects,a=>a.id)){let a=`objects/${r.name}`,i=r.before&&{path:`$.objects[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`$.objects[${r.after.index}]`,value:r.after.item},o=`object ${pe(r.name)}`;if(!i||!s){let d=(i??s).value;jt(e,{class:"control",subject:"object",key:a,before:i,after:s,sentence:`Object ${pe(r.name)} (${d.title}) is ${i?"removed":"added"}, with ${Ia(d.attachments.length,"attachment")}.`});continue}mq(e,a,o,i,s)}}function Ia(e,t){return`${e} ${t}${e===1?"":"s"}`}function mq(e,t,n,r,a){let i=r.value,s=a.value,o=(d,p,u)=>({path:`${d.path}.${p}`,value:u});i.title!==s.title&&jt(e,{class:"surface",subject:"object",key:`${t}/title`,before:o(r,"title",i.title),after:o(a,"title",s.title),sentence:`${Is(n)} is now titled ${pe(s.title)} instead of ${pe(i.title)}.`});for(let[d,p,u]of[["entryActions","control","entry actions"],["authoredFields","surface","authored fields"],["columns","surface","columns"]]){let m=i[d],c=s[d];if(!Qt(m,c)){if(Qt([...m??[]].sort(),[...c??[]].sort())){Di(e,{class:"surface",key:`${t}/${d}`,before:o(r,d,m),after:o(a,d,c),sentence:l=>`The ${u} of ${n} are now in the order ${xn(l)}.`});continue}jt(e,{class:p,subject:"object",key:`${t}/${d}`,before:m===void 0?void 0:o(r,d,m),after:c===void 0?void 0:o(a,d,c),sentence:`The ${u} of ${n} are now ${xn(c)} instead of ${xn(m)}.`})}}py(e,{key:`${t}/fields`,owner:`on ${n}`,before:o(r,"fields",i.fields),after:o(a,"fields",s.fields)});for(let d of Ci(i.attachments,s.attachments,p=>p.name)){let p=`${t}/attachments/${d.name}`,u=d.before&&{path:`${r.path}.attachments[${d.before.index}]`,value:d.before.item},m=d.after&&{path:`${a.path}.attachments[${d.after.index}]`,value:d.after.item},c=`attachment ${pe(d.name)} on ${n}`;if(!u||!m){jt(e,{class:"control",subject:"attachment",key:p,instrument:(u??m).value.instrument,before:u,after:m,sentence:u?`${Is(c)} is removed; it attached ${pe(u.value.instrument)}.`:`${Is(c)} is added; it attaches ${pe(m.value.instrument)}.`});continue}let l=m.value.instrument;for(let[y,h]of[["instrument","control"],["parent","control"],["title","surface"]]){let b=u.value[y],A=m.value[y];b!==A&&jt(e,{class:h,subject:"attachment",key:`${p}/${y}`,instrument:l,before:b===void 0?void 0:o(u,y,b),after:A===void 0?void 0:o(m,y,A),sentence:`The ${y} of ${c} is now ${A===void 0?"unset":pe(A)} instead of ${b===void 0?"unset":pe(b)}.`})}for(let y of na(u.value.parties,m.value.parties)){let h=u.value.parties[y],b=m.value.parties[y];Qt(h,b)||jt(e,{class:"money",subject:"binding",key:`${p}/parties/${y}`,instrument:l,before:h&&o(u,`parties.${y}`,h),after:b&&o(m,`parties.${y}`,b),sentence:h?b?`${Is(c)} now binds ${pe(y)} to ${wa(b)} instead of ${wa(h)}.`:`${Is(c)} no longer binds ${pe(y)}; it bound ${wa(h)}.`:`${Is(c)} now binds ${pe(y)} to ${wa(b)}.`})}Ri(e,{key:p,instrument:l,owner:`on ${c}`,before:u,after:m,handled:["name","instrument","parent","title","parties"]})}Di(e,{class:"surface",key:`${t}/attachments`,before:o(r,"attachments",i.attachments.map(d=>d.name)),after:o(a,"attachments",s.attachments.map(d=>d.name)),sentence:d=>`The attachments of ${n} are now in the order ${xn(d)}.`}),Ri(e,{key:t,owner:`on ${n}`,before:r,after:a,handled:["id","title","entryActions","authoredFields","columns","fields","attachments"]})}function Is(e){return e.charAt(0).toUpperCase()+e.slice(1)}function gq(e,t){return["label","description"].includes(t)?"surface":dy.has(e)?"money":"control"}function ey(e,t,n){if(t===void 0)return"unset";switch(e.type){case"money":return typeof t=="string"?I9(t,typeof e.currency=="string"?e.currency:sy):wn(t);case"percent":return typeof t=="number"?qo(t,n):wn(t);case"duration":return typeof t=="number"?oy(t):wn(t);default:return typeof t=="string"?pe(t):wn(t)}}function py(e,t){let n=r=>r??[];for(let r of Ci(n(t.before.value),n(t.after.value),a=>a.name)){let a=`${t.key}/${r.name}`,i=r.before&&{path:`${t.before.path}[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`${t.after.path}[${r.after.index}]`,value:r.after.item};if(i&&s&&Qt(i.value,s.value))continue;let o=(s??i).value,d=o.type==="account"?"Account":"Field",p=o.type==="account"?"account":"value"in o?"tunable":"field",u=`${d} ${pe(r.name)} ${t.owner}`;if(!i||!s||i.value.type!==s.value.type){let c=(y,h)=>y.type==="account"?`owned by ${wa(y.owner)}`:`a ${y.type} field${"value"in y?` set to ${ey(y,y.value,h)}`:""}`,l=[i?.value.type,s?.value.type].some(y=>y&&dy.has(y))?"money":"control";jt(e,{class:l,subject:p,key:a,instrument:t.instrument,before:i,after:s,sentence:i?s?`${u} is now ${c(s.value,Ti.after)} instead of ${c(i.value,Ti.before)}.`:`${u} is removed; it was ${c(i.value,Ti.before)}.`:`${u} is added, ${c(s.value,Ti.after)}.`});continue}let m=s.value.type;for(let c of na(i.value,s.value)){if(c==="name"||Qt(i.value[c],s.value[c]))continue;let l=i.value[c],y=s.value[c],h=m==="account"?"account":c==="value"?"tunable":"field",b;m==="account"&&c==="owner"?b=`${u} is now owned by ${wa(y)} instead of ${wa(l)}.`:["value","minimum","maximum"].includes(c)?b=`${c==="value"?"The value":`The ${c}`} of ${u.charAt(0).toLowerCase()}${u.slice(1)} is now ${ey(s.value,y,Ti.after)} instead of ${ey(i.value,l,Ti.before)}.`:c==="optional"?b=`${u} is now ${y?"optional":"required"}.`:c==="sensitive"?b=`${u} is ${y?"now":"no longer"} sensitive.`:b=`The ${c} of ${u.charAt(0).toLowerCase()}${u.slice(1)} is now ${y===void 0?"unset":typeof y=="string"?pe(y):wn(y)} instead of ${l===void 0?"unset":typeof l=="string"?pe(l):wn(l)}.`,jt(e,{class:c==="value"&&yq.has(m)||c==="optional"||c==="sensitive"?"control":gq(m,c),subject:h,key:`${a}/${c}`,instrument:t.instrument,before:l===void 0?void 0:{path:`${i.path}.${c}`,value:l},after:y===void 0?void 0:{path:`${s.path}.${c}`,value:y},sentence:b})}}Di(e,{class:"surface",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(r=>r.name)},after:{...t.after,value:n(t.after.value).map(r=>r.name)},sentence:r=>`The fields ${t.owner} are now in the order ${xn(r)}.`})}function k9(e,t){let n=a=>a??[],r=a=>["shift","step","banking"].includes(a.op)?"control":"money";for(let a of Ci(n(t.before.value),n(t.after.value),i=>i.target)){let i=a.before&&{path:`${t.before.path}[${a.before.index}]`,value:a.before.item},s=a.after&&{path:`${t.after.path}[${a.after.index}]`,value:a.after.item};if(i&&s&&Qt(i.value,s.value))continue;let o=`${pe(a.name)} ${t.owner}`;jt(e,{class:[i,s].some(d=>d&&r(d.value)==="money")?"money":"control",subject:"calculation",key:`${t.key}/${a.name}`,instrument:t.instrument,before:i,after:s,sentence:i?s?`The calculation of ${o} is now ${cc(s.value)} instead of ${cc(i.value)}.`:`The calculation of ${o} is removed; it was ${cc(i.value)}.`:`The calculation of ${o} is added: ${cc(s.value)}.`})}Di(e,{class:"control",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(a=>a.target)},after:{...t.after,value:n(t.after.value).map(a=>a.target)},sentence:a=>`The calculations ${t.owner} now run in the order ${xn(a)}.`})}function ny(e,t){let{removed:n,added:r}=pq(t.before.value,t.after.value),a=t.render;for(let[s,o]of n)jt(e,{class:"control",subject:t.subject,key:`${t.key}/${Vt(ta(s))}`,instrument:t.instrument,before:{path:`${t.before.path}[${o}]`,value:s},sentence:`${t.lead} no longer ${t.subject==="invocation"?"runs":"requires"} ${a(s)}.`});for(let[s,o]of r)jt(e,{class:"control",subject:t.subject,key:`${t.key}/${Vt(ta(s))}`,instrument:t.instrument,after:{path:`${t.after.path}[${o}]`,value:s},sentence:`${t.lead} now ${t.subject==="invocation"?"runs":"requires"} ${a(s)}.`});if(n.length||r.length)return;let i=s=>(s??[]).map(o=>Vt(ta(o)));Qt(i(t.before.value),i(t.after.value))||jt(e,{class:t.subject==="invocation"?"control":"surface",subject:"order",key:`${t.key}/order`,instrument:t.instrument,before:t.before,after:t.after,sentence:`${t.lead} now ${t.subject==="invocation"?"runs its invocations":"checks its requirements"} in a different order.`})}function hq(e){let t=e,n=t.instrument?`a new ${pe(t.instrument)}`:t.reference?pe(t.reference):`each selected ${xn(typeof t.selection.instrument=="string"?[t.selection.instrument]:t.selection.instrument)}`;return`${pe(t.action)} on ${n}`}function Bo(e){switch(e.operation.slice(18)){case"create":return`moves ${ra(e.amount,!0)} from ${pe(e.from)} to ${pe(e.to)}`;case"reserve":return`reserves ${ra(e.amount,!0)} from ${pe(e.from)} to ${pe(e.to)}`;case"post":return`posts the reservation ${pe(e.transfer)}`;case"void":return`releases the reservation ${pe(e.transfer)}`;default:return`runs ${pe(e.operation)}`}}function fq(e,t){let n=r=>r;for(let r of Ci(n(t.before.value),n(t.after.value),a=>a.key)){let a=`${t.key}/${r.name}`,i=r.before&&{path:`${t.before.path}[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`${t.after.path}[${r.after.index}]`,value:r.after.item};if(i&&s&&Qt(i.value,s.value))continue;if(!i||!s||i.value.operation!==s.value.operation){jt(e,{class:"money",subject:"move",key:a,instrument:t.instrument,before:i,after:s,sentence:i?s?`${t.lead} now ${Bo(s.value)} in move ${pe(r.name)}, replacing a move that ${Bo(i.value)}.`:`${t.lead} no longer ${Bo(i.value)} (move ${pe(r.name)}).`:`${t.lead} now also ${Bo(s.value)} (move ${pe(r.name)}).`});continue}let o=i.value,d=s.value,p=y=>ra(y.amount,!0),u=(y,h,b,A)=>{Qt(b,A)||jt(e,{class:"money",subject:"move",key:`${a}/${y}`,instrument:t.instrument,before:b===void 0?void 0:{path:`${i.path}.${y}`,value:b},after:A===void 0?void 0:{path:`${s.path}.${y}`,value:A},sentence:h})},m=d.operation==="internal_transfer.reserve"?"reserves":"moves";u("amount",`${t.lead} now ${m} ${p(d)} instead of ${p(o)} from ${pe(d.from??"")} (move ${pe(r.name)}).`,o.amount,d.amount),u("from",`${t.lead} now ${m} ${p(d)} from ${pe(d.from??"")} instead of ${pe(o.from??"")} (move ${pe(r.name)}).`,o.from,d.from),u("to",`${t.lead} now ${m} ${p(d)} to ${pe(d.to??"")} instead of ${pe(o.to??"")} (move ${pe(r.name)}).`,o.to,d.to),u("transfer",`${t.lead} now settles the reservation ${pe(d.transfer??"")} instead of ${pe(o.transfer??"")} (move ${pe(r.name)}).`,o.transfer,d.transfer),u("capture",`${t.lead} now keeps move ${pe(r.name)} as ${d.capture?pe(d.capture):"nothing"} instead of ${o.capture?pe(o.capture):"nothing"}.`,o.capture,d.capture),u("boundary",`${t.lead} now holds move ${pe(r.name)} at ${d.boundary?wa(d.boundary):"no boundary"} instead of ${o.boundary?wa(o.boundary):"no boundary"}.`,o.boundary,d.boundary);let c=o.economics,l=d.economics;if(!c||!l){let y=h=>h?`${h.purpose.replaceAll("_"," ")} from ${pe(h.sourceParty)}`:"no purpose";u("economics",`${t.lead} now books move ${pe(r.name)} as ${y(l)} instead of ${y(c)}.`,c,l)}else u("economics.purpose",`${t.lead} now books move ${pe(r.name)} as ${l.purpose.replaceAll("_"," ")} instead of ${c.purpose.replaceAll("_"," ")}.`,c.purpose,l.purpose),u("economics.sourceParty",`${t.lead} now names ${pe(l.sourceParty)} as the source of move ${pe(r.name)} instead of ${pe(c.sourceParty)}.`,c.sourceParty,l.sourceParty),u("economics.reversalOf",l.reversalOf?c.reversalOf?`${t.lead} now books move ${pe(r.name)} as the reversal of ${pe(l.reversalOf)} instead of ${pe(c.reversalOf)}.`:`${t.lead} now books move ${pe(r.name)} as the reversal of ${pe(l.reversalOf)}.`:`${t.lead} no longer books move ${pe(r.name)} as the reversal of ${pe(c.reversalOf)}.`,c.reversalOf,l.reversalOf),u("economics.taxOn",l.taxOn?c.taxOn?`${t.lead} now books move ${pe(r.name)} as the tax on move ${pe(l.taxOn)} instead of ${pe(c.taxOn)}.`:`${t.lead} now books move ${pe(r.name)} as the tax on move ${pe(l.taxOn)}.`:`${t.lead} no longer books move ${pe(r.name)} as the tax on move ${pe(c.taxOn)}.`,c.taxOn,l.taxOn);Ri(e,{key:a,instrument:t.instrument,owner:`on move ${pe(r.name)} of ${t.lead.charAt(0).toLowerCase()}${t.lead.slice(1)}`,before:i,after:s,handled:["key","operation","amount","from","to","transfer","capture","boundary","economics"]})}Di(e,{class:"money",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(r=>r.key)},after:{...t.after,value:n(t.after.value).map(r=>r.key)},sentence:r=>`${t.lead} now runs its moves in the order ${xn(r)}.`})}function _q(e){return e.fields.some(t=>dy.has(t.type))||Object.values(e.actions).some(t=>t.moves.length>0)}function bq(e,t,n){for(let r of Ci(t.instruments,n.instruments,a=>a.id)){let a=`instruments/${r.name}`,i=r.before&&{path:`$.instruments[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`$.instruments[${r.after.index}]`,value:r.after.item};if(!(i&&s&&Qt(i.value,s.value))){if(!i||!s){let o=(i??s).value;jt(e,{class:_q(o)?"money":"control",subject:"instrument",key:a,instrument:r.name,before:i,after:s,sentence:`Instrument ${pe(r.name)} is ${i?"removed":"added"}, with ${Ia(o.actionOrder.length,"action")}: ${xn(o.actionOrder)}.`});continue}xq(e,a,r.name,i,s)}}}function xq(e,t,n,r,a){let i=r.value,s=a.value,o=pe(n),d=(m,c,l)=>l===void 0?void 0:{path:`${m.path}.${c}`,value:l},p=(m,c,l,y)=>{Qt(i[m],s[m])||jt(e,{class:c,subject:l,key:`${t}/${m}`,instrument:n,before:d(r,m,i[m]),after:d(a,m,s[m]),sentence:`The ${m} of instrument ${o} is now ${y(s[m])} instead of ${y(i[m])}.`})},u=m=>m===void 0?"unset":typeof m=="string"?pe(m):wn(m);p("summary","surface","instrument",u),p("template","surface","instrument",u),p("examples","surface","instrument",m=>Array.isArray(m)?Ia(m.length,"example"):"none"),p("scope","control","instrument",u),p("revisioned","control","instrument",u),p("subject","control","instrument",u),p("oncePerRecord","control","instrument",u),p("accepts","control","instrument",u),p("persons","control","instrument",m=>Array.isArray(m)?m.map(c=>pe(`${c.name}${c.optional?"?":""}`)).join(", "):"none"),p("family","control","instrument",m=>{if(!m||typeof m!="object")return"none";let c=m;return`${pe(`${c.module}.${c.exportPath}`)} ${c.digest?`at ${c.digest.slice(0,12)}`:`revision ${c.revision}`}`}),py(e,{key:`${t}/fields`,instrument:n,owner:`on ${o}`,before:{path:`${r.path}.fields`,value:i.fields},after:{path:`${a.path}.fields`,value:s.fields}}),k9(e,{key:`${t}/calculate`,instrument:n,owner:`on ${o}`,before:{path:`${r.path}.calculate`,value:i.calculate},after:{path:`${a.path}.calculate`,value:s.calculate}}),vq(e,t,n,r,a);for(let m of na(i.actions,s.actions)){let c=Object.hasOwn(i.actions,m)?i.actions[m]:void 0,l=Object.hasOwn(s.actions,m)?s.actions[m]:void 0,y=c&&{path:`${r.path}.actions.${m}`,value:c},h=l&&{path:`${a.path}.actions.${m}`,value:l};if(y&&h&&Qt(y.value,h.value))continue;let b=`Action ${pe(m)} on ${o}`;if(!y||!h){let A=(y??h).value;jt(e,{class:A.moves.length?"money":"control",subject:"action",key:`${t}/actions/${m}`,instrument:n,before:y,after:h,sentence:`${b} is ${y?"removed":"added"}; it is run by ${ty(A.actor)}${A.moves.length?` and ${A.moves.map(Bo).join(", then ")}`:""}.`});continue}$q(e,`${t}/actions/${m}`,n,b,y,h)}Di(e,{class:"surface",key:`${t}/actionOrder`,instrument:n,before:{path:`${r.path}.actionOrder`,value:i.actionOrder},after:{path:`${a.path}.actionOrder`,value:s.actionOrder},independent:!0,sentence:m=>`The actions of ${o} are now listed in the order ${xn(m)}.`}),ny(e,{key:`${t}/invariants`,instrument:n,subject:"requirement",lead:`Instrument ${o} always`,render:z9,before:{path:`${r.path}.invariants`,value:i.invariants},after:{path:`${a.path}.invariants`,value:s.invariants}}),wq(e,t,n,r,a),Ri(e,{key:t,instrument:n,owner:`on instrument ${o}`,before:r,after:a,handled:["id","title","summary","template","examples","scope","revisioned","subject","oncePerRecord","accepts","persons","family","fields","calculate","lifecycle","actions","actionOrder","invariants","reports"]})}function vq(e,t,n,r,a){let i=r.value.lifecycle,s=a.value.lifecycle,o=`${r.path}.lifecycle`,d=`${a.path}.lifecycle`,p=pe(n);for(let u of na(Object.fromEntries(i.states.map(m=>[m,m])),Object.fromEntries(s.states.map(m=>[m,m])))){let m=i.states.indexOf(u),c=s.states.indexOf(u);m>=0&&c>=0||jt(e,{class:"control",subject:"state",key:`${t}/states/${u}`,instrument:n,before:m>=0?{path:`${o}.states[${m}]`,value:u}:void 0,after:c>=0?{path:`${d}.states[${c}]`,value:u}:void 0,sentence:`State ${pe(u)} is ${m>=0?"removed from":"added to"} ${p}.`})}Di(e,{class:"surface",key:`${t}/states`,instrument:n,before:{path:`${o}.states`,value:i.states},after:{path:`${d}.states`,value:s.states},sentence:u=>`The states of ${p} are now listed in the order ${xn(u)}.`}),i.initial!==s.initial&&jt(e,{class:"control",subject:"state",key:`${t}/initial`,instrument:n,before:{path:`${o}.initial`,value:i.initial},after:{path:`${d}.initial`,value:s.initial},sentence:`A new ${p} now starts in ${pe(s.initial)} instead of ${pe(i.initial)}.`}),Qt(i.ends&&[...i.ends].sort(),s.ends&&[...s.ends].sort())||jt(e,{class:"control",subject:"state",key:`${t}/ends`,instrument:n,before:i.ends&&{path:`${o}.ends`,value:i.ends},after:s.ends&&{path:`${d}.ends`,value:s.ends},sentence:s.ends?`A ${p} now ends in ${xn(s.ends)}.`:`A ${p} now ends in the states no action leaves.`});for(let u of na(i.labels,s.labels)){let m=i.labels?.[u],c=s.labels?.[u];m!==c&&jt(e,{class:"surface",subject:"state",key:`${t}/labels/${u}`,instrument:n,before:m===void 0?void 0:{path:`${o}.labels.${u}`,value:m},after:c===void 0?void 0:{path:`${d}.labels.${u}`,value:c},sentence:`State ${pe(u)} of ${p} is now labelled ${c===void 0?"with its name":pe(c)} instead of ${m===void 0?"its name":pe(m)}.`})}for(let u of na(i.transitions,s.transitions)){let m=Object.hasOwn(i.transitions,u)?i.transitions[u]:void 0,c=Object.hasOwn(s.transitions,u)?s.transitions[u]:void 0;if(Qt(m,c))continue;let l=y=>y?`from ${xn(y.from)} to ${pe(y.to)}`:"no state change";jt(e,{class:"control",subject:"transition",key:`${t}/transitions/${u}`,instrument:n,before:m&&{path:`${o}.transitions.${u}`,value:m},after:c&&{path:`${d}.transitions.${u}`,value:c},sentence:`Action ${pe(u)} on ${p} now moves ${l(c)} instead of ${l(m)}.`})}Ri(e,{key:`${t}/lifecycle`,instrument:n,owner:`on the lifecycle of ${p}`,before:{path:o,value:i},after:{path:d,value:s},handled:["states","initial","ends","labels","transitions"]})}function $q(e,t,n,r,a,i){let s=a.value,o=i.value,d=(m,c,l)=>l===void 0?void 0:{path:`${m.path}.${c}`,value:l},p=(m,c,l,y)=>{Qt(s[m],o[m])||jt(e,{class:c,subject:l,key:`${t}/${m}`,instrument:n,before:d(a,m,s[m]),after:d(i,m,o[m]),sentence:y(s[m],o[m])})},u=m=>m===void 0?"unset":typeof m=="string"?pe(m):wn(m);for(let m of["summary","title","event","publicAction"])p(m,"surface","action",(c,l)=>`The ${m==="publicAction"?"public name":m} of ${r.charAt(0).toLowerCase()}${r.slice(1)} is now ${u(l)} instead of ${u(c)}.`);p("actor","control","actor",(m,c)=>`${r} is now run by ${ty(c)} instead of ${ty(m)}.`),p("purpose","control","action",(m,c)=>`${r} is now ${c?`an ${String(c)}`:"neither an obligation nor an option"} instead of ${m?`an ${String(m)}`:"neither"}.`),p("allowZero","money","action",(m,c)=>`${r} ${c?"now allows":"no longer allows"} a zero amount.`),p("singleHanded","control","action",(m,c)=>`${r} ${c?"now runs":"no longer runs"} on one staff member's call.`);for(let m of["due","deadline"])p(m,"control","clock",(c,l)=>l===void 0?`${r} no longer has a ${m==="due"?"due time":"deadline"}; it was ${pc(c)}.`:c===void 0?`${r} now has a ${m==="due"?"due time":"deadline"} at ${pc(l)}.`:`${r} now has its ${m==="due"?"due time":"deadline"} at ${pc(l)} instead of ${pc(c)}.`);p("reminder","control","clock",(m,c)=>`${r} now ${c?`reminds ${wn(c)}`:"sends no reminder"} instead of ${m?wn(m):"no reminder"}.`),p("send","control","action",(m,c)=>`${r} now ${c?`sends ${wn(c)}`:"sends no message"} instead of ${m?wn(m):"no message"}.`),p("read","control","action",(m,c)=>`${r} now ${c?`reads ${wn(c)}`:"reads nothing"} instead of ${m?wn(m):"no read"}.`),p("follows","control","action",(m,c)=>`${r} now follows ${u(c)} instead of ${u(m)}.`),p("expansionLimit","control","action",(m,c)=>`The expansion limit of ${r.charAt(0).toLowerCase()}${r.slice(1)} is now ${u(c)} instead of ${u(m)}.`),p("subject","control","requirement",()=>`${r} now asks its subject for ${Ia(o.subject?.requirements.length??0,"requirement")} through ${Ia(o.subject?.adapters.length??0,"adapter")} instead of ${Ia(s.subject?.requirements.length??0,"requirement")} through ${Ia(s.subject?.adapters.length??0,"adapter")}.`),py(e,{key:`${t}/input`,instrument:n,owner:`in the input of ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:{path:`${a.path}.input`,value:s.input},after:{path:`${i.path}.input`,value:o.input}}),ny(e,{key:`${t}/requires`,instrument:n,subject:"requirement",lead:r,render:z9,before:{path:`${a.path}.requires`,value:s.requires},after:{path:`${i.path}.requires`,value:o.requires}});for(let m of na(s.set,o.set)){let c=s.set?.[m],l=o.set?.[m];Qt(c,l)||jt(e,{class:"control",subject:"action",key:`${t}/set/${m}`,instrument:n,before:c&&{path:`${a.path}.set.${m}`,value:c},after:l&&{path:`${i.path}.set.${m}`,value:l},sentence:l?`${r} now sets ${pe(m)} to ${ra(l)}${c?` instead of ${ra(c)}`:""}.`:`${r} no longer sets ${pe(m)}; it set it to ${ra(c)}.`})}k9(e,{key:`${t}/calculate`,instrument:n,owner:`in ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:{path:`${a.path}.calculate`,value:s.calculate},after:{path:`${i.path}.calculate`,value:o.calculate}}),fq(e,{key:`${t}/moves`,instrument:n,lead:r,before:{path:`${a.path}.moves`,value:s.moves},after:{path:`${i.path}.moves`,value:o.moves}}),ny(e,{key:`${t}/invoke`,instrument:n,subject:"invocation",lead:r,render:hq,before:{path:`${a.path}.invoke`,value:s.invoke},after:{path:`${i.path}.invoke`,value:o.invoke}}),Ri(e,{key:t,instrument:n,owner:`on ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:a,after:i,handled:["summary","title","event","publicAction","actor","purpose","allowZero","singleHanded","due","deadline","reminder","send","read","follows","expansionLimit","subject","input","requires","set","calculate","moves","invoke"]})}function wq(e,t,n,r,a){let i=s=>s??[];for(let s of Ci(i(r.value.reports),i(a.value.reports),o=>o.identity.id)){let o=s.before&&{path:`${r.path}.reports[${s.before.index}]`,value:s.before.item},d=s.after&&{path:`${a.path}.reports[${s.after.index}]`,value:s.after.item};if(o&&d&&Qt(o.value,d.value))continue;let p=`Report ${pe(s.name)} on ${pe(n)}`;jt(e,{class:"surface",subject:"report",key:`${t}/reports/${s.name}`,instrument:n,before:o,after:d,sentence:o?d?`${p} now has a different shape, version ${d.value.identity.version} instead of ${o.value.identity.version}.`:`${p} is removed.`:`${p} is added.`})}}function w9(e){if(!e||typeof e!="object")return;let t=e,n=t.role??t.party;return typeof n=="string"?n:void 0}function ry(e,t,n){if(typeof e=="string"){if(e===t)return n;let r=`party.${t}`;return e===r||e.startsWith(`${r}.`)?`party.${n}${e.slice(r.length)}`:e}return Array.isArray(e)?e.map(r=>ry(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,a])=>[r,ry(a,t,n)])):e}function Iq(e,t,n){let r=new Set,a=new Map;for(let i of e){if(i.subject!=="binding"||i.kind!=="changed")continue;let s=w9(i.before),o=w9(i.after);if(!s||!o||s===o||!i.instrument||!t.instruments.some(c=>c.id===i.instrument)||!n.instruments.some(c=>c.id===i.instrument))continue;let d=e.filter(c=>c!==i&&!r.has(c)&&c.kind==="changed"&&c.subject!=="binding"&&c.instrument===i.instrument&&Qt(ry(c.before,s,o),c.after));if(!d.length)continue;d.forEach(c=>r.add(c));let p=d.filter(c=>c.class==="money").length,u=d.length-p,m=[p?Ia(p,"money reference"):"",u?Ia(u,"control reference"):""].filter(Boolean);a.set(i,{...i,sentence:`${i.sentence.replace(/\.$/,"")}, which reroutes ${m.join(" and ")} in ${pe(i.instrument)}.`,follows:d})}return e.filter(i=>!r.has(i)).map(i=>a.get(i)??i)}var uc,Qt,pe,sy,Ti,dy,yq,q9=ve(()=>{"use strict";gs();ko();hs();$s();uc=["money","control","surface"];Qt=(e,t)=>Vt(ta(e))===Vt(ta(t)),pe=e=>`\`${e}\``;sy=Ka;Ti={before:1e8,after:1e8};dy=new Set(["money","percent","account"]),yq=new Set(["date","duration"])});var ct,L9,j9,cy,zq,kq,qq,Lq,jq,Aq,SS,A9=ve(()=>{"use strict";Fa();xs();ct=Ce(),L9=Y({min:Gn().int().nonnegative(),max:Gn().int().nonnegative().nullable()}),j9=rn([Y({kind:he("instrument"),instrument:ct}),Y({kind:he("role"),role:Oe(un)}),Y({kind:he("party"),party:ct}),Y({kind:he("adapter"),adapter:ct})]),cy=Y({path:ct,scope:ct,instrument:ct,field:ct,owner:j9,book:Oe(["cash","claim"]),key:ct.optional(),contra:Ir()}),zq=rn([j9,Y({kind:Oe(["caller","clock","observation"])}),Y({kind:he("parent"),instruments:ye(ct)})]),kq=Y({kind:Oe(["reference","child"]),via:Oe(["field","attachment","invocation","parent_actor"]),name:ct,targetKind:Oe(["instrument","object"]),targets:ye(ct),cardinality:L9}),qq=Y({key:ct,operation:Bx,amount:vt.nullable(),from:ye(cy),to:ye(cy),disposition:Oe(["held","paid","released","claim","unresolved"]),transfer:ct.nullable(),reservations:ye(Y({instrument:ct,action:ct,key:ct})),economics:Y({purpose:Oe(Zo),sourceParty:ct,reversalOf:ct.nullable()}).nullable(),share:Y({base:ct,bps:Gn(),value:Ce().nullable()}).nullable()}),Lq=Y({name:ct,alias:ct.nullable(),title:ct,actor:tr.shape.actor,roles:ye(zq),from:ye(ct),to:ct.nullable(),references:ye(_s).optional(),invokedBy:ye(Y({instrument:ct,action:ct,alias:ct.nullable(),invocation:tr.shape.invoke.unwrap().element})).optional(),inputs:tr.shape.input,subject:tr.shape.subject,prerequisites:tr.shape.requires,due:tr.shape.due.unwrap().nullable(),deadline:tr.shape.deadline.unwrap().nullable(),calculations:ye(So),assignments:tr.shape.set.unwrap(),moves:tr.shape.moves,moneyEffects:ye(qq),invokes:tr.shape.invoke.unwrap()}),jq=Oe(["stage_and_decisions","payment_review","held_funds","reserved_payment","payment_calendar","funding_progress","cancellation_review","external_checks","report_view"]),Aq=Y({id:ct,summary:ct.optional(),subject:ct.optional(),template:ct.optional(),fields:ye(_s),accounts:ye(cy),relationships:ye(kq),calculations:ye(So),invariants:ye(Wp),initialState:ct,lifecycle:Y({initial:ct,states:ye(Y({name:ct,label:ct,terminal:Ir()})),cancellationActions:ye(ct)}),actions:ye(Lq),reports:Yp.shape.reports.unwrap(),structures:ye(jq)}),SS=Y({currency:ct,percentWhole:Gn().int().positive(),parties:gn(ct,$m),objects:ye(Y({...zm.shape,attachments:ye(Y({...Im.shape,cardinality:L9}))})),instruments:ye(Aq)})});var P9=ve(()=>{"use strict";A9()});var In=ve(()=>{"use strict";xs();hs();Wx();ko();v9();gs();q9();Ya();Mm();Gm();r9();Xm();Tm();bm();Vm();P9();$s()});function U(e,t,n,r="HSX1001"){return je(e,r,t,n)}function je(e,t,n,r){throw new St({code:t,message:n,fix:r,span:e.span,...e.source?{source:e.source}:{}})}function Bn(e,t,n,r,a,{values:i,code:s="given_twice"}={}){let o=m=>e.get(m.source??"program")??"",d=m=>{let{line:c,column:l}=_n(o(m),m.span.start),y=m.source??"program";return`${y===(r.source??"program")?"":`${y} `}${c}:${l}`},[p,u]=(i??[]).map(m=>o(m).slice(m.span.start,m.span.end).trim());throw new St({code:s,message:p&&u&&p!==u?`${t} with different values: ${p} at ${d(n)} and ${u} at ${d(r)}`:`${t}, at ${d(n)} and ${d(r)}`,fix:a,span:r.span,...r.source?{source:r.source}:{},related:[{source:n.source??"program",span:n.span,message:"First given here"}]})}function ot(e,t){try{return t()}catch(n){if(!(n instanceof St))throw n;e.push(n.diagnostic);return}}function lc(e){let t=r=>(r.source??"program")==="program",n=new Set;return e.filter(r=>{let a=JSON.stringify([r.code,r.source??"program",r.span.start,r.span.end,r.message]);return n.has(a)?!1:(n.add(a),!0)}).sort((r,a)=>Number(t(a))-Number(t(r))||S9(r.source??"program",a.source??"program")||r.span.start-a.span.start||S9(r.code,a.code))}function Pq(e,t){let n=Array.from({length:e.length+1},(r,a)=>Array.from({length:t.length+1},(i,s)=>a===0?s:s===0?a:0));for(let r=1;r<=e.length;r++)for(let a=1;a<=t.length;a++)n[r][a]=Math.min(n[r-1][a]+1,n[r][a-1]+1,n[r-1][a-1]+(e[r-1]===t[a-1]?0:1)),r>1&&a>1&&e[r-1]===t[a-2]&&e[r-2]===t[a-1]&&(n[r][a]=Math.min(n[r][a],n[r-2][a-2]+1));return n[e.length][t.length]}function en(e,t){let n=Math.max(1,Math.floor(e.length/3)),r,a=n+1;for(let i of t){let s=Pq(e,i);s<a&&([r,a]=[i,s])}return r===void 0?"":` Did you mean \`${r}\`?`}function Oq(e,t){let n=Dn(t),r=10n**BigInt(n),a=String(e%r).padStart(n,"0");return`${e/r}${n?`.${a}`:""} ${t}`}function mc(e,t,n="SAR"){let r=e.value;if(!/^\d{1,18}$/.test(r))return{code:Z9,message:`${t} is money, and "${r}" is text`,fix:`write an amount such as 0 ${n}`,span:e.span,...e.source?{source:e.source}:{}};let a=Oq(BigInt(r),n);return{code:Z9,message:`${t} is money, and the text "${r}" counts minor units, so it reads as ${a}`,fix:`write ${a.replace(/\.0+ /," ")}`,span:e.span,...e.source?{source:e.source}:{}}}function yc(e,t,n){return{code:"currency_mismatch",message:`${t} is in ${n}, and ${e.value} is not`,fix:`write the amount in ${n}, or convert it with ratio into a ${n} field`,span:e.span,...e.source?{source:e.source}:{}}}var St,S9,Z9,Er=ve(()=>{"use strict";Ha();In();St=class extends Error{constructor(n){super(n.message);this.diagnostic=n}diagnostic};S9=(e,t)=>e<t?-1:e>t?1:0;Z9="money_text_literal"});function my(e){return e>=Uo.needs_review?"needs_review":e>=Uo.complex?"complex":e>=Uo.standard?"standard":"simple"}function yy(e){let t={instruments:e.instruments.length,states:0,actions:0,transitions:0,invocations:0,moves:0,unwinds:0,requires:0,clocks:0,calculations:0,expressions:0,parties:Object.keys(e.parties).length,actors:0,exposures:0},n=new Set,r=o=>typeof o=="string"?o:"party"in o?`party:${o.party}`:`parent:${[o.parent].flat().join(",")}`,a=(o=[])=>o.reduce((d,p)=>d+(["compare","state","all","any","not"].includes(p.kind)?ji(p):0),0);for(let o of e.instruments){t.states+=o.lifecycle.states.length,t.expressions+=a(o.invariants)+o.calculate.reduce((d,p)=>d+tc(p),0),t.transitions+=Object.keys(o.lifecycle.transitions).length,t.requires+=o.invariants?.length??0,t.calculations+=o.calculate.length;for(let d of Object.values(o.actions))t.actions++,t.invocations+=d.invoke?.length??0,t.moves+=d.moves.length,t.unwinds+=d.moves.filter(p=>p.operation==="internal_transfer.reserve"||p.operation==="internal_transfer.void").length,t.requires+=d.requires.length,t.clocks+=+!!d.due+ +!!d.deadline+ +!!d.reminder,t.calculations+=d.calculate?.length??0,t.expressions+=a(d.requires)+(d.calculate??[]).reduce((p,u)=>p+tc(u),0)+Object.values(d.set??{}).reduce((p,u)=>p+ei(u),0)+d.moves.reduce((p,u)=>p+("amount"in u?ei(u.amount):0),0)+(d.invoke??[]).reduce((p,u)=>p+(u.guard?ji(u.guard):0)+Object.values(u.input).reduce((m,c)=>m+ei(c),0),0),d.publicAction&&t.exposures++,n.add(r(d.actor))}t.actors=n.size;let i=ly,s=Math.round(i.flow*Math.log2(1+t.transitions+t.invocations)+i.move*t.moves+i.unwind*t.unwinds+i.clock*t.clocks+i.party*t.parties+i.actor*t.actors+i.requirement*t.requires+i.calculation*t.calculations+i.expression*t.expressions);return{factor:s,tier:my(s),counts:t}}function Fo(e){let t={},n=new Set,r=(a,i)=>{let s=`${a}.${i}`;if(t[s])return t[s];if(n.has(s))throw new Error(`Invocation cycle at ${s}`);let o=e.instruments.find(m=>m.id===a),d=o?.actions[i];if(!o||!d)throw new Error(`Unknown invocation ${s}`);n.add(s);let p=(m=[])=>m.filter(c=>c.op==="rate_of").length,u={transfers:d.moves.length,accounts:i==="create"?o.fields.filter(m=>m.type==="account"&&m.owner==="self").length:0,invocations:0,rateSteps:(p(d.calculate)+2*p(o.calculate))*Dm(an(e.udl))};for(let m of d.invoke??[]){let c=Sq(e,o,d,m).map(y=>r(y,m.action)),l="selection"in m?m.selection.limit:"instrument"in m?m.range?.maximum??1:1;u.transfers+=l*Math.max(0,...c.map(y=>y.transfers)),u.accounts+=l*Math.max(0,...c.map(y=>y.accounts)),u.invocations+=l*(1+Math.max(0,...c.map(y=>y.invocations))),u.rateSteps+=l*Math.max(0,...c.map(y=>y.rateSteps))}return n.delete(s),t[s]=u,u};for(let a of e.instruments)for(let i of Object.keys(a.actions))r(a.id,i);return{actions:t,complexity:yy(e)}}function Sq(e,t,n,r){if("instrument"in r)return[r.instrument];if("selection"in r)return typeof r.selection.instrument=="string"?[r.selection.instrument]:[...r.selection.instrument];let a=mt(e,t,r.reference,n.input);return a?.type==="ref"?typeof a.target=="string"?[a.target]:[...a.target]:[]}function R9(e,t=Fo(e)){let n=[];for(let r of e.instruments){let a=r.lifecycle.transitions.create?.to??r.lifecycle.initial;for(let[i,s]of Object.entries(r.actions)){let o=t.actions[`${r.id}.${i}`],d=i!=="create"&&s.publicAction&&r.subject&&r.lifecycle.transitions[i]?.from.includes(a)?t.actions[`${r.id}.create`]:void 0,p=1+o.invocations+(d?1+d.invocations:0),u=o.transfers+(d?.transfers??0);(p>ki||u>Fp)&&n.push({instrument:r.id,action:i,create:!!d,invocations:p,transfers:u})}}return n}var uy,T9,D9,Uo,ly,Ko=ve(()=>{"use strict";In();uy=262144,T9=2*uy,D9=["simple","standard","complex","needs_review"],Uo={standard:60,complex:150,needs_review:400},ly={flow:10,move:2,unwind:2,clock:2,party:3,actor:3,requirement:1,calculation:1,expression:1}});function E9(e,t,n,r){let a=new Set;return e.flatMap(i=>{let s=ot(r,()=>(a.has(i.name)&&U(i,`check "${i.name}" is declared twice`,"rename one","given_twice"),a.add(i.name),Zq(i,t,n)));return s?[s]:[]})}function Zq(e,t,n){let r=[],a={},i=[],s=[],o=new Map,d=new Set,p=new Set,u=new Set,m,c=(g,I,O,D)=>{let _=[...I];return _.includes(g.name)||U(g,`${O} ${g.name} is not declared.${en(g.name,_)}`,D,"check_unknown_name"),g.name},l=g=>c(g,r.map(I=>I.id),"customer",`declare customer ${g.name} "Name" before this step`),y=g=>c(g,o.keys(),"object","create it on an earlier step"),h=Object.values(t.parties).flatMap(g=>g.kind==="staff"&&g.role?[g.role]:[]),b=g=>c(g,h,"staff role","name a role a staff party of the program holds"),A=new Set,Z=g=>{if(!g||typeof g!="object")return;let{kind:I,policy:O}=g;I==="approval"&&typeof O=="string"&&A.add(O),Object.values(g).forEach(Z)};for(let g of t.instruments)for(let I of Object.values(g.actions))Z(I.requires);let k=(g,I,O)=>{I.has(g.name)&&U(g,`${O} twice`,"rename one","given_twice"),I.add(g.name)},f=(g,I)=>{(d.has(g.name)||p.has(g.name))&&U(g,"remembered twice","rename one","given_twice"),I.add(g.name)},z=(g,I,O=!1)=>{g.kind!=="money"&&U(g,"expected an amount",`write an amount such as 100 ${I}`);let D=O&&g.value.startsWith("-"),_=n(D?{...g,value:g.value.slice(1)}:g);return!g.value.endsWith(` ${I}`)&&_!=="0"&&U(g,`a balance is in ${I}, and ${g.value} is not`,`write the balance in ${I}`,"currency_mismatch"),D&&_!=="0"?`-${_}`:_},P=g=>{let I=t.objects.find(D=>D.id===g),O=new Set(I.attachments.map(D=>D.instrument));return t.instruments.filter(D=>O.has(D.id))},T=(g,I)=>{let O=t.objects.find(_=>_.id===g);c(I,O.attachments.map(_=>_.name),`${g} attachment`,`name an attachment of object ${g}`);let{instrument:D}=O.attachments.find(_=>_.name===I.name);return t.instruments.find(_=>_.id===D)},$=g=>{let I=g.name.split(".");if(I.length===1)return c(g,[Ei,...r.map(X=>X.id)],"balance",`name a customer, ${Ei} or object.attachment.account`),t.currency;let[O,D,_]=I;I.length!==3&&U(g,`${g.name} is not an account`,"write object.attachment.account","check_shape");let S=o.get(y({name:O,span:g.span})),C=T(S,{name:D,span:g.span}),E=C.fields.filter(X=>X.type==="account");c({name:_,span:g.span},E.map(X=>X.name),`${O}.${D} account`,`name an account field of ${C.id}`);let F=E.find(X=>X.name===_);return"currency"in F&&F.currency||t.currency},q=g=>Object.fromEntries(g.entries.map(I=>{let O={name:I.key,span:I.span};return[I.key,z(I.value,$(O),!0)]})),R=(g,I=t.currency)=>{if(g.kind==="list")return g.items.map(O=>R(O));if(g.kind==="block")return Object.fromEntries(g.entries.map(O=>[O.key,R(O.value)]));if(g.kind==="money"){let[O,D]=g.value.split(" ");D!==I&&!/^0+(?:\.0*)?$/.test(O)&&U(g,`this input is in ${I}, and ${g.value} is not`,`write the amount in ${I}`,"currency_mismatch")}if(g.kind==="call"&&["agreement","object","record"].includes(g.name)){let[O]=g.args;(g.args.length!==1||O?.kind!=="name")&&U(g,`${g.name} takes one name`,`write ${g.name}(name)`);let D={name:O.value,span:O.span};return g.name==="agreement"?c(D,d,"agreement","remember it on an earlier step"):g.name==="record"?c(D,u,"record","record it on an earlier step"):y(D),`$${g.name}:${O.value}`}return n(g)},H=(g,I=[])=>Object.fromEntries(g.entries.map(O=>[O.key,R(O.value,I.find(D=>D.name===O.key)?.currency)])),x=(g,I)=>{for(let _ of g.entries)c({name:_.key,span:_.span},I.map(S=>S.name),"field","name a field of the agreement this step reads");let O=_=>_.value.kind==="name"?/^(\w+)\.(iban|reference)$/.exec(_.value.value):null,D=H({...g,entries:g.entries.filter(_=>!O(_))},I);for(let _ of g.entries){let[,S,C]=O(_)??[];S&&(c({name:S,span:_.value.span},I.filter(E=>E.type==="account").map(E=>E.name),"account field","name an account field of the agreement this step reads"),D[_.key]=`$account:${S}.${C}`)}return D},w=g=>{let I=y(g.object),O=o.get(I),D=g.attachment?[T(O,g.attachment)]:P(O);c(g.state,(g.recordPath?t.instruments:P(O)).flatMap(S=>S.lifecycle.states),"state",`name a lifecycle state on object ${O}`);let _=g.recordPath?t.instruments.flatMap(S=>S.fields):D.flatMap(S=>S.fields);return{waitFor:{object:I,...g.recordPath?{recordPath:g.recordPath}:{},state:g.state.name,...g.attachment?{attachment:g.attachment.name}:{}},...g.reads?{reads:x(g.reads,_)}:{}}},v=(g,I,O)=>{let D=P(O).filter(S=>S.actions[g.action.name]?.actor==="observation");c(g.action,D.length?[g.action.name]:P(O).flatMap(S=>Object.entries(S.actions).flatMap(([C,E])=>E.actor==="observation"?[C]:[])),`${O} observation action`,"name an action with actor: observation"),g.role||U(g.action,"an officer maps a desk row",`write ${I}.${g.action.name} as <staff role> on ${g.instance.name}`,"check_shape");let _=g.actor??g.input??g.fields??g.remember;return _&&U(_,"a mapping runs the action with the credit's amount alone","drop the actor, input, fields and remember","check_shape"),g.state&&c(g.state,D.flatMap(S=>S.lifecycle.states),"state",`name a state ${g.action.name} can reach`),{kind:"action",object:I,action:g.action.name,role:b(g.role),credit:g.instance.name,...g.state?{state:g.state.name}:{},...g.status?{status:L(g.status)}:{},...g.code?{code:g.code}:{},...g.reads?{reads:x(g.reads,D.flatMap(S=>S.fields))}:{}}},L=g=>g.kind==="number"&&/^[45]\d\d$/.test(g.value)?Number(g.value):U(g,"expected a refusal","write status 409"),j=(g,I)=>{let O=P(g).filter(D=>Object.values(D.actions).some(_=>_.publicAction===I.name));return c(I,O.length?[I.name]:P(g).flatMap(D=>Object.values(D.actions).flatMap(_=>_.publicAction?[_.publicAction]:[])),`${g} action`,`name an action object ${g} exposes`),O};for(let g of e.statements){m&&U(g,"expect closes a check","move this step before expect","check_shape");let I=g.balances?{expected:q(g.balances)}:{};switch(g.kind){case"customer":{let{id:O}=g;(C9.has(O.name)||O.name===Ei)&&U(O,`${O.name} cannot name a customer`,"pick another name"),r.some(D=>D.id===O.name)&&U(O,`customer ${O.name} is declared twice`,"rename one","given_twice"),s.length&&U(g,"customers come before steps","move it up","check_shape"),r.push({id:O.name,name:g.title,...g.organization?{kind:"organization"}:{},...g.fund?{fund:z(g.fund,t.currency)}:{}});for(let D of g.binds){let _=Object.keys(t.parties);c(D,_,"party","bind a party the program declares"),D.name in a&&U(D,`party ${D.name} is bound twice`,"bind it once","given_twice"),a[D.name]=O.name}break}case"clock":{let O=g.at;O.kind!=="date"&&U(O,"a clock step needs a date","write clock 2031-04-01","check_shape"),s.push({kind:"clock",at:n(O),...g.until?w(g.until):{},...I});break}case"read":{let{waitFor:O,...D}=w(g);s.push({kind:"read",...O,...D,...I});break}case"sent":{let O=y(g.object),D=o.get(O),_=(g.attachment?[T(D,g.attachment)]:P(D)).flatMap(X=>Object.values(X.actions).flatMap(ae=>ae.send?[{...ae.send,bindings:ae.subject?.adapters??[]}]:[]));c(g.adapter,_.map(X=>X.adapter),"message adapter",`name the adapter an action of ${D} sends through`);let S=_.filter(X=>X.adapter===g.adapter.name);c(g.type,S.map(X=>X.kind),"message type",`name a type an action of ${D} sends through ${g.adapter.name}`);let C=S.filter(X=>X.kind===g.type.name),E=C.flatMap(X=>X.bindings).find(X=>X.binding===g.adapter.name)?.snapshot?.provider??g.adapter.name,F={};for(let X of g.fields?.entries??[]){c({name:X.key,span:X.span},C.flatMap(W=>Object.keys(W.fields)),"message field",`name a field the ${g.type.name} carries`);let ae=X.value;if(ae.kind==="money"){let W=ae.value.split(" ").at(-1),G=String(n(ae)).padStart(Dn(W)+1,"0"),se=Dn(W);F[X.key]=se?`${W} ${G.slice(0,-se)}.${G.slice(-se)}`:`${W} ${G}`}else ae.kind==="date"?F[X.key]=String(n(ae)).slice(0,10):F[X.key]=String(n(ae))}s.push({kind:"sent",object:O,...g.attachment?{attachment:g.attachment.name}:{},type:g.type.name,adapter:E,...g.fields?{fields:F}:{},...I});break}case"paid":{let O=y(g.object),D=T(o.get(O),g.attachment),_=Object.values(D.actions).flatMap(C=>C.moves.flatMap(E=>E.operation==="internal_transfer.reserve"&&E.boundary?.items?[{adapter:E.boundary.adapter,bindings:C.subject?.adapters??[]}]:[]));c(g.adapter,_.map(C=>C.adapter),"batch adapter",`name the adapter a reserve with items in ${D.id} pays through`);let S=_.flatMap(C=>C.bindings).find(C=>C.binding===g.adapter.name)?.snapshot?.provider??g.adapter.name;s.push({kind:"paid",object:O,attachment:g.attachment.name,adapter:S,items:Object.fromEntries(g.items.entries.map(C=>[C.key,C.value.kind==="name"?C.value.value:String(n(C.value))])),...I});break}case"object":{let{id:O}=g;o.has(O.name)&&U(O,`object ${O.name} is created twice`,"rename one","given_twice");let D=c(g.objectKind,t.objects.map(C=>C.id),"object kind","name an object the program declares"),_=g.owner.name===Ei?Ei:l(g.owner),S=t.objects.find(C=>C.id===D).fields.map(C=>C.name);for(let C of g.fields?.entries??[])c({name:C.key,span:C.span},S,`${D} field`,`name a field of object ${D}`);o.set(O.name,D),s.push({kind:"object",id:O.name,objectKind:D,owner:_,...g.fields?{fields:H(g.fields,t.objects.find(C=>C.id===D).fields)}:{},...I});break}case"action":{let O=y(g.object),D=o.get(O);if(g.instance&&p.has(g.instance.name)){s.push(v(g,O,D));break}let _=j(D,g.action),S=g.actor&&l(g.actor);S&&g.role&&U(g.role,"a step runs as a customer or as a staff role, not both",`drop ${S} or as ${g.role.name}`,"check_shape");let C=g.role&&b(g.role),E=g.state?.name===Xo;g.state&&!E&&c(g.state,_.flatMap(B=>B.lifecycle.states),"state",`name a state ${g.action.name} can reach`);let F;if(g.status){let B=g.status;F=B.kind==="name"&&B.value==="absent"?"absent":L(B)}let X=g.instance&&c(g.instance,d,"agreement","remember it on an earlier step"),ae=_.flatMap(B=>Object.values(B.actions).filter(te=>te.publicAction===g.action.name)),W=g.input&&H(g.input,ae.flatMap(B=>B.input)),G=_.flatMap(B=>B.fields),se=g.fields&&H(g.fields,G);E&&(g.remember||g.reads)&&U(g.remember??g.state,`a step held for approval has no agreement to ${g.remember?"remember":"read"}`,"remember or read on a step after the approve","check_shape"),g.remember&&f(g.remember,d),s.push({kind:"action",object:O,action:g.action.name,...S?{actor:S}:{},...C?{role:C}:{},...W?{input:W}:{},...se?{fields:se}:{},...E?{status:202,code:Xo}:g.state?{state:g.state.name}:{},...F!==void 0?{status:F}:{},...g.code?{code:g.code}:{},...g.remember?{remember:g.remember.name}:{},...X?{instance:X}:{},...g.reads?{reads:x(g.reads,G)}:{},...I});break}case"approve":{let O=y(g.object),D=o.get(O),_=j(D,g.action),S=s.at(-1);(S?.kind==="action"||S?.kind==="approve")&&S.object===O&&S.action===g.action.name&&(S.kind==="action"&&S.code===Xo||S.kind==="approve"&&!S.state&&!S.status)||U(g,`approve follows ${O}.${g.action.name} -> ${Xo}`,`end the step before with -> ${Xo}`,"check_shape"),g.state&&c(g.state,_.flatMap(C=>C.lifecycle.states),"state",`name a state ${g.action.name} can reach`),s.push({kind:"approve",object:O,action:g.action.name,role:b(g.role),...g.state?{state:g.state.name}:{},...g.status?{status:L(g.status)}:{},...g.code?{code:g.code}:{},...I});break}case"record":{C9.has(g.id.name)&&U(g.id,`${g.id.name} cannot name a record`,"pick another name"),k(g.id,u,`record ${g.id.name} is made`),g.title.length>160&&U(g,"a record title is at most 160 characters","shorten the title","check_shape");let O=g.signers.map(l);s.push({kind:"record",id:g.id.name,form:g.form,title:g.title,...O.length?{signers:O}:{},...g.direction?{direction:g.direction}:{},...I});break}case"policy":{s.length&&U(g,"a policy is written before the first step","move the policy above the first step","check_shape");let O=c(g.key,A,"approval policy",'name a key a requires approval "<key>" of the program names');i.some(S=>S.key===O)&&U(g.key,`policy ${O} twice`,"merge the rows","given_twice");let D=S=>(S.kind!=="money"&&U(S,"expected an amount","write an amount such as 1000000 SAR"),{minor:n(S),currency:S.value.split(" ")[1]}),_=g.rows.map(S=>{(S.by.kind!=="list"||!S.by.items.length)&&U(S.by,"by names staff roles","write by [checker]");let C=S.by.items.map(G=>G.kind==="name"?b({name:G.value,span:G.span}):U(G,"expected a staff role","write by [checker]")),E=S.count?n(S.count):1;(typeof E!="number"||E<1||E>16)&&U(S.count,"count is 1 to 16 people","write count 2");let F=S.within&&n(S.within);S.within&&(typeof F!="number"||F<=0||F>366*864e5)&&U(S.within,"within is a duration up to 366 days","write within 48h","check_shape");let X=S.from&&D(S.from),ae=S.below&&D(S.below);X&&ae&&X.currency!==ae.currency&&U(S.below,`a band is in one currency, and ${X.currency} is not ${ae.currency}`,`write both bounds in ${X.currency}`,"currency_mismatch");let W=(X??ae)?.currency;return{by:C,count:E,...typeof F=="number"?{within:F}:{},...W?{band:{currency:W,...X?{from:X.minor}:{},...ae?{below:ae.minor}:{}}}:{}}});_.length||U(g,"a policy needs a row","write by [checker]","check_shape"),i.push({key:O,rows:_});break}case"fund":{let O=$(g.account);r.some(D=>D.id===g.account.name)&&U(g.account,"a customer is funded where it is declared",`write customer ${g.account.name} "Name" funded <amount>`,"check_shape"),s.push({kind:"fund",account:g.account.name,amount:z(g.amount,O),currency:O,...I});break}case"credit":{g.account.name.split(".").length!==3&&U(g.account,"the bank credits an agreement's account","write credit <amount> to object.attachment.account","check_shape");let O=$(g.account);c(g.state,["matched","open"],"desk outcome","write -> matched when the observation action runs, -> open when the credit parks"),g.remember&&f(g.remember,p),s.push({kind:"credit",account:g.account.name,amount:z(g.amount,O),currency:O,reference:g.reference,...g.remember?{remember:g.remember.name}:{},outcome:g.state.name,...I});break}case"bill":{c(g.category,["sadad","moi"],"biller category","write bill sadad or bill moi");let O=g.due.kind==="money"?g.due.value.split(" ").at(-1):"SAR",[D,_]=g.band??[];s.push({kind:"bill",category:g.category.name,biller:g.biller,number:g.number,amountDue:z(g.due,O),...D&&_?{minimum:z(D,O),maximum:z(_,O)}:{},currency:O,...I});break}case"close":s.push({kind:"close",customer:l(g.customer),...I});break;case"expect":{s.length||U(g,"a check needs a step","add a step before expect","check_shape"),g.balances||U(g,"expect needs balances","write expect balances { }","check_shape"),m={expected:q(g.balances),...g.held?{expectedHeld:z(g.held,t.currency)}:{},...g.pending?{pending:Object.fromEntries(g.pending.entries.map(O=>{let D={name:O.key,span:O.span};O.value.kind!=="block"&&U(O,"expected balances","write name { }","check_shape");let _=O.value.entries.map(S=>[S.key,z(S.value,t.currency)]);return[c(D,[Ei,...r.map(S=>S.id)],"balance",`name a customer or ${Ei}`),Object.fromEntries(_)]}))}:{}};break}}}return m||U(e,"a check ends with expect","write expect balances { }","check_shape"),{name:e.name,customers:r,...Object.keys(a).length?{bindings:a}:{},...i.length?{policies:i}:{},steps:s,...m}}function gc(e){return new Set(e.flatMap(t=>{let n=new Map(t.steps.flatMap(r=>r.kind==="object"?[[r.id,r.objectKind]]:[]));return t.steps.flatMap(r=>r.kind==="action"?[`${n.get(r.object)}.${r.action}`]:[])}))}var C9,Ei,Xo,hc=ve(()=>{"use strict";In();Er();C9=new Set(["customer","clock","object","close","expect","record","fund","credit","bill","approve","policy"]),Ei="operator",Xo="approval_required"});function H9(e,t){let n={span:e.span,...e.source?{source:e.source}:{}},r=(x,w,v=n)=>U({...n,span:v.span},x,w,"report_invalid"),a=new Map(e.body.entries.map(x=>[x.key,x.value]));for(let x of e.body.entries)Tq.has(x.key)||r(`report ${e.name} has no clause ${x.key}`,"write summary, over, states, by and sum",x.value);let i=a.get("summary"),s=i?.kind==="text"?i.value:r(`report ${e.name} needs a summary`,'add summary: "what the officer reads"'),o=x=>x===void 0?[]:x.kind==="list"?x.items:[x],d=x=>x.kind==="name"?x.value:r("expected a name","write a field, state or instrument name",x),p=o(a.get("by"));p.length||r(`report ${e.name} groups by nothing`,"add by: [state], a field, or age(<date field>, [30d, 60d, 90d])");let u=o(a.get("sum")).map(d),m=o(a.get("states")).map(d),c=[],l=[],y=[];for(let x of p){if(x.kind==="call"&&(x.name==="age"||x.name==="until")){let[v,L]=x.args,j=`write ${x.name}(dueAt, [30d, 60d, 90d])`,g=v?d(v):r(`${x.name} names a date field`,j,x),I=o(L).map(_=>{let S=_.kind==="duration"?/^(\d+)d$/.exec(_.value):null;return S?Number(S[1]):r("a day bucket is a whole number of days","write 30d",_)});(!I.length||I.some((_,S)=>S>0&&I[S-1]>=_))&&r(`${x.name} buckets ascend`,j,x);let O=x.name==="until",D=`${g}${O?"Ahead":"Age"}`;c.push({name:g,field:g,at:v}),y.push({column:D,days:`${D}Days`,field:g,ahead:O,bounds:I}),l.push({column:D,at:x});continue}let w=d(x);w==="state"?l.push({column:"state",at:x}):(c.push({name:Hi(w),field:w,at:x}),l.push({column:Hi(w),at:x}))}for(let[x,w]of u.entries())c.push({name:Hi(w),field:w,at:o(a.get("sum"))[x]});let h=new Set(t.instruments.map(x=>x.id)),b=(x,w)=>gy(x,w,t)!==void 0,A=x=>u.some(w=>{let v=gy(x,w,t);return v?.kind==="money"&&v.currency!==t.currency}),Z=x=>c.every(w=>b(x,w.field))&&!A(x)&&m.every(w=>x.lifecycle.states.includes(w)),k=a.get("over"),f;if(k?.kind==="name"&&k.value==="every"){if(f=t.instruments.filter(Z),!f.length&&e.standard)return;f.length||r(`no instrument declares every field and state report ${e.name} reads in ${t.currency}`,"name the instruments in over:, or read fields they declare",k)}else f=(k?o(k):[void 0]).flatMap(x=>{let w=x?d(x):"self",v=e.hosts.map(j=>`${j.id}_${w}`).filter(j=>h.has(j));return(w==="self"?e.hosts.map(j=>j.id):v.length?v:h.has(w)?[w]:r(`report ${e.name} reads ${w}, which is not an instrument or a record of ${e.hosts[0].id}`,"name self, a record of this instrument, a program instrument, or every",x)).map(j=>t.instruments.find(g=>g.id===j))});for(let x of f){for(let w of c)b(x,w.field)||r(`${x.id} declares no field ${w.field} a report can read`,"read a money, integer, date, text, enum, ref or account field, or an account's balance, iban or reference",w.at);for(let w of m)x.lifecycle.states.includes(w)||r(`${x.id} has no state ${w}`,`use one of ${x.lifecycle.states.join(", ")}`,a.get("states"))}let z=x=>gy(f[0],x,t);for(let x of u)["money","integer"].includes(z(x).kind)||r(`report ${e.name} sums ${x}, which is not money or a count`,"sum a money field, an integer field or an account's balance");for(let x of y)z(x.field).kind!=="date"&&r(`${x.ahead?"until":"age"} reads ${x.field}, which is not a date`,"name a date field");let P=[{name:"id",field:"id",type:{kind:"text"},required:!0},{name:"state",field:"status",type:{kind:"text"},required:!0}];for(let x of c)P.some(w=>w.name===x.name)||P.push({name:x.name,field:x.field,type:z(x.field),required:!1});let T=[],$;for(let x of m)T.push({id:`${x}State`,op:"literal",type:{kind:"text"},value:x},{id:`${x}Selected`,op:"equal",left:"state",right:`${x}State`}),$?(T.push({id:`${x}OrBefore`,op:"or",left:$,right:`${x}Selected`}),$=`${x}OrBefore`):$=`${x}Selected`;y.length&&T.push({id:"observed",op:"parameter",name:"observationAt"});for(let x of y)T.push({id:x.days,op:"daysBetween",left:x.ahead?"observed":x.field,right:x.ahead?x.field:"observed"},{id:x.column,op:"bucket",value:x.days,bounds:x.bounds});let q=new Map(P.map(x=>[x.name,x.type]));for(let x of y)q.set(x.column,{kind:"text"});let R=[{name:"count",op:"count"},...u.map(x=>({name:Hi(x),op:"sum",value:Hi(x)}))],H=l.map(x=>x.column);return{identity:{id:e.name,version:1,description:s},scope:{kind:"product",currency:t.currency},datasets:[{id:"rows",source:"instrument",instruments:f.map(x=>x.id),rowKey:"id",columns:P,expressions:T,...$?{selection:$}:{}}],selection:{dataset:"rows"},calculation:{joins:[],expressions:[],groupBy:H,aggregates:R,resultExpressions:[]},validation:{empty:"noEligibleFacilities",required:[],rowReconcile:[],reconcile:[],unavailableFacts:[]},output:{formats:["json","csv"],columns:[...H.map(x=>({name:x,label:x,type:q.get(x)})),{name:"count",label:"count",type:{kind:"integer"}},...u.map(x=>({name:Hi(x),label:Hi(x),type:z(x)}))],sort:H},authority:{request:["owner","finance"],read:["owner","admin","operations","finance","viewer"],retention:{years:10}}}}function gy(e,t,n){let[r,a,...i]=t.split(".");if(i.length)return;if(!a&&r==="createdAt")return{kind:"date"};let s=e.fields.find(d=>d.name===r);if(!s)return;let o="currency"in s&&s.currency||n.currency;if(a){let d=s.type==="account"&&a!=="reserved"?Wa(a):void 0;return d==="money"?{kind:"money",currency:o}:d&&{kind:d}}if(s.type==="money")return{kind:"money",currency:o};if(["ref","account","enum","text"].includes(s.type))return{kind:"text"};if(["integer","boolean","date"].includes(s.type))return{kind:s.type}}function Hi(e){return e.replace(/\.(\w)/,(t,n)=>n.toUpperCase())}var Tq,N9=ve(()=>{"use strict";In();Er();Tq=new Set(["summary","over","states","by","sum"])});function fc(e){let t=e.kind==="call"||e.kind==="type"?e.name:e.kind==="name"?e.value:"";if(t==="money")return{minimum:"0",maximum:"999999999999999999"};if(t==="percent")return{minimum:0,maximum:an(er)};if(t==="duration")return{minimum:0,maximum:Number.MAX_SAFE_INTEGER};if(t==="integer"){if(e.kind==="call"){let n=e.args.map(r=>r.kind==="number"?Number(r.value):NaN);return(n.length!==2||n.some(r=>!Number.isSafeInteger(r))||n[0]>n[1])&&U(e,"integer tunable needs ordered safe integer bounds","write integer(1, 12)","field_type_invalid"),{minimum:n[0],maximum:n[1]}}return{minimum:0,maximum:Number.MAX_SAFE_INTEGER}}}var hy=ve(()=>{"use strict";In();Er()});function*ni(e){if(e)switch(e.kind){case"name":yield e;return;case"list":for(let t of e.items)yield*ni(t);return;case"block":for(let t of e.entries)yield*ni(t.value);return;case"call":for(let t of e.args)yield*ni(t);return;case"default":yield*ni(e.type),yield*ni(e.value);return;case"capped":yield*ni(e.rate),yield*ni(e.cap);return}}function U9(e,t,n,r){let a=[],i=new Map;for(let s of r.entries)if(s.key==="calculate")for(let o of bc(s.value)){let d=ri(o,"target");d&&"value"in d&&typeof d.value=="string"&&i.set(d.value,{span:o.span,...o.source?{source:o.source}:{}})}for(let s of r.entries)if(s.key!=="actor")for(let o of ni(s.value)){o.value==="caller"&&["requires","set","calculate","invoke"].includes(s.key)&&a.push(_c(o,"caller_is_not_a_value",`\`caller\` in ${t} is the text "caller", not the person running the action`,"write actor to read the person behind the call"));let d=/^self\.([a-zA-Z0-9_]+)(?:\.|$)/.exec(o.value)?.[1],p=d===void 0?void 0:i.get(d);p&&o.span.start<p.span.start&&a.push(_c(o,"let_target_read",`\`self.${d}\` in ${t} reads the result of \`let ${d}\` at ${B9(e,p)}, not the value at action start: every let runs before the rest of the action`,`move \`let ${d}\` above this read to use its result, or read self.${d} in an earlier action to use the value before it changes`))}for(let s of n.entries)if(s.key==="requires")for(let o of bc(s.value)){let d=ri(o,"kind"),p=ri(o,"left");d?.kind==="text"&&d.value==="compare"&&M9(p)&&M9(ri(o,"right"))&&a.push(_c(ri(p,"literal"),"constant_requirement",`this requirement of ${t} compares two constants, so it never depends on the record`,"compare a field, an input or a tunable, or delete the requirement"))}return a}function F9(e,t){let n=new Map;for(let[a,i]of t)for(let s of i.entries)if(s.key==="calculate")for(let o of bc(s.value)){let d=ri(o,"target");d&&"value"in d&&typeof d.value=="string"&&!n.has(d.value)&&n.set(d.value,{action:a,site:o})}let r=[];for(let[a,i]of t)for(let s of i.entries)if(s.key==="set"&&s.value.kind==="block")for(let o of s.value.entries){let d=n.get(o.key);if(!d)continue;let p=o;r.push(_c({...p,span:{start:o.span.start,end:o.span.start+o.key.length}},"immutable_field",`\`${o.key} = ...\` in ${a} assigns a field that \`let ${o.key}\` in ${d.action} at ${B9(e,d.site)} calculates, and a calculated field takes no assignment`,`write \`let ${o.key} = ...\` in ${a} too, or give the assigned value its own field`))}return r}function K9(e){let t=new Set,n=r=>{for(let a of r.entries)if(a.key.startsWith("when ")&&a.value.kind==="block")n(a.value);else if(a.key==="set"&&a.value.kind==="block")for(let i of a.value.entries)t.add(i.key);else if(a.key==="calculate")for(let i of bc(a.value)){let s=ri(i,"target");s&&"value"in s&&typeof s.value=="string"&&t.add(s.value)}};for(let r of e.entries)r.key.startsWith("action ")&&r.value.kind==="block"&&n(r.value);return t}var B9,_c,bc,ri,Dq,M9,X9=ve(()=>{"use strict";Ha();B9=(e,t)=>{let{line:n,column:r}=_n(e.get(t.source??"program")??"",t.span.start);return`${n}:${r}`},_c=(e,t,n,r)=>({code:t,message:n,fix:r,span:e.span,...e.source?{source:e.source}:{}});bc=e=>e.kind==="list"?e.items:[e],ri=(e,t)=>e.kind==="block"?e.entries.find(n=>n.key===t)?.value:void 0,Dq=new Set(["number","money","percent","duration","date"]),M9=e=>{let t=e&&ri(e,"literal");return!!t&&(Dq.has(t.kind)||t.kind==="text"||t.kind==="name"&&["true","false"].includes(t.value))}});function V9(e,t,n,r,a,i=[]){let s=new Set;for(let o of r){let d=o.key.slice(10),[p,u,m]=d.split("."),c=Object.hasOwn(t.actions,p)?t.actions[p]:void 0;c||U(o,`unknown economics action ${p}`,`choose ${t.actionOrder.join(", ")}, before its public alias${i.length?`, or record.action for a record (${i.join(", ")})`:""}`,"unknown_action");let l=u?c.moves.find(Z=>Z.key===u):c.moves.length===1?c.moves[0]:void 0;(!l||m)&&U(o,`economics ${d} must select one money move`,c.moves.length?`choose ${c.moves.map(Z=>`${p}.${Z.key}`).join(", ")}`:"choose an action that transfers or reserves money","economics_move_unselected"),l.operation==="internal_transfer.void"&&U(o,`economics ${d} cannot classify a void`,"declare the purpose on the reservation or its posting"),s.has(l)&&U(o,`repeated economics for ${d}`,"declare each money move's purpose once"),s.add(l);let y=km.safeParse({...l,economics:a(o.value)});(!y.success||!y.data.economics)&&U(o,`invalid economics for ${d}`,"declare purpose and sourceParty using the move economics fields");let h=y.data.economics;l.economics&&(l.economics.purpose!==h.purpose||l.economics.sourceParty!==h.sourceParty||l.economics.reversalOf!==h.reversalOf||h.taxOn!==void 0&&l.economics.taxOn!==h.taxOn)&&U(o,`economics ${d} conflicts with the instrument's declared purpose`,"keep the instrument's economics or choose an unclassified move");let b=h.sourceParty,A=un.includes(b);if(!A&&e.parties[b]?.kind!=="business"&&U(o,`unknown economic source party ${b}`,"bind sourceParty to owner, actor, operator or a declared business","unknown_party"),!Object.values(n).some(Z=>"role"in Z?Z.role===b:Z.party===b)){let Z="economicSource";for(let k=2;Object.hasOwn(n,Z);k++)Z=`economicSource${k}`;n[Z]=A?{role:b}:{party:b}}l.economics=l.economics?.taxOn&&!h.taxOn?{...h,taxOn:l.economics.taxOn}:h}}function xc(e,t,n){let r=new Map(e.objects.flatMap(a=>a.attachments.map(i=>[i.instrument,i.parties])));return e.instruments.flatMap(a=>{let i=t.get(a.id),s=i&&n.get(i.root);if(!i||!s)return[];let o=s.entry.span.start;return[{instrument:a,selector:i,attach:s,parties:r.get(a.id)??r.get(i.root)??{},span:{start:o,end:o+`attach ${s.name}`.length}}]})}function za(e,t){return t==="operator"||t==="programOperator"||t!==void 0&&e.parties[t]?.role==="program_operator"}function W9(e,t,n){let r=[];for(let{instrument:a,selector:i,attach:s,parties:o,span:d}of xc(e,t,n)){let p=s.template.parameters.filter(m=>m.value.kind==="name"&&m.value.value==="party").map(m=>m.key),u=m=>p.find(c=>o[c]&&ks(o[c])===m)??m;for(let m of a.actionOrder){let c=a.actions[m];for(let l of c.moves){if(l.economics||l.operation!=="internal_transfer.create"&&l.operation!=="internal_transfer.reserve")continue;let y=`${i.prefix}${m}${c.moves.length>1||!/^move\d+$/.test(l.key)?`.${l.key}`:""}`,h=[l.from,l.to].map(z=>/^self\.\w+$/.test(z)?mt(e,a,z,c.input,c):void 0),b=z=>z?.type==="account"&&typeof z.owner=="string"?z.owner:void 0,A=zs(l.from)??(b(h[0])==="self"?void 0:b(h[0])),Z=p.find(z=>o[z]&&!za(e,ks(o[z]))),k=h.some(z=>z?.type==="account"&&z.book!=="cash")?"internal":za(e,zs(l.to))?za(e,A)||!A&&!Z?"internal":"earning":za(e,A)?b(h[1])==="self"?"internal":"participant_payout":"pass_through",f=A?u(A):k==="earning"?Z:"programOperator";r.push({code:"economic_purpose_missing",message:`${s.name}: ${y} moves money with no declared purpose, so the books will not count it as revenue or a payout`,fix:`add economics ${y} { purpose: ${k}, sourceParty: ${f} } inside attach ${s.name}`,span:d})}}}return r}function Y9(e,t,n){let r=[],a=[],i=o=>za(e,o)?"operator":o,s=new Set;for(let{instrument:o,selector:d,attach:p,parties:u,span:m}of xc(e,t,n)){let c=A=>Object.entries(u).find(([,Z])=>[A,i(A)].includes(i(ks(Z))))?.[0],l=A=>{let Z=c(A);return Z&&Z!==A?`${Z}: ${A}`:A},y=e.instruments.find(A=>A.id===d.root)?.actions.create?.actor,h=typeof y=="object"&&"party"in y?i(y.party):void 0,b=h&&h!=="actor"?h:void 0;for(let A of o.actionOrder)for(let Z of o.actions[A].moves){let k="from"in Z?zs(Z.from):void 0,f="to"in Z?zs(Z.to):void 0;if(!k||!f)continue;let z=i(k),P=i(f),T=R=>R==="actor"&&b?b:R,$=`${p.name}:${z}:${P}`;if(s.has($))continue;let q=`${d.prefix}${A}`;if(T(z)===T(P)){s.add($);let R=z!==P?` ${c(b)??b} runs create, so actor is ${b}.`:"";r.push({code:"same_party_move",message:`${p.name}: ${q} moves money from ${l(k)} to ${l(f)}, and both are ${T(z)}.${R} A party cannot pay itself.`,fix:`Bind the paying and receiving parties to different roles, such as ${c(k)??"payer"}: owner and ${c(f)??"payee"}: operator for a customer paying the company.`,span:m})}else!b&&[k,f].includes("actor")&&[k,f].includes("operator")&&(s.add($),a.push({code:"same_party_move",message:`${p.name}: ${q} moves money from ${l(k)} to ${l(f)}. When the company runs create itself, actor is the company and it pays itself.`,fix:`Run create on behalf of a customer, or bind ${c("actor")??"the paying party"}: owner if the record's owner pays.`,span:m}))}}return{errors:r,warnings:a}}function J9(e,t,n){let r=[],a=o=>za(e,o),i=o=>a(o)?"company":o,s=o=>o==="owner"||o==="actor";for(let{instrument:o,selector:d,attach:p,parties:u,span:m}of xc(e,t,n)){let c=l=>!a(l)&&Object.entries(u).find(([,y])=>ks(y)===l)?.[0]||l;for(let l of o.actionOrder){let y=o.actions[l];for(let h of y.moves){if(!h.economics||!("amount"in h)||!/^(?:party|self)\.\w+$/.test(h.from))continue;let b=mt(e,o,h.from,y.input,y);if(b?.type!=="account")continue;let A=b.owner==="self"||typeof b.owner!="string"?"company":i(b.owner),Z=i(h.economics.sourceParty);if(A===Z||s(A)&&s(Z))continue;let k=/^party\.\w+$/.test(h.to)?void 0:mt(e,o,h.to,y.input,y),f=/^party\.\w+$/.test(h.to)?a(h.to.slice(6)):k?.type!=="account"||typeof k.owner!="string"||k.owner==="self"||a(k.owner);if(h.economics.purpose==="earning"&&!h.economics.reversalOf&&b.owner==="self"&&Z!=="company"&&f)continue;let P=`${d.prefix}${l}${y.moves.length>1||!/^move\d+$/.test(h.key)?`.${h.key}`:""}`,T=A==="company"?"your company's":`the ${c(A)}'s`,$=A==="company"?"programOperator":A;r.push({code:"economic_source_unbound",message:`${p.name}: ${P} moves money out of ${h.from.startsWith("party.")?c(h.from.slice(6)):h.from}, which is ${T} account, but names ${c(h.economics.sourceParty)} as the source. Every run of this action would refuse with economic_source_unbound.`,fix:`Set sourceParty: ${$==="programOperator"?$:c($)} on economics ${P}, or move the money from an account ${c(h.economics.sourceParty)} owns.`,span:m})}}}return r}function G9(e,t,n){let r=[];for(let{instrument:a,selector:i,attach:s,parties:o,span:d}of xc(e,t,n)){let p=l=>Object.entries(o).find(([,y])=>za(e,ks(y))?za(e,l):ks(y)===l)?.[0]??l,u=[],m="",c="";for(let l of a.actionOrder){let y=a.actions[l];for(let h of y.moves){let b="to"in h?zs(h.to):void 0;if(!b||!za(e,b))continue;let A=y.moves.find(P=>P.key===`${h.key}Fee`);if(!A||!("to"in A)||zs(A.to)!=="programOperator")continue;let Z=`${l}_${h.key}_feeGross`,f=[...a.calculate??[],...y.calculate??[]].find(P=>P.target===Z)?.bps?.literal;if(f!==void 0&&Number(f)===0)continue;let z=a.fields.find(P=>P.name===Z)?.label??"Fee";m=`${f===void 0?"":`${qo(Number(f),an(e.udl))} `}${z.toLowerCase()}`,c=p(b),u.push(`${i.prefix}${l}`)}}u.length&&r.push({code:"fee_on_company_sale",message:`${s.name}: ${u.join(" and ")} ${u.length===1?"charges":"charge"} the ${m} on ${c}'s share, but ${c} is bound to the company itself, so no ${c} is paid and the company keeps the whole price.`,fix:`Bind \`${c}: customer\` when a customer is paid, or a declared business for a fixed one. Drop the fee when the company itself is paid.`,span:d})}return r}var zs,ks,fy=ve(()=>{"use strict";In();Er();zs=e=>/^party\.(\w+)$/.exec(e??"")?.[1],ks=e=>"role"in e?e.role:e.party});function Vo(e){return qs(e,!1)}function qs(e,t=!0){let n=[],r=[],a=0;for(;a<e.length;){let i=a,s=e.slice(a),o=/^\s+|^\/\/[^\n]*/.exec(s);if(o){a+=o[0].length,t&&o[0].startsWith("//")&&n.push({kind:"comment",text:o[0],span:{start:i,end:a}});continue}let d=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2}))?/.exec(s),p=/^-?\d+(?:\.\d+)?(?:%|ms|[smhdw])?/.exec(s),u=/^[A-Za-z_][A-Za-z0-9_]*/.exec(s),m,c;if(d)m="date",c=d[0];else if(p)m="number",c=p[0];else if(u)m="name",c=u[0];else if(s[0]==='"'){let l=/^"(?:[^"\\\u0000-\u001f]|\\["\\/bfnrt]|\\u[0-9a-fA-F]{4})*"/.exec(s);if(!l){if(r.push({code:"invalid_string",message:"unclosed or invalid string",fix:"close the string and use JSON escapes",span:{start:i,end:i+1}}),t){let y=/^"(?:[^"\\\n]|\\[^\n]?)*(?:"|(?=\n)|$)/.exec(s)?.[0]??'"';a+=y.length,n.push({kind:"string",text:y,span:{start:i,end:a}})}else a++;continue}m="string",c=l[0]}else if(/^(==|!=|<=|>=|->)/.test(s))m="punct",c=s.slice(0,2);else if(/^[{}()[\]:,;=<>?.|+\-*/]/.test(s))m="punct",c=s[0];else{r.push({code:"unexpected_character",message:`unexpected character ${s[0]}`,fix:"remove this character",span:{start:i,end:i+1}}),a++;continue}a+=c.length,n.push({kind:m,text:c,span:{start:i,end:a}})}return n.push({kind:"eof",text:"",span:{start:a,end:a}}),{tokens:n,diagnostics:r}}var Q9,Wo=ve(()=>{"use strict";Q9=["program","header","party","role","currency","instrument","fields","lifecycle","action","expose","as","cap","of","when","checks","requires","invariants","moves","from","to","in","is","has","unique","on","count","sum","hours","between","and","or","not","otherwise","timezone","evidence","approval","family","check","result","maxAge","instruction","reserve","post","void","capture","boundary","key","fee","shares","object","attach","subject","rename","columns","let","then","with","udl","amends","names","hide","use"]});function ar(e){let t={name:"",title:"",currency:"SAR",header:!1,uses:[],decls:[],checks:[],span:{start:0,end:e.length}},n=s=>new TextEncoder().encode(s).length,r=s=>({program:t,warnings:[],diagnostics:[{code:"HSX1004",message:s,fix:"split the program into headers",span:t.span}]});if(n(e)>T9)return r("source exceeds 512 KiB");if(/^\s*[[{]/.test(e))return{program:t,warnings:[],diagnostics:[{code:"HSX1014",message:"JSON is not HSX source",fix:'write program name "Title" followed by HSX declarations',span:{start:e.search(/\S/),end:e.search(/\S/)+1}}]};let a=Vo(e);if(a.diagnostics.length)return{program:t,diagnostics:a.diagnostics,warnings:[]};let i=new vc(a.tokens,e);try{let s=i.program(t);if(i.failures.length)return{program:t,diagnostics:i.failures,warnings:[]};let o=s.checks.reduce((d,p)=>d+n(e.slice(p.span.start,p.span.end)),0);return n(e)-o>uy?r("program exceeds 256 KiB without its checks"):{program:s,diagnostics:[],warnings:i.warnings}}catch(s){if(s instanceof Ni)return{program:t,diagnostics:[s.diagnostic],warnings:[]};throw s}}function rv(e){let t=Vo(e);if(!t.diagnostics.length)try{return new vc(t.tokens).value()}catch(n){if(n instanceof Ni)return;throw n}}function _y(e){if(e.kind==="list")return Math.max(0,...e.items.map(_y));if(e.kind!=="block")return 0;let t=Math.max(0,...e.entries.map(n=>_y(n.value)));return e.entries.some(n=>n.key==="op"||n.key==="kind")?t+1:t}var Ni,ev,Rq,Cq,Eq,Hq,tv,nv,Nq,Mq,vc,ka=ve(()=>{"use strict";Wo();Ko();Ni=class extends Error{constructor(n){super(n.message);this.diagnostic=n}diagnostic};ev=new Set(["rate","ratio","divide","compound","days between","months between"]),Rq=new Set(["actual/365","actual/360","30/360"]),Cq=new Set(["calculate","invoke","set"]),Eq=new Set(["==","!=","<","<=",">",">="]),Hq=["+","-","*","/"],tv=new Set(["sum","minimum","maximum","subtract","multiply","divide","rate","ratio","compound"]),nv=10;Nq=new Set(["divide","rate","ratio","compound","between"]),Mq="36525d",vc=class{constructor(t,n=""){this.tokens=t;this.source=n}tokens;source;index=0;depth=0;guarding=!1;reading=0;failures=[];warnings=[];currencyDeclared=!1;peek(){return this.tokens[this.index]}take(){let t=this.peek();return t.kind!=="eof"&&this.index++,t}at(t){return this.peek().text===t}eat(t){return this.at(t)?(this.take(),!0):!1}fail(t,n,r=this.peek().span,a="HSX1000"){throw new Ni({code:a,message:t,fix:n,span:r})}recover(t){this.index=Math.min(Math.max(this.index,t+1),this.tokens.length-1);let n=r=>r.kind==="name"&&(r.span.start===0||this.source[r.span.start-1]===`
|
|
66
|
+
`)}var v9=ve(()=>{"use strict";Gm();gs()});function ay(e){return kr(e)}function iy(e,t){let n=[];sy=t.currency,Ti={before:an(e.udl),after:an(t.udl)},cq(n,e,t),uq(n,e,t),lq(n,e,t),bq(n,e,t);let r=Iq(n,e,t),a=i=>uc.indexOf(i.class);return r.map((i,s)=>({change:i,index:s})).sort((i,s)=>a(i.change)-a(s.change)||i.index-s.index).map(({change:i})=>i)}function jt(e,t){let n=t.before?t.after?"changed":"removed":"added";e.push({kind:n,class:t.class,subject:t.subject,key:t.key,at:{...t.before?{before:t.before.path}:{},...t.after?{after:t.after.path}:{}},...t.instrument===void 0?{}:{instrument:t.instrument},...t.before?{before:ta(t.before.value)}:{},...t.after?{after:ta(t.after.value)}:{},sentence:t.sentence})}function ta(e){return e===void 0?null:JSON.parse(JSON.stringify(e))}function na(...e){return[...new Set(e.flatMap(t=>t?Object.keys(t):[]))].sort()}function $9(e,t){return new Map((e??[]).map((n,r)=>[t(n),{item:n,index:r}]))}function Ci(e,t,n){let r=$9(e,n),a=$9(t,n);return na(Object.fromEntries(r),Object.fromEntries(a)).map(i=>({name:i,before:r.get(i),after:a.get(i)}))}function Di(e,t){let n=t.before.value??[],r=t.after.value??[];Qt(n,r)||!t.independent&&!Qt([...n].sort(),[...r].sort())||jt(e,{class:t.class,subject:"order",key:`${t.key}/order`,instrument:t.instrument,before:t.before,after:t.after,sentence:t.sentence(r)})}function pq(e,t){let n=new Map;(t??[]).forEach((s,o)=>{let d=Vt(ta(s));n.set(d,[...n.get(d)??[],o])});let r=[];(e??[]).forEach((s,o)=>{let d=Vt(ta(s)),p=n.get(d);p?.length?p.shift():r.push([s,o])});let a=new Set([...n.values()].flat()),i=(t??[]).flatMap((s,o)=>a.has(o)?[[s,o]]:[]);return{removed:r,added:i}}function Ri(e,t){let n=t.before.value,r=t.after.value;for(let a of na(n,r))t.handled.includes(a)||Qt(n[a],r[a])||jt(e,{class:"control",subject:"document",key:`${t.key}/${a}`,instrument:t.instrument,before:n[a]===void 0?void 0:{path:`${t.before.path}.${a}`,value:n[a]},after:r[a]===void 0?void 0:{path:`${t.after.path}.${a}`,value:r[a]},sentence:`${pe(a)} ${t.owner} changed.`})}function I9(e,t=sy){let n=Dn(t);if(n===0)return`${e} ${t}`;let r=e.padStart(n+1,"0");return`${r.slice(0,-n)}.${r.slice(-n)} ${t}`}function oy(e){let t=[[864e5,"day"],[36e5,"hour"],[6e4,"minute"],[1e3,"second"]];for(let[n,r]of t)if(e%n===0){let a=e/n;return`${a} ${r}${a===1?"":"s"}`}return`${e} milliseconds`}function ra(e,t=!1){if(!e)return"nothing";if(ft(e))return pe(bn(e));if("field"in e)return pe(e.field);let n=e.literal;return t&&typeof n=="string"&&/^[0-9]+$/.test(n)?I9(n):pe(String(n))}function xn(e){return e?.length?e.map(pe).join(", "):"none"}function wn(e){return pe(Vt(ta(e)))}function wa(e){if(e&&typeof e=="object"){let t=e;if(typeof t.role=="string")return`the ${pe(t.role)} role`;if(typeof t.party=="string")return`party ${pe(t.party)}`;if(typeof t.adapter=="string")return`adapter ${pe(t.adapter)}`}return typeof e=="string"?pe(e):wn(e)}function ty(e){if(e===void 0)return"nobody";if(e==="caller")return"the caller";if(e==="clock")return"the clock";if(e==="observation")return"an observed credit";if(typeof e!="object")return pe(String(e));if("party"in e)return`party ${pe(e.party)}`;let t=typeof e.parent=="string"?[e.parent]:e.parent;return`a parent ${xn(t)}`}function z9(e){switch(e.kind){case"compare":return`${ra(e.left)} ${e.operator} ${ra(e.right)}`;case"state":return`${pe(e.reference)} is in ${xn(e.states)}`;case"hours":return`${pe(e.at)} falls between ${e.start}:00 and ${e.end}:00 ${e.timezone}`;case"unique":return`${xn(e.fields)} is unique in ${pe(e.namespace)}`;case"aggregate":return`${e.measure==="count"?"the count":`the sum of ${pe(e.measure.sum)}`} of ${xn(typeof e.selection.instrument=="string"?[e.selection.instrument]:e.selection.instrument)} in ${xn(e.selection.states)} ${e.operator} ${ra(e.value)}`;case"evidence":return`evidence ${pe(`${e.family}.${e.check}`)} on ${pe(e.subject)} reads ${pe(e.result)} within ${oy(e.maxAge)}`;case"approval":return`approval ${wn(e)}`;case"all":case"any":case"not":return pe(qi(e))}}function pc(e){if(!e)return"no time";let t=e,n=t.offset===void 0||t.offset===0?"":` ${t.offset<0?"minus":"plus"} ${oy(Math.abs(t.offset))}`,r=t.localDay?`, at ${t.localDay.hour}:00 ${t.localDay.timezone} ${t.localDay.days}${t.localDay.banking?" banking":""} days ${t.localDay.direction}`:"";return`${pe(t.at)}${n}${r}`}function cc(e){let{target:t,op:n,...r}=e,a=Object.keys(r).sort().map(i=>{let s=r[i];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s;if("field"in o||"literal"in o)return`${i} ${ra(o)}`}return`${i} ${typeof s=="string"?pe(s):wn(s)}`});return`${String(n)}(${a.join(", ")})`}function cq(e,t,n){let r=[["udl","control",s=>`format ${String(s)}`,"The document is now in UDL"],["product","surface",s=>pe(String(s)),"The product id is now"],["title","surface",s=>pe(String(s)),"The product title is now"],["version","surface",s=>String(s),"The product version is now"],["currency","money",s=>String(s),"The product currency is now"]],a=t,i=n;for(let[s,o,d,p]of r)Qt(a[s],i[s])||jt(e,{class:o,subject:"document",key:`document/${s}`,before:{path:`$.${s}`,value:a[s]},after:{path:`$.${s}`,value:i[s]},sentence:`${p} ${d(i[s])} instead of ${d(a[s])}.`});Ri(e,{key:"document",owner:"on the document",before:{path:"$",value:t},after:{path:"$",value:n},handled:[...r.map(([s])=>s),"parties","objects","instruments"]})}function uq(e,t,n){for(let r of na(t.parties,n.parties)){let a=t.parties[r],i=n.parties[r];if(Qt(a,i))continue;let s=o=>`a ${o.kind}${o.role?` in role ${pe(o.role)}`:""}`;jt(e,{class:"money",subject:"party",key:`parties/${r}`,before:a&&{path:`$.parties.${r}`,value:a},after:i&&{path:`$.parties.${r}`,value:i},sentence:a?i?`Party ${pe(r)} is now ${s(i)} instead of ${s(a)}.`:`Party ${pe(r)} is removed; it was ${s(a)}.`:`Party ${pe(r)} is added as ${s(i)}.`})}}function lq(e,t,n){for(let r of Ci(t.objects,n.objects,a=>a.id)){let a=`objects/${r.name}`,i=r.before&&{path:`$.objects[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`$.objects[${r.after.index}]`,value:r.after.item},o=`object ${pe(r.name)}`;if(!i||!s){let d=(i??s).value;jt(e,{class:"control",subject:"object",key:a,before:i,after:s,sentence:`Object ${pe(r.name)} (${d.title}) is ${i?"removed":"added"}, with ${Ia(d.attachments.length,"attachment")}.`});continue}mq(e,a,o,i,s)}}function Ia(e,t){return`${e} ${t}${e===1?"":"s"}`}function mq(e,t,n,r,a){let i=r.value,s=a.value,o=(d,p,u)=>({path:`${d.path}.${p}`,value:u});i.title!==s.title&&jt(e,{class:"surface",subject:"object",key:`${t}/title`,before:o(r,"title",i.title),after:o(a,"title",s.title),sentence:`${Is(n)} is now titled ${pe(s.title)} instead of ${pe(i.title)}.`});for(let[d,p,u]of[["entryActions","control","entry actions"],["authoredFields","surface","authored fields"],["columns","surface","columns"]]){let m=i[d],c=s[d];if(!Qt(m,c)){if(Qt([...m??[]].sort(),[...c??[]].sort())){Di(e,{class:"surface",key:`${t}/${d}`,before:o(r,d,m),after:o(a,d,c),sentence:l=>`The ${u} of ${n} are now in the order ${xn(l)}.`});continue}jt(e,{class:p,subject:"object",key:`${t}/${d}`,before:m===void 0?void 0:o(r,d,m),after:c===void 0?void 0:o(a,d,c),sentence:`The ${u} of ${n} are now ${xn(c)} instead of ${xn(m)}.`})}}py(e,{key:`${t}/fields`,owner:`on ${n}`,before:o(r,"fields",i.fields),after:o(a,"fields",s.fields)});for(let d of Ci(i.attachments,s.attachments,p=>p.name)){let p=`${t}/attachments/${d.name}`,u=d.before&&{path:`${r.path}.attachments[${d.before.index}]`,value:d.before.item},m=d.after&&{path:`${a.path}.attachments[${d.after.index}]`,value:d.after.item},c=`attachment ${pe(d.name)} on ${n}`;if(!u||!m){jt(e,{class:"control",subject:"attachment",key:p,instrument:(u??m).value.instrument,before:u,after:m,sentence:u?`${Is(c)} is removed; it attached ${pe(u.value.instrument)}.`:`${Is(c)} is added; it attaches ${pe(m.value.instrument)}.`});continue}let l=m.value.instrument;for(let[y,h]of[["instrument","control"],["parent","control"],["title","surface"]]){let b=u.value[y],A=m.value[y];b!==A&&jt(e,{class:h,subject:"attachment",key:`${p}/${y}`,instrument:l,before:b===void 0?void 0:o(u,y,b),after:A===void 0?void 0:o(m,y,A),sentence:`The ${y} of ${c} is now ${A===void 0?"unset":pe(A)} instead of ${b===void 0?"unset":pe(b)}.`})}for(let y of na(u.value.parties,m.value.parties)){let h=u.value.parties[y],b=m.value.parties[y];Qt(h,b)||jt(e,{class:"money",subject:"binding",key:`${p}/parties/${y}`,instrument:l,before:h&&o(u,`parties.${y}`,h),after:b&&o(m,`parties.${y}`,b),sentence:h?b?`${Is(c)} now binds ${pe(y)} to ${wa(b)} instead of ${wa(h)}.`:`${Is(c)} no longer binds ${pe(y)}; it bound ${wa(h)}.`:`${Is(c)} now binds ${pe(y)} to ${wa(b)}.`})}Ri(e,{key:p,instrument:l,owner:`on ${c}`,before:u,after:m,handled:["name","instrument","parent","title","parties"]})}Di(e,{class:"surface",key:`${t}/attachments`,before:o(r,"attachments",i.attachments.map(d=>d.name)),after:o(a,"attachments",s.attachments.map(d=>d.name)),sentence:d=>`The attachments of ${n} are now in the order ${xn(d)}.`}),Ri(e,{key:t,owner:`on ${n}`,before:r,after:a,handled:["id","title","entryActions","authoredFields","columns","fields","attachments"]})}function Is(e){return e.charAt(0).toUpperCase()+e.slice(1)}function gq(e,t){return["label","description"].includes(t)?"surface":dy.has(e)?"money":"control"}function ey(e,t,n){if(t===void 0)return"unset";switch(e.type){case"money":return typeof t=="string"?I9(t,typeof e.currency=="string"?e.currency:sy):wn(t);case"percent":return typeof t=="number"?qo(t,n):wn(t);case"duration":return typeof t=="number"?oy(t):wn(t);default:return typeof t=="string"?pe(t):wn(t)}}function py(e,t){let n=r=>r??[];for(let r of Ci(n(t.before.value),n(t.after.value),a=>a.name)){let a=`${t.key}/${r.name}`,i=r.before&&{path:`${t.before.path}[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`${t.after.path}[${r.after.index}]`,value:r.after.item};if(i&&s&&Qt(i.value,s.value))continue;let o=(s??i).value,d=o.type==="account"?"Account":"Field",p=o.type==="account"?"account":"value"in o?"tunable":"field",u=`${d} ${pe(r.name)} ${t.owner}`;if(!i||!s||i.value.type!==s.value.type){let c=(y,h)=>y.type==="account"?`owned by ${wa(y.owner)}`:`a ${y.type} field${"value"in y?` set to ${ey(y,y.value,h)}`:""}`,l=[i?.value.type,s?.value.type].some(y=>y&&dy.has(y))?"money":"control";jt(e,{class:l,subject:p,key:a,instrument:t.instrument,before:i,after:s,sentence:i?s?`${u} is now ${c(s.value,Ti.after)} instead of ${c(i.value,Ti.before)}.`:`${u} is removed; it was ${c(i.value,Ti.before)}.`:`${u} is added, ${c(s.value,Ti.after)}.`});continue}let m=s.value.type;for(let c of na(i.value,s.value)){if(c==="name"||Qt(i.value[c],s.value[c]))continue;let l=i.value[c],y=s.value[c],h=m==="account"?"account":c==="value"?"tunable":"field",b;m==="account"&&c==="owner"?b=`${u} is now owned by ${wa(y)} instead of ${wa(l)}.`:["value","minimum","maximum"].includes(c)?b=`${c==="value"?"The value":`The ${c}`} of ${u.charAt(0).toLowerCase()}${u.slice(1)} is now ${ey(s.value,y,Ti.after)} instead of ${ey(i.value,l,Ti.before)}.`:c==="optional"?b=`${u} is now ${y?"optional":"required"}.`:c==="sensitive"?b=`${u} is ${y?"now":"no longer"} sensitive.`:b=`The ${c} of ${u.charAt(0).toLowerCase()}${u.slice(1)} is now ${y===void 0?"unset":typeof y=="string"?pe(y):wn(y)} instead of ${l===void 0?"unset":typeof l=="string"?pe(l):wn(l)}.`,jt(e,{class:c==="value"&&yq.has(m)||c==="optional"||c==="sensitive"?"control":gq(m,c),subject:h,key:`${a}/${c}`,instrument:t.instrument,before:l===void 0?void 0:{path:`${i.path}.${c}`,value:l},after:y===void 0?void 0:{path:`${s.path}.${c}`,value:y},sentence:b})}}Di(e,{class:"surface",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(r=>r.name)},after:{...t.after,value:n(t.after.value).map(r=>r.name)},sentence:r=>`The fields ${t.owner} are now in the order ${xn(r)}.`})}function k9(e,t){let n=a=>a??[],r=a=>["shift","step","banking"].includes(a.op)?"control":"money";for(let a of Ci(n(t.before.value),n(t.after.value),i=>i.target)){let i=a.before&&{path:`${t.before.path}[${a.before.index}]`,value:a.before.item},s=a.after&&{path:`${t.after.path}[${a.after.index}]`,value:a.after.item};if(i&&s&&Qt(i.value,s.value))continue;let o=`${pe(a.name)} ${t.owner}`;jt(e,{class:[i,s].some(d=>d&&r(d.value)==="money")?"money":"control",subject:"calculation",key:`${t.key}/${a.name}`,instrument:t.instrument,before:i,after:s,sentence:i?s?`The calculation of ${o} is now ${cc(s.value)} instead of ${cc(i.value)}.`:`The calculation of ${o} is removed; it was ${cc(i.value)}.`:`The calculation of ${o} is added: ${cc(s.value)}.`})}Di(e,{class:"control",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(a=>a.target)},after:{...t.after,value:n(t.after.value).map(a=>a.target)},sentence:a=>`The calculations ${t.owner} now run in the order ${xn(a)}.`})}function ny(e,t){let{removed:n,added:r}=pq(t.before.value,t.after.value),a=t.render;for(let[s,o]of n)jt(e,{class:"control",subject:t.subject,key:`${t.key}/${Vt(ta(s))}`,instrument:t.instrument,before:{path:`${t.before.path}[${o}]`,value:s},sentence:`${t.lead} no longer ${t.subject==="invocation"?"runs":"requires"} ${a(s)}.`});for(let[s,o]of r)jt(e,{class:"control",subject:t.subject,key:`${t.key}/${Vt(ta(s))}`,instrument:t.instrument,after:{path:`${t.after.path}[${o}]`,value:s},sentence:`${t.lead} now ${t.subject==="invocation"?"runs":"requires"} ${a(s)}.`});if(n.length||r.length)return;let i=s=>(s??[]).map(o=>Vt(ta(o)));Qt(i(t.before.value),i(t.after.value))||jt(e,{class:t.subject==="invocation"?"control":"surface",subject:"order",key:`${t.key}/order`,instrument:t.instrument,before:t.before,after:t.after,sentence:`${t.lead} now ${t.subject==="invocation"?"runs its invocations":"checks its requirements"} in a different order.`})}function hq(e){let t=e,n=t.instrument?`a new ${pe(t.instrument)}`:t.reference?pe(t.reference):`each selected ${xn(typeof t.selection.instrument=="string"?[t.selection.instrument]:t.selection.instrument)}`;return`${pe(t.action)} on ${n}`}function Bo(e){switch(e.operation.slice(18)){case"create":return`moves ${ra(e.amount,!0)} from ${pe(e.from)} to ${pe(e.to)}`;case"reserve":return`reserves ${ra(e.amount,!0)} from ${pe(e.from)} to ${pe(e.to)}`;case"post":return`posts the reservation ${pe(e.transfer)}`;case"void":return`releases the reservation ${pe(e.transfer)}`;default:return`runs ${pe(e.operation)}`}}function fq(e,t){let n=r=>r;for(let r of Ci(n(t.before.value),n(t.after.value),a=>a.key)){let a=`${t.key}/${r.name}`,i=r.before&&{path:`${t.before.path}[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`${t.after.path}[${r.after.index}]`,value:r.after.item};if(i&&s&&Qt(i.value,s.value))continue;if(!i||!s||i.value.operation!==s.value.operation){jt(e,{class:"money",subject:"move",key:a,instrument:t.instrument,before:i,after:s,sentence:i?s?`${t.lead} now ${Bo(s.value)} in move ${pe(r.name)}, replacing a move that ${Bo(i.value)}.`:`${t.lead} no longer ${Bo(i.value)} (move ${pe(r.name)}).`:`${t.lead} now also ${Bo(s.value)} (move ${pe(r.name)}).`});continue}let o=i.value,d=s.value,p=y=>ra(y.amount,!0),u=(y,h,b,A)=>{Qt(b,A)||jt(e,{class:"money",subject:"move",key:`${a}/${y}`,instrument:t.instrument,before:b===void 0?void 0:{path:`${i.path}.${y}`,value:b},after:A===void 0?void 0:{path:`${s.path}.${y}`,value:A},sentence:h})},m=d.operation==="internal_transfer.reserve"?"reserves":"moves";u("amount",`${t.lead} now ${m} ${p(d)} instead of ${p(o)} from ${pe(d.from??"")} (move ${pe(r.name)}).`,o.amount,d.amount),u("from",`${t.lead} now ${m} ${p(d)} from ${pe(d.from??"")} instead of ${pe(o.from??"")} (move ${pe(r.name)}).`,o.from,d.from),u("to",`${t.lead} now ${m} ${p(d)} to ${pe(d.to??"")} instead of ${pe(o.to??"")} (move ${pe(r.name)}).`,o.to,d.to),u("transfer",`${t.lead} now settles the reservation ${pe(d.transfer??"")} instead of ${pe(o.transfer??"")} (move ${pe(r.name)}).`,o.transfer,d.transfer),u("capture",`${t.lead} now keeps move ${pe(r.name)} as ${d.capture?pe(d.capture):"nothing"} instead of ${o.capture?pe(o.capture):"nothing"}.`,o.capture,d.capture),u("boundary",`${t.lead} now holds move ${pe(r.name)} at ${d.boundary?wa(d.boundary):"no boundary"} instead of ${o.boundary?wa(o.boundary):"no boundary"}.`,o.boundary,d.boundary);let c=o.economics,l=d.economics;if(!c||!l){let y=h=>h?`${h.purpose.replaceAll("_"," ")} from ${pe(h.sourceParty)}`:"no purpose";u("economics",`${t.lead} now books move ${pe(r.name)} as ${y(l)} instead of ${y(c)}.`,c,l)}else u("economics.purpose",`${t.lead} now books move ${pe(r.name)} as ${l.purpose.replaceAll("_"," ")} instead of ${c.purpose.replaceAll("_"," ")}.`,c.purpose,l.purpose),u("economics.sourceParty",`${t.lead} now names ${pe(l.sourceParty)} as the source of move ${pe(r.name)} instead of ${pe(c.sourceParty)}.`,c.sourceParty,l.sourceParty),u("economics.reversalOf",l.reversalOf?c.reversalOf?`${t.lead} now books move ${pe(r.name)} as the reversal of ${pe(l.reversalOf)} instead of ${pe(c.reversalOf)}.`:`${t.lead} now books move ${pe(r.name)} as the reversal of ${pe(l.reversalOf)}.`:`${t.lead} no longer books move ${pe(r.name)} as the reversal of ${pe(c.reversalOf)}.`,c.reversalOf,l.reversalOf),u("economics.taxOn",l.taxOn?c.taxOn?`${t.lead} now books move ${pe(r.name)} as the tax on move ${pe(l.taxOn)} instead of ${pe(c.taxOn)}.`:`${t.lead} now books move ${pe(r.name)} as the tax on move ${pe(l.taxOn)}.`:`${t.lead} no longer books move ${pe(r.name)} as the tax on move ${pe(c.taxOn)}.`,c.taxOn,l.taxOn);Ri(e,{key:a,instrument:t.instrument,owner:`on move ${pe(r.name)} of ${t.lead.charAt(0).toLowerCase()}${t.lead.slice(1)}`,before:i,after:s,handled:["key","operation","amount","from","to","transfer","capture","boundary","economics"]})}Di(e,{class:"money",key:t.key,instrument:t.instrument,before:{...t.before,value:n(t.before.value).map(r=>r.key)},after:{...t.after,value:n(t.after.value).map(r=>r.key)},sentence:r=>`${t.lead} now runs its moves in the order ${xn(r)}.`})}function _q(e){return e.fields.some(t=>dy.has(t.type))||Object.values(e.actions).some(t=>t.moves.length>0)}function bq(e,t,n){for(let r of Ci(t.instruments,n.instruments,a=>a.id)){let a=`instruments/${r.name}`,i=r.before&&{path:`$.instruments[${r.before.index}]`,value:r.before.item},s=r.after&&{path:`$.instruments[${r.after.index}]`,value:r.after.item};if(!(i&&s&&Qt(i.value,s.value))){if(!i||!s){let o=(i??s).value;jt(e,{class:_q(o)?"money":"control",subject:"instrument",key:a,instrument:r.name,before:i,after:s,sentence:`Instrument ${pe(r.name)} is ${i?"removed":"added"}, with ${Ia(o.actionOrder.length,"action")}: ${xn(o.actionOrder)}.`});continue}xq(e,a,r.name,i,s)}}}function xq(e,t,n,r,a){let i=r.value,s=a.value,o=pe(n),d=(m,c,l)=>l===void 0?void 0:{path:`${m.path}.${c}`,value:l},p=(m,c,l,y)=>{Qt(i[m],s[m])||jt(e,{class:c,subject:l,key:`${t}/${m}`,instrument:n,before:d(r,m,i[m]),after:d(a,m,s[m]),sentence:`The ${m} of instrument ${o} is now ${y(s[m])} instead of ${y(i[m])}.`})},u=m=>m===void 0?"unset":typeof m=="string"?pe(m):wn(m);p("summary","surface","instrument",u),p("template","surface","instrument",u),p("examples","surface","instrument",m=>Array.isArray(m)?Ia(m.length,"example"):"none"),p("scope","control","instrument",u),p("revisioned","control","instrument",u),p("subject","control","instrument",u),p("oncePerRecord","control","instrument",u),p("accepts","control","instrument",u),p("persons","control","instrument",m=>Array.isArray(m)?m.map(c=>pe(`${c.name}${c.optional?"?":""}`)).join(", "):"none"),p("family","control","instrument",m=>{if(!m||typeof m!="object")return"none";let c=m;return`${pe(`${c.module}.${c.exportPath}`)} ${c.digest?`at ${c.digest.slice(0,12)}`:`revision ${c.revision}`}`}),py(e,{key:`${t}/fields`,instrument:n,owner:`on ${o}`,before:{path:`${r.path}.fields`,value:i.fields},after:{path:`${a.path}.fields`,value:s.fields}}),k9(e,{key:`${t}/calculate`,instrument:n,owner:`on ${o}`,before:{path:`${r.path}.calculate`,value:i.calculate},after:{path:`${a.path}.calculate`,value:s.calculate}}),vq(e,t,n,r,a);for(let m of na(i.actions,s.actions)){let c=Object.hasOwn(i.actions,m)?i.actions[m]:void 0,l=Object.hasOwn(s.actions,m)?s.actions[m]:void 0,y=c&&{path:`${r.path}.actions.${m}`,value:c},h=l&&{path:`${a.path}.actions.${m}`,value:l};if(y&&h&&Qt(y.value,h.value))continue;let b=`Action ${pe(m)} on ${o}`;if(!y||!h){let A=(y??h).value;jt(e,{class:A.moves.length?"money":"control",subject:"action",key:`${t}/actions/${m}`,instrument:n,before:y,after:h,sentence:`${b} is ${y?"removed":"added"}; it is run by ${ty(A.actor)}${A.moves.length?` and ${A.moves.map(Bo).join(", then ")}`:""}.`});continue}$q(e,`${t}/actions/${m}`,n,b,y,h)}Di(e,{class:"surface",key:`${t}/actionOrder`,instrument:n,before:{path:`${r.path}.actionOrder`,value:i.actionOrder},after:{path:`${a.path}.actionOrder`,value:s.actionOrder},independent:!0,sentence:m=>`The actions of ${o} are now listed in the order ${xn(m)}.`}),ny(e,{key:`${t}/invariants`,instrument:n,subject:"requirement",lead:`Instrument ${o} always`,render:z9,before:{path:`${r.path}.invariants`,value:i.invariants},after:{path:`${a.path}.invariants`,value:s.invariants}}),wq(e,t,n,r,a),Ri(e,{key:t,instrument:n,owner:`on instrument ${o}`,before:r,after:a,handled:["id","title","summary","template","examples","scope","revisioned","subject","oncePerRecord","accepts","persons","family","fields","calculate","lifecycle","actions","actionOrder","invariants","reports"]})}function vq(e,t,n,r,a){let i=r.value.lifecycle,s=a.value.lifecycle,o=`${r.path}.lifecycle`,d=`${a.path}.lifecycle`,p=pe(n);for(let u of na(Object.fromEntries(i.states.map(m=>[m,m])),Object.fromEntries(s.states.map(m=>[m,m])))){let m=i.states.indexOf(u),c=s.states.indexOf(u);m>=0&&c>=0||jt(e,{class:"control",subject:"state",key:`${t}/states/${u}`,instrument:n,before:m>=0?{path:`${o}.states[${m}]`,value:u}:void 0,after:c>=0?{path:`${d}.states[${c}]`,value:u}:void 0,sentence:`State ${pe(u)} is ${m>=0?"removed from":"added to"} ${p}.`})}Di(e,{class:"surface",key:`${t}/states`,instrument:n,before:{path:`${o}.states`,value:i.states},after:{path:`${d}.states`,value:s.states},sentence:u=>`The states of ${p} are now listed in the order ${xn(u)}.`}),i.initial!==s.initial&&jt(e,{class:"control",subject:"state",key:`${t}/initial`,instrument:n,before:{path:`${o}.initial`,value:i.initial},after:{path:`${d}.initial`,value:s.initial},sentence:`A new ${p} now starts in ${pe(s.initial)} instead of ${pe(i.initial)}.`}),Qt(i.ends&&[...i.ends].sort(),s.ends&&[...s.ends].sort())||jt(e,{class:"control",subject:"state",key:`${t}/ends`,instrument:n,before:i.ends&&{path:`${o}.ends`,value:i.ends},after:s.ends&&{path:`${d}.ends`,value:s.ends},sentence:s.ends?`A ${p} now ends in ${xn(s.ends)}.`:`A ${p} now ends in the states no action leaves.`});for(let u of na(i.labels,s.labels)){let m=i.labels?.[u],c=s.labels?.[u];m!==c&&jt(e,{class:"surface",subject:"state",key:`${t}/labels/${u}`,instrument:n,before:m===void 0?void 0:{path:`${o}.labels.${u}`,value:m},after:c===void 0?void 0:{path:`${d}.labels.${u}`,value:c},sentence:`State ${pe(u)} of ${p} is now labelled ${c===void 0?"with its name":pe(c)} instead of ${m===void 0?"its name":pe(m)}.`})}for(let u of na(i.transitions,s.transitions)){let m=Object.hasOwn(i.transitions,u)?i.transitions[u]:void 0,c=Object.hasOwn(s.transitions,u)?s.transitions[u]:void 0;if(Qt(m,c))continue;let l=y=>y?`from ${xn(y.from)} to ${pe(y.to)}`:"no state change";jt(e,{class:"control",subject:"transition",key:`${t}/transitions/${u}`,instrument:n,before:m&&{path:`${o}.transitions.${u}`,value:m},after:c&&{path:`${d}.transitions.${u}`,value:c},sentence:`Action ${pe(u)} on ${p} now moves ${l(c)} instead of ${l(m)}.`})}Ri(e,{key:`${t}/lifecycle`,instrument:n,owner:`on the lifecycle of ${p}`,before:{path:o,value:i},after:{path:d,value:s},handled:["states","initial","ends","labels","transitions"]})}function $q(e,t,n,r,a,i){let s=a.value,o=i.value,d=(m,c,l)=>l===void 0?void 0:{path:`${m.path}.${c}`,value:l},p=(m,c,l,y)=>{Qt(s[m],o[m])||jt(e,{class:c,subject:l,key:`${t}/${m}`,instrument:n,before:d(a,m,s[m]),after:d(i,m,o[m]),sentence:y(s[m],o[m])})},u=m=>m===void 0?"unset":typeof m=="string"?pe(m):wn(m);for(let m of["summary","title","event","publicAction"])p(m,"surface","action",(c,l)=>`The ${m==="publicAction"?"public name":m} of ${r.charAt(0).toLowerCase()}${r.slice(1)} is now ${u(l)} instead of ${u(c)}.`);p("actor","control","actor",(m,c)=>`${r} is now run by ${ty(c)} instead of ${ty(m)}.`),p("purpose","control","action",(m,c)=>`${r} is now ${c?`an ${String(c)}`:"neither an obligation nor an option"} instead of ${m?`an ${String(m)}`:"neither"}.`),p("allowZero","money","action",(m,c)=>`${r} ${c?"now allows":"no longer allows"} a zero amount.`),p("singleHanded","control","action",(m,c)=>`${r} ${c?"now runs":"no longer runs"} on one staff member's call.`);for(let m of["due","deadline"])p(m,"control","clock",(c,l)=>l===void 0?`${r} no longer has a ${m==="due"?"due time":"deadline"}; it was ${pc(c)}.`:c===void 0?`${r} now has a ${m==="due"?"due time":"deadline"} at ${pc(l)}.`:`${r} now has its ${m==="due"?"due time":"deadline"} at ${pc(l)} instead of ${pc(c)}.`);p("reminder","control","clock",(m,c)=>`${r} now ${c?`reminds ${wn(c)}`:"sends no reminder"} instead of ${m?wn(m):"no reminder"}.`),p("send","control","action",(m,c)=>`${r} now ${c?`sends ${wn(c)}`:"sends no message"} instead of ${m?wn(m):"no message"}.`),p("read","control","action",(m,c)=>`${r} now ${c?`reads ${wn(c)}`:"reads nothing"} instead of ${m?wn(m):"no read"}.`),p("follows","control","action",(m,c)=>`${r} now follows ${u(c)} instead of ${u(m)}.`),p("expansionLimit","control","action",(m,c)=>`The expansion limit of ${r.charAt(0).toLowerCase()}${r.slice(1)} is now ${u(c)} instead of ${u(m)}.`),p("subject","control","requirement",()=>`${r} now asks its subject for ${Ia(o.subject?.requirements.length??0,"requirement")} through ${Ia(o.subject?.adapters.length??0,"adapter")} instead of ${Ia(s.subject?.requirements.length??0,"requirement")} through ${Ia(s.subject?.adapters.length??0,"adapter")}.`),py(e,{key:`${t}/input`,instrument:n,owner:`in the input of ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:{path:`${a.path}.input`,value:s.input},after:{path:`${i.path}.input`,value:o.input}}),ny(e,{key:`${t}/requires`,instrument:n,subject:"requirement",lead:r,render:z9,before:{path:`${a.path}.requires`,value:s.requires},after:{path:`${i.path}.requires`,value:o.requires}});for(let m of na(s.set,o.set)){let c=s.set?.[m],l=o.set?.[m];Qt(c,l)||jt(e,{class:"control",subject:"action",key:`${t}/set/${m}`,instrument:n,before:c&&{path:`${a.path}.set.${m}`,value:c},after:l&&{path:`${i.path}.set.${m}`,value:l},sentence:l?`${r} now sets ${pe(m)} to ${ra(l)}${c?` instead of ${ra(c)}`:""}.`:`${r} no longer sets ${pe(m)}; it set it to ${ra(c)}.`})}k9(e,{key:`${t}/calculate`,instrument:n,owner:`in ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:{path:`${a.path}.calculate`,value:s.calculate},after:{path:`${i.path}.calculate`,value:o.calculate}}),fq(e,{key:`${t}/moves`,instrument:n,lead:r,before:{path:`${a.path}.moves`,value:s.moves},after:{path:`${i.path}.moves`,value:o.moves}}),ny(e,{key:`${t}/invoke`,instrument:n,subject:"invocation",lead:r,render:hq,before:{path:`${a.path}.invoke`,value:s.invoke},after:{path:`${i.path}.invoke`,value:o.invoke}}),Ri(e,{key:t,instrument:n,owner:`on ${r.charAt(0).toLowerCase()}${r.slice(1)}`,before:a,after:i,handled:["summary","title","event","publicAction","actor","purpose","allowZero","singleHanded","due","deadline","reminder","send","read","follows","expansionLimit","subject","input","requires","set","calculate","moves","invoke"]})}function wq(e,t,n,r,a){let i=s=>s??[];for(let s of Ci(i(r.value.reports),i(a.value.reports),o=>o.identity.id)){let o=s.before&&{path:`${r.path}.reports[${s.before.index}]`,value:s.before.item},d=s.after&&{path:`${a.path}.reports[${s.after.index}]`,value:s.after.item};if(o&&d&&Qt(o.value,d.value))continue;let p=`Report ${pe(s.name)} on ${pe(n)}`;jt(e,{class:"surface",subject:"report",key:`${t}/reports/${s.name}`,instrument:n,before:o,after:d,sentence:o?d?`${p} now has a different shape, version ${d.value.identity.version} instead of ${o.value.identity.version}.`:`${p} is removed.`:`${p} is added.`})}}function w9(e){if(!e||typeof e!="object")return;let t=e,n=t.role??t.party;return typeof n=="string"?n:void 0}function ry(e,t,n){if(typeof e=="string"){if(e===t)return n;let r=`party.${t}`;return e===r||e.startsWith(`${r}.`)?`party.${n}${e.slice(r.length)}`:e}return Array.isArray(e)?e.map(r=>ry(r,t,n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,a])=>[r,ry(a,t,n)])):e}function Iq(e,t,n){let r=new Set,a=new Map;for(let i of e){if(i.subject!=="binding"||i.kind!=="changed")continue;let s=w9(i.before),o=w9(i.after);if(!s||!o||s===o||!i.instrument||!t.instruments.some(c=>c.id===i.instrument)||!n.instruments.some(c=>c.id===i.instrument))continue;let d=e.filter(c=>c!==i&&!r.has(c)&&c.kind==="changed"&&c.subject!=="binding"&&c.instrument===i.instrument&&Qt(ry(c.before,s,o),c.after));if(!d.length)continue;d.forEach(c=>r.add(c));let p=d.filter(c=>c.class==="money").length,u=d.length-p,m=[p?Ia(p,"money reference"):"",u?Ia(u,"control reference"):""].filter(Boolean);a.set(i,{...i,sentence:`${i.sentence.replace(/\.$/,"")}, which reroutes ${m.join(" and ")} in ${pe(i.instrument)}.`,follows:d})}return e.filter(i=>!r.has(i)).map(i=>a.get(i)??i)}var uc,Qt,pe,sy,Ti,dy,yq,q9=ve(()=>{"use strict";gs();ko();hs();$s();uc=["money","control","surface"];Qt=(e,t)=>Vt(ta(e))===Vt(ta(t)),pe=e=>`\`${e}\``;sy=Ka;Ti={before:1e8,after:1e8};dy=new Set(["money","percent","account"]),yq=new Set(["date","duration"])});var ct,L9,j9,cy,zq,kq,qq,Lq,jq,Aq,SS,A9=ve(()=>{"use strict";Fa();xs();ct=Ce(),L9=Y({min:Gn().int().nonnegative(),max:Gn().int().nonnegative().nullable()}),j9=rn([Y({kind:he("instrument"),instrument:ct}),Y({kind:he("role"),role:Oe(un)}),Y({kind:he("party"),party:ct}),Y({kind:he("adapter"),adapter:ct})]),cy=Y({path:ct,scope:ct,instrument:ct,field:ct,owner:j9,book:Oe(["cash","claim"]),key:ct.optional(),contra:Ir()}),zq=rn([j9,Y({kind:Oe(["caller","clock","observation"])}),Y({kind:he("parent"),instruments:ye(ct)})]),kq=Y({kind:Oe(["reference","child"]),via:Oe(["field","attachment","invocation","parent_actor"]),name:ct,targetKind:Oe(["instrument","object"]),targets:ye(ct),cardinality:L9}),qq=Y({key:ct,operation:Bx,amount:vt.nullable(),from:ye(cy),to:ye(cy),disposition:Oe(["held","paid","released","claim","unresolved"]),transfer:ct.nullable(),reservations:ye(Y({instrument:ct,action:ct,key:ct})),economics:Y({purpose:Oe(Zo),sourceParty:ct,reversalOf:ct.nullable()}).nullable(),share:Y({base:ct,bps:Gn(),value:Ce().nullable()}).nullable()}),Lq=Y({name:ct,alias:ct.nullable(),title:ct,actor:tr.shape.actor,roles:ye(zq),from:ye(ct),to:ct.nullable(),references:ye(_s).optional(),invokedBy:ye(Y({instrument:ct,action:ct,alias:ct.nullable(),invocation:tr.shape.invoke.unwrap().element})).optional(),inputs:tr.shape.input,subject:tr.shape.subject,prerequisites:tr.shape.requires,due:tr.shape.due.unwrap().nullable(),deadline:tr.shape.deadline.unwrap().nullable(),calculations:ye(So),assignments:tr.shape.set.unwrap(),moves:tr.shape.moves,moneyEffects:ye(qq),invokes:tr.shape.invoke.unwrap()}),jq=Oe(["stage_and_decisions","payment_review","held_funds","reserved_payment","payment_calendar","funding_progress","cancellation_review","external_checks","report_view"]),Aq=Y({id:ct,summary:ct.optional(),subject:ct.optional(),template:ct.optional(),fields:ye(_s),accounts:ye(cy),relationships:ye(kq),calculations:ye(So),invariants:ye(Wp),initialState:ct,lifecycle:Y({initial:ct,states:ye(Y({name:ct,label:ct,terminal:Ir()})),cancellationActions:ye(ct)}),actions:ye(Lq),reports:Yp.shape.reports.unwrap(),structures:ye(jq)}),SS=Y({currency:ct,percentWhole:Gn().int().positive(),parties:gn(ct,$m),objects:ye(Y({...zm.shape,attachments:ye(Y({...Im.shape,cardinality:L9}))})),instruments:ye(Aq)})});var P9=ve(()=>{"use strict";A9()});var In=ve(()=>{"use strict";xs();hs();Wx();ko();v9();gs();q9();Ya();Mm();Gm();r9();Xm();Tm();bm();Vm();P9();$s()});function U(e,t,n,r="HSX1001"){return je(e,r,t,n)}function je(e,t,n,r){throw new St({code:t,message:n,fix:r,span:e.span,...e.source?{source:e.source}:{}})}function Bn(e,t,n,r,a,{values:i,code:s="given_twice"}={}){let o=m=>e.get(m.source??"program")??"",d=m=>{let{line:c,column:l}=_n(o(m),m.span.start),y=m.source??"program";return`${y===(r.source??"program")?"":`${y} `}${c}:${l}`},[p,u]=(i??[]).map(m=>o(m).slice(m.span.start,m.span.end).trim());throw new St({code:s,message:p&&u&&p!==u?`${t} with different values: ${p} at ${d(n)} and ${u} at ${d(r)}`:`${t}, at ${d(n)} and ${d(r)}`,fix:a,span:r.span,...r.source?{source:r.source}:{},related:[{source:n.source??"program",span:n.span,message:"First given here"}]})}function ot(e,t){try{return t()}catch(n){if(!(n instanceof St))throw n;e.push(n.diagnostic);return}}function lc(e){let t=r=>(r.source??"program")==="program",n=new Set;return e.filter(r=>{let a=JSON.stringify([r.code,r.source??"program",r.span.start,r.span.end,r.message]);return n.has(a)?!1:(n.add(a),!0)}).sort((r,a)=>Number(t(a))-Number(t(r))||S9(r.source??"program",a.source??"program")||r.span.start-a.span.start||S9(r.code,a.code))}function Pq(e,t){let n=Array.from({length:e.length+1},(r,a)=>Array.from({length:t.length+1},(i,s)=>a===0?s:s===0?a:0));for(let r=1;r<=e.length;r++)for(let a=1;a<=t.length;a++)n[r][a]=Math.min(n[r-1][a]+1,n[r][a-1]+1,n[r-1][a-1]+(e[r-1]===t[a-1]?0:1)),r>1&&a>1&&e[r-1]===t[a-2]&&e[r-2]===t[a-1]&&(n[r][a]=Math.min(n[r][a],n[r-2][a-2]+1));return n[e.length][t.length]}function en(e,t){let n=Math.max(1,Math.floor(e.length/3)),r,a=n+1;for(let i of t){let s=Pq(e,i);s<a&&([r,a]=[i,s])}return r===void 0?"":` Did you mean \`${r}\`?`}function Oq(e,t){let n=Dn(t),r=10n**BigInt(n),a=String(e%r).padStart(n,"0");return`${e/r}${n?`.${a}`:""} ${t}`}function mc(e,t,n="SAR"){let r=e.value;if(!/^\d{1,18}$/.test(r))return{code:Z9,message:`${t} is money, and "${r}" is text`,fix:`write an amount such as 0 ${n}`,span:e.span,...e.source?{source:e.source}:{}};let a=Oq(BigInt(r),n);return{code:Z9,message:`${t} is money, and the text "${r}" counts minor units, so it reads as ${a}`,fix:`write ${a.replace(/\.0+ /," ")}`,span:e.span,...e.source?{source:e.source}:{}}}function yc(e,t,n){return{code:"currency_mismatch",message:`${t} is in ${n}, and ${e.value} is not`,fix:`write the amount in ${n}, or convert it with ratio into a ${n} field`,span:e.span,...e.source?{source:e.source}:{}}}var St,S9,Z9,Er=ve(()=>{"use strict";Ha();In();St=class extends Error{constructor(n){super(n.message);this.diagnostic=n}diagnostic};S9=(e,t)=>e<t?-1:e>t?1:0;Z9="money_text_literal"});function my(e){return e>=Uo.needs_review?"needs_review":e>=Uo.complex?"complex":e>=Uo.standard?"standard":"simple"}function yy(e){let t={instruments:e.instruments.length,states:0,actions:0,transitions:0,invocations:0,moves:0,unwinds:0,requires:0,clocks:0,calculations:0,expressions:0,parties:Object.keys(e.parties).length,actors:0,exposures:0},n=new Set,r=o=>typeof o=="string"?o:"party"in o?`party:${o.party}`:`parent:${[o.parent].flat().join(",")}`,a=(o=[])=>o.reduce((d,p)=>d+(["compare","state","all","any","not"].includes(p.kind)?ji(p):0),0);for(let o of e.instruments){t.states+=o.lifecycle.states.length,t.expressions+=a(o.invariants)+o.calculate.reduce((d,p)=>d+tc(p),0),t.transitions+=Object.keys(o.lifecycle.transitions).length,t.requires+=o.invariants?.length??0,t.calculations+=o.calculate.length;for(let d of Object.values(o.actions))t.actions++,t.invocations+=d.invoke?.length??0,t.moves+=d.moves.length,t.unwinds+=d.moves.filter(p=>p.operation==="internal_transfer.reserve"||p.operation==="internal_transfer.void").length,t.requires+=d.requires.length,t.clocks+=+!!d.due+ +!!d.deadline+ +!!d.reminder,t.calculations+=d.calculate?.length??0,t.expressions+=a(d.requires)+(d.calculate??[]).reduce((p,u)=>p+tc(u),0)+Object.values(d.set??{}).reduce((p,u)=>p+ei(u),0)+d.moves.reduce((p,u)=>p+("amount"in u?ei(u.amount):0),0)+(d.invoke??[]).reduce((p,u)=>p+(u.guard?ji(u.guard):0)+Object.values(u.input).reduce((m,c)=>m+ei(c),0),0),d.publicAction&&t.exposures++,n.add(r(d.actor))}t.actors=n.size;let i=ly,s=Math.round(i.flow*Math.log2(1+t.transitions+t.invocations)+i.move*t.moves+i.unwind*t.unwinds+i.clock*t.clocks+i.party*t.parties+i.actor*t.actors+i.requirement*t.requires+i.calculation*t.calculations+i.expression*t.expressions);return{factor:s,tier:my(s),counts:t}}function Fo(e){let t={},n=new Set,r=(a,i)=>{let s=`${a}.${i}`;if(t[s])return t[s];if(n.has(s))throw new Error(`Invocation cycle at ${s}`);let o=e.instruments.find(m=>m.id===a),d=o?.actions[i];if(!o||!d)throw new Error(`Unknown invocation ${s}`);n.add(s);let p=(m=[])=>m.filter(c=>c.op==="rate_of").length,u={transfers:d.moves.length,accounts:i==="create"?o.fields.filter(m=>m.type==="account"&&m.owner==="self").length:0,invocations:0,rateSteps:(p(d.calculate)+2*p(o.calculate))*Dm(an(e.udl))};for(let m of d.invoke??[]){let c=Sq(e,o,d,m).map(y=>r(y,m.action)),l="selection"in m?m.selection.limit:"instrument"in m?m.range?.maximum??1:1;u.transfers+=l*Math.max(0,...c.map(y=>y.transfers)),u.accounts+=l*Math.max(0,...c.map(y=>y.accounts)),u.invocations+=l*(1+Math.max(0,...c.map(y=>y.invocations))),u.rateSteps+=l*Math.max(0,...c.map(y=>y.rateSteps))}return n.delete(s),t[s]=u,u};for(let a of e.instruments)for(let i of Object.keys(a.actions))r(a.id,i);return{actions:t,complexity:yy(e)}}function Sq(e,t,n,r){if("instrument"in r)return[r.instrument];if("selection"in r)return typeof r.selection.instrument=="string"?[r.selection.instrument]:[...r.selection.instrument];let a=mt(e,t,r.reference,n.input);return a?.type==="ref"?typeof a.target=="string"?[a.target]:[...a.target]:[]}function R9(e,t=Fo(e)){let n=[];for(let r of e.instruments){let a=r.lifecycle.transitions.create?.to??r.lifecycle.initial;for(let[i,s]of Object.entries(r.actions)){let o=t.actions[`${r.id}.${i}`],d=i!=="create"&&s.publicAction&&r.subject&&r.lifecycle.transitions[i]?.from.includes(a)?t.actions[`${r.id}.create`]:void 0,p=1+o.invocations+(d?1+d.invocations:0),u=o.transfers+(d?.transfers??0);(p>ki||u>Fp)&&n.push({instrument:r.id,action:i,create:!!d,invocations:p,transfers:u})}}return n}var uy,T9,D9,Uo,ly,Ko=ve(()=>{"use strict";In();uy=262144,T9=2*uy,D9=["simple","standard","complex","needs_review"],Uo={standard:60,complex:150,needs_review:400},ly={flow:10,move:2,unwind:2,clock:2,party:3,actor:3,requirement:1,calculation:1,expression:1}});function E9(e,t,n,r){let a=new Set;return e.flatMap(i=>{let s=ot(r,()=>(a.has(i.name)&&U(i,`check "${i.name}" is declared twice`,"rename one","given_twice"),a.add(i.name),Zq(i,t,n)));return s?[s]:[]})}function Zq(e,t,n){let r=[],a={},i=[],s=[],o=new Map,d=new Set,p=new Set,u=new Set,m,c=(g,I,O,D)=>{let _=[...I];return _.includes(g.name)||U(g,`${O} ${g.name} is not declared.${en(g.name,_)}`,D,"check_unknown_name"),g.name},l=g=>c(g,r.map(I=>I.id),"customer",`declare customer ${g.name} "Name" before this step`),y=g=>c(g,o.keys(),"object","create it on an earlier step"),h=Object.values(t.parties).flatMap(g=>g.kind==="staff"&&g.role?[g.role]:[]),b=g=>c(g,h,"staff role","name a role a staff party of the program holds"),A=new Set,Z=g=>{if(!g||typeof g!="object")return;let{kind:I,policy:O}=g;I==="approval"&&typeof O=="string"&&A.add(O),Object.values(g).forEach(Z)};for(let g of t.instruments)for(let I of Object.values(g.actions))Z(I.requires);let k=(g,I,O)=>{I.has(g.name)&&U(g,`${O} twice`,"rename one","given_twice"),I.add(g.name)},f=(g,I)=>{(d.has(g.name)||p.has(g.name))&&U(g,"remembered twice","rename one","given_twice"),I.add(g.name)},z=(g,I,O=!1)=>{g.kind!=="money"&&U(g,"expected an amount",`write an amount such as 100 ${I}`);let D=O&&g.value.startsWith("-"),_=n(D?{...g,value:g.value.slice(1)}:g);return!g.value.endsWith(` ${I}`)&&_!=="0"&&U(g,`a balance is in ${I}, and ${g.value} is not`,`write the balance in ${I}`,"currency_mismatch"),D&&_!=="0"?`-${_}`:_},P=g=>{let I=t.objects.find(D=>D.id===g),O=new Set(I.attachments.map(D=>D.instrument));return t.instruments.filter(D=>O.has(D.id))},T=(g,I)=>{let O=t.objects.find(_=>_.id===g);c(I,O.attachments.map(_=>_.name),`${g} attachment`,`name an attachment of object ${g}`);let{instrument:D}=O.attachments.find(_=>_.name===I.name);return t.instruments.find(_=>_.id===D)},$=g=>{let I=g.name.split(".");if(I.length===1)return c(g,[Ei,...r.map(X=>X.id)],"balance",`name a customer, ${Ei} or object.attachment.account`),t.currency;let[O,D,_]=I;I.length!==3&&U(g,`${g.name} is not an account`,"write object.attachment.account","check_shape");let S=o.get(y({name:O,span:g.span})),C=T(S,{name:D,span:g.span}),E=C.fields.filter(X=>X.type==="account");c({name:_,span:g.span},E.map(X=>X.name),`${O}.${D} account`,`name an account field of ${C.id}`);let F=E.find(X=>X.name===_);return"currency"in F&&F.currency||t.currency},q=g=>Object.fromEntries(g.entries.map(I=>{let O={name:I.key,span:I.span};return[I.key,z(I.value,$(O),!0)]})),R=(g,I=t.currency)=>{if(g.kind==="list")return g.items.map(O=>R(O));if(g.kind==="block")return Object.fromEntries(g.entries.map(O=>[O.key,R(O.value)]));if(g.kind==="money"){let[O,D]=g.value.split(" ");D!==I&&!/^0+(?:\.0*)?$/.test(O)&&U(g,`this input is in ${I}, and ${g.value} is not`,`write the amount in ${I}`,"currency_mismatch")}if(g.kind==="call"&&["agreement","object","record"].includes(g.name)){let[O]=g.args;(g.args.length!==1||O?.kind!=="name")&&U(g,`${g.name} takes one name`,`write ${g.name}(name)`);let D={name:O.value,span:O.span};return g.name==="agreement"?c(D,d,"agreement","remember it on an earlier step"):g.name==="record"?c(D,u,"record","record it on an earlier step"):y(D),`$${g.name}:${O.value}`}return n(g)},H=(g,I=[])=>Object.fromEntries(g.entries.map(O=>[O.key,R(O.value,I.find(D=>D.name===O.key)?.currency)])),x=(g,I)=>{for(let _ of g.entries)c({name:_.key,span:_.span},I.map(S=>S.name),"field","name a field of the agreement this step reads");let O=_=>_.value.kind==="name"?/^(\w+)\.(iban|reference)$/.exec(_.value.value):null,D=H({...g,entries:g.entries.filter(_=>!O(_))},I);for(let _ of g.entries){let[,S,C]=O(_)??[];S&&(c({name:S,span:_.value.span},I.filter(E=>E.type==="account").map(E=>E.name),"account field","name an account field of the agreement this step reads"),D[_.key]=`$account:${S}.${C}`)}return D},w=g=>{let I=y(g.object),O=o.get(I),D=g.attachment?[T(O,g.attachment)]:P(O);c(g.state,(g.recordPath?t.instruments:P(O)).flatMap(S=>S.lifecycle.states),"state",`name a lifecycle state on object ${O}`);let _=g.recordPath?t.instruments.flatMap(S=>S.fields):D.flatMap(S=>S.fields);return{waitFor:{object:I,...g.recordPath?{recordPath:g.recordPath}:{},state:g.state.name,...g.attachment?{attachment:g.attachment.name}:{}},...g.reads?{reads:x(g.reads,_)}:{}}},v=(g,I,O)=>{let D=P(O).filter(S=>S.actions[g.action.name]?.actor==="observation");c(g.action,D.length?[g.action.name]:P(O).flatMap(S=>Object.entries(S.actions).flatMap(([C,E])=>E.actor==="observation"?[C]:[])),`${O} observation action`,"name an action with actor: observation"),g.role||U(g.action,"an officer maps a desk row",`write ${I}.${g.action.name} as <staff role> on ${g.instance.name}`,"check_shape");let _=g.actor??g.input??g.fields??g.remember;return _&&U(_,"a mapping runs the action with the credit's amount alone","drop the actor, input, fields and remember","check_shape"),g.state&&c(g.state,D.flatMap(S=>S.lifecycle.states),"state",`name a state ${g.action.name} can reach`),{kind:"action",object:I,action:g.action.name,role:b(g.role),credit:g.instance.name,...g.state?{state:g.state.name}:{},...g.status?{status:L(g.status)}:{},...g.code?{code:g.code}:{},...g.reads?{reads:x(g.reads,D.flatMap(S=>S.fields))}:{}}},L=g=>g.kind==="number"&&/^[45]\d\d$/.test(g.value)?Number(g.value):U(g,"expected a refusal","write status 409"),j=(g,I)=>{let O=P(g).filter(D=>Object.values(D.actions).some(_=>_.publicAction===I.name));return c(I,O.length?[I.name]:P(g).flatMap(D=>Object.values(D.actions).flatMap(_=>_.publicAction?[_.publicAction]:[])),`${g} action`,`name an action object ${g} exposes`),O};for(let g of e.statements){m&&U(g,"expect closes a check","move this step before expect","check_shape");let I=g.balances?{expected:q(g.balances)}:{};switch(g.kind){case"customer":{let{id:O}=g;(C9.has(O.name)||O.name===Ei)&&U(O,`${O.name} cannot name a customer`,"pick another name"),r.some(D=>D.id===O.name)&&U(O,`customer ${O.name} is declared twice`,"rename one","given_twice"),s.length&&U(g,"customers come before steps","move it up","check_shape"),r.push({id:O.name,name:g.title,...g.organization?{kind:"organization"}:{},...g.fund?{fund:z(g.fund,t.currency)}:{}});for(let D of g.binds){let _=Object.keys(t.parties);c(D,_,"party","bind a party the program declares"),D.name in a&&U(D,`party ${D.name} is bound twice`,"bind it once","given_twice"),a[D.name]=O.name}break}case"clock":{let O=g.at;O.kind!=="date"&&U(O,"a clock step needs a date","write clock 2031-04-01","check_shape"),s.push({kind:"clock",at:n(O),...g.until?w(g.until):{},...I});break}case"read":{let{waitFor:O,...D}=w(g);s.push({kind:"read",...O,...D,...I});break}case"sent":{let O=y(g.object),D=o.get(O),_=(g.attachment?[T(D,g.attachment)]:P(D)).flatMap(X=>Object.values(X.actions).flatMap(ae=>ae.send?[{...ae.send,bindings:ae.subject?.adapters??[]}]:[]));c(g.adapter,_.map(X=>X.adapter),"message adapter",`name the adapter an action of ${D} sends through`);let S=_.filter(X=>X.adapter===g.adapter.name);c(g.type,S.map(X=>X.kind),"message type",`name a type an action of ${D} sends through ${g.adapter.name}`);let C=S.filter(X=>X.kind===g.type.name),E=C.flatMap(X=>X.bindings).find(X=>X.binding===g.adapter.name)?.snapshot?.provider??g.adapter.name,F={};for(let X of g.fields?.entries??[]){c({name:X.key,span:X.span},C.flatMap(W=>Object.keys(W.fields)),"message field",`name a field the ${g.type.name} carries`);let ae=X.value;if(ae.kind==="money"){let W=ae.value.split(" ").at(-1),G=String(n(ae)).padStart(Dn(W)+1,"0"),se=Dn(W);F[X.key]=se?`${W} ${G.slice(0,-se)}.${G.slice(-se)}`:`${W} ${G}`}else ae.kind==="date"?F[X.key]=String(n(ae)).slice(0,10):F[X.key]=String(n(ae))}s.push({kind:"sent",object:O,...g.attachment?{attachment:g.attachment.name}:{},type:g.type.name,adapter:E,...g.fields?{fields:F}:{},...I});break}case"paid":{let O=y(g.object),D=T(o.get(O),g.attachment),_=Object.values(D.actions).flatMap(C=>C.moves.flatMap(E=>E.operation==="internal_transfer.reserve"&&E.boundary?.items?[{adapter:E.boundary.adapter,bindings:C.subject?.adapters??[]}]:[]));c(g.adapter,_.map(C=>C.adapter),"batch adapter",`name the adapter a reserve with items in ${D.id} pays through`);let S=_.flatMap(C=>C.bindings).find(C=>C.binding===g.adapter.name)?.snapshot?.provider??g.adapter.name;s.push({kind:"paid",object:O,attachment:g.attachment.name,adapter:S,items:Object.fromEntries(g.items.entries.map(C=>[C.key,C.value.kind==="name"?C.value.value:String(n(C.value))])),...I});break}case"object":{let{id:O}=g;o.has(O.name)&&U(O,`object ${O.name} is created twice`,"rename one","given_twice");let D=c(g.objectKind,t.objects.map(C=>C.id),"object kind","name an object the program declares"),_=g.owner.name===Ei?Ei:l(g.owner),S=t.objects.find(C=>C.id===D).fields.map(C=>C.name);for(let C of g.fields?.entries??[])c({name:C.key,span:C.span},S,`${D} field`,`name a field of object ${D}`);o.set(O.name,D),s.push({kind:"object",id:O.name,objectKind:D,owner:_,...g.fields?{fields:H(g.fields,t.objects.find(C=>C.id===D).fields)}:{},...I});break}case"action":{let O=y(g.object),D=o.get(O);if(g.instance&&p.has(g.instance.name)){s.push({...v(g,O,D),...I});break}let _=j(D,g.action),S=g.actor&&l(g.actor);S&&g.role&&U(g.role,"a step runs as a customer or as a staff role, not both",`drop ${S} or as ${g.role.name}`,"check_shape");let C=g.role&&b(g.role),E=g.state?.name===Xo;g.state&&!E&&c(g.state,_.flatMap(B=>B.lifecycle.states),"state",`name a state ${g.action.name} can reach`);let F;if(g.status){let B=g.status;F=B.kind==="name"&&B.value==="absent"?"absent":L(B)}let X=g.instance&&c(g.instance,d,"agreement","remember it on an earlier step"),ae=_.flatMap(B=>Object.values(B.actions).filter(te=>te.publicAction===g.action.name)),W=g.input&&H(g.input,ae.flatMap(B=>B.input)),G=_.flatMap(B=>B.fields),se=g.fields&&H(g.fields,G);E&&(g.remember||g.reads)&&U(g.remember??g.state,`a step held for approval has no agreement to ${g.remember?"remember":"read"}`,"remember or read on a step after the approve","check_shape"),g.remember&&f(g.remember,d),s.push({kind:"action",object:O,action:g.action.name,...S?{actor:S}:{},...C?{role:C}:{},...W?{input:W}:{},...se?{fields:se}:{},...E?{status:202,code:Xo}:g.state?{state:g.state.name}:{},...F!==void 0?{status:F}:{},...g.code?{code:g.code}:{},...g.remember?{remember:g.remember.name}:{},...X?{instance:X}:{},...g.reads?{reads:x(g.reads,G)}:{},...I});break}case"approve":{let O=y(g.object),D=o.get(O),_=j(D,g.action),S=s.at(-1);(S?.kind==="action"||S?.kind==="approve")&&S.object===O&&S.action===g.action.name&&(S.kind==="action"&&S.code===Xo||S.kind==="approve"&&!S.state&&!S.status)||U(g,`approve follows ${O}.${g.action.name} -> ${Xo}`,`end the step before with -> ${Xo}`,"check_shape"),g.state&&c(g.state,_.flatMap(C=>C.lifecycle.states),"state",`name a state ${g.action.name} can reach`),s.push({kind:"approve",object:O,action:g.action.name,role:b(g.role),...g.state?{state:g.state.name}:{},...g.status?{status:L(g.status)}:{},...g.code?{code:g.code}:{},...I});break}case"record":{C9.has(g.id.name)&&U(g.id,`${g.id.name} cannot name a record`,"pick another name"),k(g.id,u,`record ${g.id.name} is made`),g.title.length>160&&U(g,"a record title is at most 160 characters","shorten the title","check_shape");let O=g.signers.map(l);s.push({kind:"record",id:g.id.name,form:g.form,title:g.title,...O.length?{signers:O}:{},...g.direction?{direction:g.direction}:{},...I});break}case"policy":{s.length&&U(g,"a policy is written before the first step","move the policy above the first step","check_shape");let O=c(g.key,A,"approval policy",'name a key a requires approval "<key>" of the program names');i.some(S=>S.key===O)&&U(g.key,`policy ${O} twice`,"merge the rows","given_twice");let D=S=>(S.kind!=="money"&&U(S,"expected an amount","write an amount such as 1000000 SAR"),{minor:n(S),currency:S.value.split(" ")[1]}),_=g.rows.map(S=>{(S.by.kind!=="list"||!S.by.items.length)&&U(S.by,"by names staff roles","write by [checker]");let C=S.by.items.map(G=>G.kind==="name"?b({name:G.value,span:G.span}):U(G,"expected a staff role","write by [checker]")),E=S.count?n(S.count):1;(typeof E!="number"||E<1||E>16)&&U(S.count,"count is 1 to 16 people","write count 2");let F=S.within&&n(S.within);S.within&&(typeof F!="number"||F<=0||F>366*864e5)&&U(S.within,"within is a duration up to 366 days","write within 48h","check_shape");let X=S.from&&D(S.from),ae=S.below&&D(S.below);X&&ae&&X.currency!==ae.currency&&U(S.below,`a band is in one currency, and ${X.currency} is not ${ae.currency}`,`write both bounds in ${X.currency}`,"currency_mismatch");let W=(X??ae)?.currency;return{by:C,count:E,...typeof F=="number"?{within:F}:{},...W?{band:{currency:W,...X?{from:X.minor}:{},...ae?{below:ae.minor}:{}}}:{}}});_.length||U(g,"a policy needs a row","write by [checker]","check_shape"),i.push({key:O,rows:_});break}case"fund":{let O=$(g.account);r.some(D=>D.id===g.account.name)&&U(g.account,"a customer is funded where it is declared",`write customer ${g.account.name} "Name" funded <amount>`,"check_shape"),s.push({kind:"fund",account:g.account.name,amount:z(g.amount,O),currency:O,...I});break}case"credit":{g.account.name.split(".").length!==3&&U(g.account,"the bank credits an agreement's account","write credit <amount> to object.attachment.account","check_shape");let O=$(g.account);c(g.state,["matched","open"],"desk outcome","write -> matched when the observation action runs, -> open when the credit parks"),g.remember&&f(g.remember,p),s.push({kind:"credit",account:g.account.name,amount:z(g.amount,O),currency:O,reference:g.reference,...g.remember?{remember:g.remember.name}:{},outcome:g.state.name,...I});break}case"bill":{c(g.category,["sadad","moi"],"biller category","write bill sadad or bill moi");let O=g.due.kind==="money"?g.due.value.split(" ").at(-1):"SAR",[D,_]=g.band??[];s.push({kind:"bill",category:g.category.name,biller:g.biller,number:g.number,amountDue:z(g.due,O),...D&&_?{minimum:z(D,O),maximum:z(_,O)}:{},currency:O,...I});break}case"close":s.push({kind:"close",customer:l(g.customer),...I});break;case"expect":{s.length||U(g,"a check needs a step","add a step before expect","check_shape"),g.balances||U(g,"expect needs balances","write expect balances { }","check_shape"),m={expected:q(g.balances),...g.held?{expectedHeld:z(g.held,t.currency)}:{},...g.pending?{pending:Object.fromEntries(g.pending.entries.map(O=>{let D={name:O.key,span:O.span};O.value.kind!=="block"&&U(O,"expected balances","write name { }","check_shape");let _=O.value.entries.map(S=>[S.key,z(S.value,t.currency)]);return[c(D,[Ei,...r.map(S=>S.id)],"balance",`name a customer or ${Ei}`),Object.fromEntries(_)]}))}:{}};break}}}return m||U(e,"a check ends with expect","write expect balances { }","check_shape"),{name:e.name,customers:r,...Object.keys(a).length?{bindings:a}:{},...i.length?{policies:i}:{},steps:s,...m}}function gc(e){return new Set(e.flatMap(t=>{let n=new Map(t.steps.flatMap(r=>r.kind==="object"?[[r.id,r.objectKind]]:[]));return t.steps.flatMap(r=>r.kind==="action"?[`${n.get(r.object)}.${r.action}`]:[])}))}var C9,Ei,Xo,hc=ve(()=>{"use strict";In();Er();C9=new Set(["customer","clock","object","close","expect","record","fund","credit","bill","approve","policy"]),Ei="operator",Xo="approval_required"});function H9(e,t){let n={span:e.span,...e.source?{source:e.source}:{}},r=(x,w,v=n)=>U({...n,span:v.span},x,w,"report_invalid"),a=new Map(e.body.entries.map(x=>[x.key,x.value]));for(let x of e.body.entries)Tq.has(x.key)||r(`report ${e.name} has no clause ${x.key}`,"write summary, over, states, by and sum",x.value);let i=a.get("summary"),s=i?.kind==="text"?i.value:r(`report ${e.name} needs a summary`,'add summary: "what the officer reads"'),o=x=>x===void 0?[]:x.kind==="list"?x.items:[x],d=x=>x.kind==="name"?x.value:r("expected a name","write a field, state or instrument name",x),p=o(a.get("by"));p.length||r(`report ${e.name} groups by nothing`,"add by: [state], a field, or age(<date field>, [30d, 60d, 90d])");let u=o(a.get("sum")).map(d),m=o(a.get("states")).map(d),c=[],l=[],y=[];for(let x of p){if(x.kind==="call"&&(x.name==="age"||x.name==="until")){let[v,L]=x.args,j=`write ${x.name}(dueAt, [30d, 60d, 90d])`,g=v?d(v):r(`${x.name} names a date field`,j,x),I=o(L).map(_=>{let S=_.kind==="duration"?/^(\d+)d$/.exec(_.value):null;return S?Number(S[1]):r("a day bucket is a whole number of days","write 30d",_)});(!I.length||I.some((_,S)=>S>0&&I[S-1]>=_))&&r(`${x.name} buckets ascend`,j,x);let O=x.name==="until",D=`${g}${O?"Ahead":"Age"}`;c.push({name:g,field:g,at:v}),y.push({column:D,days:`${D}Days`,field:g,ahead:O,bounds:I}),l.push({column:D,at:x});continue}let w=d(x);w==="state"?l.push({column:"state",at:x}):(c.push({name:Hi(w),field:w,at:x}),l.push({column:Hi(w),at:x}))}for(let[x,w]of u.entries())c.push({name:Hi(w),field:w,at:o(a.get("sum"))[x]});let h=new Set(t.instruments.map(x=>x.id)),b=(x,w)=>gy(x,w,t)!==void 0,A=x=>u.some(w=>{let v=gy(x,w,t);return v?.kind==="money"&&v.currency!==t.currency}),Z=x=>c.every(w=>b(x,w.field))&&!A(x)&&m.every(w=>x.lifecycle.states.includes(w)),k=a.get("over"),f;if(k?.kind==="name"&&k.value==="every"){if(f=t.instruments.filter(Z),!f.length&&e.standard)return;f.length||r(`no instrument declares every field and state report ${e.name} reads in ${t.currency}`,"name the instruments in over:, or read fields they declare",k)}else f=(k?o(k):[void 0]).flatMap(x=>{let w=x?d(x):"self",v=e.hosts.map(j=>`${j.id}_${w}`).filter(j=>h.has(j));return(w==="self"?e.hosts.map(j=>j.id):v.length?v:h.has(w)?[w]:r(`report ${e.name} reads ${w}, which is not an instrument or a record of ${e.hosts[0].id}`,"name self, a record of this instrument, a program instrument, or every",x)).map(j=>t.instruments.find(g=>g.id===j))});for(let x of f){for(let w of c)b(x,w.field)||r(`${x.id} declares no field ${w.field} a report can read`,"read a money, integer, date, text, enum, ref or account field, or an account's balance, iban or reference",w.at);for(let w of m)x.lifecycle.states.includes(w)||r(`${x.id} has no state ${w}`,`use one of ${x.lifecycle.states.join(", ")}`,a.get("states"))}let z=x=>gy(f[0],x,t);for(let x of u)["money","integer"].includes(z(x).kind)||r(`report ${e.name} sums ${x}, which is not money or a count`,"sum a money field, an integer field or an account's balance");for(let x of y)z(x.field).kind!=="date"&&r(`${x.ahead?"until":"age"} reads ${x.field}, which is not a date`,"name a date field");let P=[{name:"id",field:"id",type:{kind:"text"},required:!0},{name:"state",field:"status",type:{kind:"text"},required:!0}];for(let x of c)P.some(w=>w.name===x.name)||P.push({name:x.name,field:x.field,type:z(x.field),required:!1});let T=[],$;for(let x of m)T.push({id:`${x}State`,op:"literal",type:{kind:"text"},value:x},{id:`${x}Selected`,op:"equal",left:"state",right:`${x}State`}),$?(T.push({id:`${x}OrBefore`,op:"or",left:$,right:`${x}Selected`}),$=`${x}OrBefore`):$=`${x}Selected`;y.length&&T.push({id:"observed",op:"parameter",name:"observationAt"});for(let x of y)T.push({id:x.days,op:"daysBetween",left:x.ahead?"observed":x.field,right:x.ahead?x.field:"observed"},{id:x.column,op:"bucket",value:x.days,bounds:x.bounds});let q=new Map(P.map(x=>[x.name,x.type]));for(let x of y)q.set(x.column,{kind:"text"});let R=[{name:"count",op:"count"},...u.map(x=>({name:Hi(x),op:"sum",value:Hi(x)}))],H=l.map(x=>x.column);return{identity:{id:e.name,version:1,description:s},scope:{kind:"product",currency:t.currency},datasets:[{id:"rows",source:"instrument",instruments:f.map(x=>x.id),rowKey:"id",columns:P,expressions:T,...$?{selection:$}:{}}],selection:{dataset:"rows"},calculation:{joins:[],expressions:[],groupBy:H,aggregates:R,resultExpressions:[]},validation:{empty:"noEligibleFacilities",required:[],rowReconcile:[],reconcile:[],unavailableFacts:[]},output:{formats:["json","csv"],columns:[...H.map(x=>({name:x,label:x,type:q.get(x)})),{name:"count",label:"count",type:{kind:"integer"}},...u.map(x=>({name:Hi(x),label:Hi(x),type:z(x)}))],sort:H},authority:{request:["owner","finance"],read:["owner","admin","operations","finance","viewer"],retention:{years:10}}}}function gy(e,t,n){let[r,a,...i]=t.split(".");if(i.length)return;if(!a&&r==="createdAt")return{kind:"date"};let s=e.fields.find(d=>d.name===r);if(!s)return;let o="currency"in s&&s.currency||n.currency;if(a){let d=s.type==="account"&&a!=="reserved"?Wa(a):void 0;return d==="money"?{kind:"money",currency:o}:d&&{kind:d}}if(s.type==="money")return{kind:"money",currency:o};if(["ref","account","enum","text"].includes(s.type))return{kind:"text"};if(["integer","boolean","date"].includes(s.type))return{kind:s.type}}function Hi(e){return e.replace(/\.(\w)/,(t,n)=>n.toUpperCase())}var Tq,N9=ve(()=>{"use strict";In();Er();Tq=new Set(["summary","over","states","by","sum"])});function fc(e){let t=e.kind==="call"||e.kind==="type"?e.name:e.kind==="name"?e.value:"";if(t==="money")return{minimum:"0",maximum:"999999999999999999"};if(t==="percent")return{minimum:0,maximum:an(er)};if(t==="duration")return{minimum:0,maximum:Number.MAX_SAFE_INTEGER};if(t==="integer"){if(e.kind==="call"){let n=e.args.map(r=>r.kind==="number"?Number(r.value):NaN);return(n.length!==2||n.some(r=>!Number.isSafeInteger(r))||n[0]>n[1])&&U(e,"integer tunable needs ordered safe integer bounds","write integer(1, 12)","field_type_invalid"),{minimum:n[0],maximum:n[1]}}return{minimum:0,maximum:Number.MAX_SAFE_INTEGER}}}var hy=ve(()=>{"use strict";In();Er()});function*ni(e){if(e)switch(e.kind){case"name":yield e;return;case"list":for(let t of e.items)yield*ni(t);return;case"block":for(let t of e.entries)yield*ni(t.value);return;case"call":for(let t of e.args)yield*ni(t);return;case"default":yield*ni(e.type),yield*ni(e.value);return;case"capped":yield*ni(e.rate),yield*ni(e.cap);return}}function U9(e,t,n,r){let a=[],i=new Map;for(let s of r.entries)if(s.key==="calculate")for(let o of bc(s.value)){let d=ri(o,"target");d&&"value"in d&&typeof d.value=="string"&&i.set(d.value,{span:o.span,...o.source?{source:o.source}:{}})}for(let s of r.entries)if(s.key!=="actor")for(let o of ni(s.value)){o.value==="caller"&&["requires","set","calculate","invoke"].includes(s.key)&&a.push(_c(o,"caller_is_not_a_value",`\`caller\` in ${t} is the text "caller", not the person running the action`,"write actor to read the person behind the call"));let d=/^self\.([a-zA-Z0-9_]+)(?:\.|$)/.exec(o.value)?.[1],p=d===void 0?void 0:i.get(d);p&&o.span.start<p.span.start&&a.push(_c(o,"let_target_read",`\`self.${d}\` in ${t} reads the result of \`let ${d}\` at ${B9(e,p)}, not the value at action start: every let runs before the rest of the action`,`move \`let ${d}\` above this read to use its result, or read self.${d} in an earlier action to use the value before it changes`))}for(let s of n.entries)if(s.key==="requires")for(let o of bc(s.value)){let d=ri(o,"kind"),p=ri(o,"left");d?.kind==="text"&&d.value==="compare"&&M9(p)&&M9(ri(o,"right"))&&a.push(_c(ri(p,"literal"),"constant_requirement",`this requirement of ${t} compares two constants, so it never depends on the record`,"compare a field, an input or a tunable, or delete the requirement"))}return a}function F9(e,t){let n=new Map;for(let[a,i]of t)for(let s of i.entries)if(s.key==="calculate")for(let o of bc(s.value)){let d=ri(o,"target");d&&"value"in d&&typeof d.value=="string"&&!n.has(d.value)&&n.set(d.value,{action:a,site:o})}let r=[];for(let[a,i]of t)for(let s of i.entries)if(s.key==="set"&&s.value.kind==="block")for(let o of s.value.entries){let d=n.get(o.key);if(!d)continue;let p=o;r.push(_c({...p,span:{start:o.span.start,end:o.span.start+o.key.length}},"immutable_field",`\`${o.key} = ...\` in ${a} assigns a field that \`let ${o.key}\` in ${d.action} at ${B9(e,d.site)} calculates, and a calculated field takes no assignment`,`write \`let ${o.key} = ...\` in ${a} too, or give the assigned value its own field`))}return r}function K9(e){let t=new Set,n=r=>{for(let a of r.entries)if(a.key.startsWith("when ")&&a.value.kind==="block")n(a.value);else if(a.key==="set"&&a.value.kind==="block")for(let i of a.value.entries)t.add(i.key);else if(a.key==="calculate")for(let i of bc(a.value)){let s=ri(i,"target");s&&"value"in s&&typeof s.value=="string"&&t.add(s.value)}};for(let r of e.entries)r.key.startsWith("action ")&&r.value.kind==="block"&&n(r.value);return t}var B9,_c,bc,ri,Dq,M9,X9=ve(()=>{"use strict";Ha();B9=(e,t)=>{let{line:n,column:r}=_n(e.get(t.source??"program")??"",t.span.start);return`${n}:${r}`},_c=(e,t,n,r)=>({code:t,message:n,fix:r,span:e.span,...e.source?{source:e.source}:{}});bc=e=>e.kind==="list"?e.items:[e],ri=(e,t)=>e.kind==="block"?e.entries.find(n=>n.key===t)?.value:void 0,Dq=new Set(["number","money","percent","duration","date"]),M9=e=>{let t=e&&ri(e,"literal");return!!t&&(Dq.has(t.kind)||t.kind==="text"||t.kind==="name"&&["true","false"].includes(t.value))}});function V9(e,t,n,r,a,i=[]){let s=new Set;for(let o of r){let d=o.key.slice(10),[p,u,m]=d.split("."),c=Object.hasOwn(t.actions,p)?t.actions[p]:void 0;c||U(o,`unknown economics action ${p}`,`choose ${t.actionOrder.join(", ")}, before its public alias${i.length?`, or record.action for a record (${i.join(", ")})`:""}`,"unknown_action");let l=u?c.moves.find(Z=>Z.key===u):c.moves.length===1?c.moves[0]:void 0;(!l||m)&&U(o,`economics ${d} must select one money move`,c.moves.length?`choose ${c.moves.map(Z=>`${p}.${Z.key}`).join(", ")}`:"choose an action that transfers or reserves money","economics_move_unselected"),l.operation==="internal_transfer.void"&&U(o,`economics ${d} cannot classify a void`,"declare the purpose on the reservation or its posting"),s.has(l)&&U(o,`repeated economics for ${d}`,"declare each money move's purpose once"),s.add(l);let y=km.safeParse({...l,economics:a(o.value)});(!y.success||!y.data.economics)&&U(o,`invalid economics for ${d}`,"declare purpose and sourceParty using the move economics fields");let h=y.data.economics;l.economics&&(l.economics.purpose!==h.purpose||l.economics.sourceParty!==h.sourceParty||l.economics.reversalOf!==h.reversalOf||h.taxOn!==void 0&&l.economics.taxOn!==h.taxOn)&&U(o,`economics ${d} conflicts with the instrument's declared purpose`,"keep the instrument's economics or choose an unclassified move");let b=h.sourceParty,A=un.includes(b);if(!A&&e.parties[b]?.kind!=="business"&&U(o,`unknown economic source party ${b}`,"bind sourceParty to owner, actor, operator or a declared business","unknown_party"),!Object.values(n).some(Z=>"role"in Z?Z.role===b:Z.party===b)){let Z="economicSource";for(let k=2;Object.hasOwn(n,Z);k++)Z=`economicSource${k}`;n[Z]=A?{role:b}:{party:b}}l.economics=l.economics?.taxOn&&!h.taxOn?{...h,taxOn:l.economics.taxOn}:h}}function xc(e,t,n){let r=new Map(e.objects.flatMap(a=>a.attachments.map(i=>[i.instrument,i.parties])));return e.instruments.flatMap(a=>{let i=t.get(a.id),s=i&&n.get(i.root);if(!i||!s)return[];let o=s.entry.span.start;return[{instrument:a,selector:i,attach:s,parties:r.get(a.id)??r.get(i.root)??{},span:{start:o,end:o+`attach ${s.name}`.length}}]})}function za(e,t){return t==="operator"||t==="programOperator"||t!==void 0&&e.parties[t]?.role==="program_operator"}function W9(e,t,n){let r=[];for(let{instrument:a,selector:i,attach:s,parties:o,span:d}of xc(e,t,n)){let p=s.template.parameters.filter(m=>m.value.kind==="name"&&m.value.value==="party").map(m=>m.key),u=m=>p.find(c=>o[c]&&ks(o[c])===m)??m;for(let m of a.actionOrder){let c=a.actions[m];for(let l of c.moves){if(l.economics||l.operation!=="internal_transfer.create"&&l.operation!=="internal_transfer.reserve")continue;let y=`${i.prefix}${m}${c.moves.length>1||!/^move\d+$/.test(l.key)?`.${l.key}`:""}`,h=[l.from,l.to].map(z=>/^self\.\w+$/.test(z)?mt(e,a,z,c.input,c):void 0),b=z=>z?.type==="account"&&typeof z.owner=="string"?z.owner:void 0,A=zs(l.from)??(b(h[0])==="self"?void 0:b(h[0])),Z=p.find(z=>o[z]&&!za(e,ks(o[z]))),k=h.some(z=>z?.type==="account"&&z.book!=="cash")?"internal":za(e,zs(l.to))?za(e,A)||!A&&!Z?"internal":"earning":za(e,A)?b(h[1])==="self"?"internal":"participant_payout":"pass_through",f=A?u(A):k==="earning"?Z:"programOperator";r.push({code:"economic_purpose_missing",message:`${s.name}: ${y} moves money with no declared purpose, so the books will not count it as revenue or a payout`,fix:`add economics ${y} { purpose: ${k}, sourceParty: ${f} } inside attach ${s.name}`,span:d})}}}return r}function Y9(e,t,n){let r=[],a=[],i=o=>za(e,o)?"operator":o,s=new Set;for(let{instrument:o,selector:d,attach:p,parties:u,span:m}of xc(e,t,n)){let c=A=>Object.entries(u).find(([,Z])=>[A,i(A)].includes(i(ks(Z))))?.[0],l=A=>{let Z=c(A);return Z&&Z!==A?`${Z}: ${A}`:A},y=e.instruments.find(A=>A.id===d.root)?.actions.create?.actor,h=typeof y=="object"&&"party"in y?i(y.party):void 0,b=h&&h!=="actor"?h:void 0;for(let A of o.actionOrder)for(let Z of o.actions[A].moves){let k="from"in Z?zs(Z.from):void 0,f="to"in Z?zs(Z.to):void 0;if(!k||!f)continue;let z=i(k),P=i(f),T=R=>R==="actor"&&b?b:R,$=`${p.name}:${z}:${P}`;if(s.has($))continue;let q=`${d.prefix}${A}`;if(T(z)===T(P)){s.add($);let R=z!==P?` ${c(b)??b} runs create, so actor is ${b}.`:"";r.push({code:"same_party_move",message:`${p.name}: ${q} moves money from ${l(k)} to ${l(f)}, and both are ${T(z)}.${R} A party cannot pay itself.`,fix:`Bind the paying and receiving parties to different roles, such as ${c(k)??"payer"}: owner and ${c(f)??"payee"}: operator for a customer paying the company.`,span:m})}else!b&&[k,f].includes("actor")&&[k,f].includes("operator")&&(s.add($),a.push({code:"same_party_move",message:`${p.name}: ${q} moves money from ${l(k)} to ${l(f)}. When the company runs create itself, actor is the company and it pays itself.`,fix:`Run create on behalf of a customer, or bind ${c("actor")??"the paying party"}: owner if the record's owner pays.`,span:m}))}}return{errors:r,warnings:a}}function J9(e,t,n){let r=[],a=o=>za(e,o),i=o=>a(o)?"company":o,s=o=>o==="owner"||o==="actor";for(let{instrument:o,selector:d,attach:p,parties:u,span:m}of xc(e,t,n)){let c=l=>!a(l)&&Object.entries(u).find(([,y])=>ks(y)===l)?.[0]||l;for(let l of o.actionOrder){let y=o.actions[l];for(let h of y.moves){if(!h.economics||!("amount"in h)||!/^(?:party|self)\.\w+$/.test(h.from))continue;let b=mt(e,o,h.from,y.input,y);if(b?.type!=="account")continue;let A=b.owner==="self"||typeof b.owner!="string"?"company":i(b.owner),Z=i(h.economics.sourceParty);if(A===Z||s(A)&&s(Z))continue;let k=/^party\.\w+$/.test(h.to)?void 0:mt(e,o,h.to,y.input,y),f=/^party\.\w+$/.test(h.to)?a(h.to.slice(6)):k?.type!=="account"||typeof k.owner!="string"||k.owner==="self"||a(k.owner);if(h.economics.purpose==="earning"&&!h.economics.reversalOf&&b.owner==="self"&&Z!=="company"&&f)continue;let P=`${d.prefix}${l}${y.moves.length>1||!/^move\d+$/.test(h.key)?`.${h.key}`:""}`,T=A==="company"?"your company's":`the ${c(A)}'s`,$=A==="company"?"programOperator":A;r.push({code:"economic_source_unbound",message:`${p.name}: ${P} moves money out of ${h.from.startsWith("party.")?c(h.from.slice(6)):h.from}, which is ${T} account, but names ${c(h.economics.sourceParty)} as the source. Every run of this action would refuse with economic_source_unbound.`,fix:`Set sourceParty: ${$==="programOperator"?$:c($)} on economics ${P}, or move the money from an account ${c(h.economics.sourceParty)} owns.`,span:m})}}}return r}function G9(e,t,n){let r=[];for(let{instrument:a,selector:i,attach:s,parties:o,span:d}of xc(e,t,n)){let p=l=>Object.entries(o).find(([,y])=>za(e,ks(y))?za(e,l):ks(y)===l)?.[0]??l,u=[],m="",c="";for(let l of a.actionOrder){let y=a.actions[l];for(let h of y.moves){let b="to"in h?zs(h.to):void 0;if(!b||!za(e,b))continue;let A=y.moves.find(P=>P.key===`${h.key}Fee`);if(!A||!("to"in A)||zs(A.to)!=="programOperator")continue;let Z=`${l}_${h.key}_feeGross`,f=[...a.calculate??[],...y.calculate??[]].find(P=>P.target===Z)?.bps?.literal;if(f!==void 0&&Number(f)===0)continue;let z=a.fields.find(P=>P.name===Z)?.label??"Fee";m=`${f===void 0?"":`${qo(Number(f),an(e.udl))} `}${z.toLowerCase()}`,c=p(b),u.push(`${i.prefix}${l}`)}}u.length&&r.push({code:"fee_on_company_sale",message:`${s.name}: ${u.join(" and ")} ${u.length===1?"charges":"charge"} the ${m} on ${c}'s share, but ${c} is bound to the company itself, so no ${c} is paid and the company keeps the whole price.`,fix:`Bind \`${c}: customer\` when a customer is paid, or a declared business for a fixed one. Drop the fee when the company itself is paid.`,span:d})}return r}var zs,ks,fy=ve(()=>{"use strict";In();Er();zs=e=>/^party\.(\w+)$/.exec(e??"")?.[1],ks=e=>"role"in e?e.role:e.party});function Vo(e){return qs(e,!1)}function qs(e,t=!0){let n=[],r=[],a=0;for(;a<e.length;){let i=a,s=e.slice(a),o=/^\s+|^\/\/[^\n]*/.exec(s);if(o){a+=o[0].length,t&&o[0].startsWith("//")&&n.push({kind:"comment",text:o[0],span:{start:i,end:a}});continue}let d=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2}))?/.exec(s),p=/^-?\d+(?:\.\d+)?(?:%|ms|[smhdw])?/.exec(s),u=/^[A-Za-z_][A-Za-z0-9_]*/.exec(s),m,c;if(d)m="date",c=d[0];else if(p)m="number",c=p[0];else if(u)m="name",c=u[0];else if(s[0]==='"'){let l=/^"(?:[^"\\\u0000-\u001f]|\\["\\/bfnrt]|\\u[0-9a-fA-F]{4})*"/.exec(s);if(!l){if(r.push({code:"invalid_string",message:"unclosed or invalid string",fix:"close the string and use JSON escapes",span:{start:i,end:i+1}}),t){let y=/^"(?:[^"\\\n]|\\[^\n]?)*(?:"|(?=\n)|$)/.exec(s)?.[0]??'"';a+=y.length,n.push({kind:"string",text:y,span:{start:i,end:a}})}else a++;continue}m="string",c=l[0]}else if(/^(==|!=|<=|>=|->)/.test(s))m="punct",c=s.slice(0,2);else if(/^[{}()[\]:,;=<>?.|+\-*/]/.test(s))m="punct",c=s[0];else{r.push({code:"unexpected_character",message:`unexpected character ${s[0]}`,fix:"remove this character",span:{start:i,end:i+1}}),a++;continue}a+=c.length,n.push({kind:m,text:c,span:{start:i,end:a}})}return n.push({kind:"eof",text:"",span:{start:a,end:a}}),{tokens:n,diagnostics:r}}var Q9,Wo=ve(()=>{"use strict";Q9=["program","header","party","role","currency","instrument","fields","lifecycle","action","expose","as","cap","of","when","checks","requires","invariants","moves","from","to","in","is","has","unique","on","count","sum","hours","between","and","or","not","otherwise","timezone","evidence","approval","family","check","result","maxAge","instruction","reserve","post","void","capture","boundary","key","fee","shares","object","attach","subject","rename","columns","let","then","with","udl","amends","names","hide","use"]});function ar(e){let t={name:"",title:"",currency:"SAR",header:!1,uses:[],decls:[],checks:[],span:{start:0,end:e.length}},n=s=>new TextEncoder().encode(s).length,r=s=>({program:t,warnings:[],diagnostics:[{code:"HSX1004",message:s,fix:"split the program into headers",span:t.span}]});if(n(e)>T9)return r("source exceeds 512 KiB");if(/^\s*[[{]/.test(e))return{program:t,warnings:[],diagnostics:[{code:"HSX1014",message:"JSON is not HSX source",fix:'write program name "Title" followed by HSX declarations',span:{start:e.search(/\S/),end:e.search(/\S/)+1}}]};let a=Vo(e);if(a.diagnostics.length)return{program:t,diagnostics:a.diagnostics,warnings:[]};let i=new vc(a.tokens,e);try{let s=i.program(t);if(i.failures.length)return{program:t,diagnostics:i.failures,warnings:[]};let o=s.checks.reduce((d,p)=>d+n(e.slice(p.span.start,p.span.end)),0);return n(e)-o>uy?r("program exceeds 256 KiB without its checks"):{program:s,diagnostics:[],warnings:i.warnings}}catch(s){if(s instanceof Ni)return{program:t,diagnostics:[s.diagnostic],warnings:[]};throw s}}function rv(e){let t=Vo(e);if(!t.diagnostics.length)try{return new vc(t.tokens).value()}catch(n){if(n instanceof Ni)return;throw n}}function _y(e){if(e.kind==="list")return Math.max(0,...e.items.map(_y));if(e.kind!=="block")return 0;let t=Math.max(0,...e.entries.map(n=>_y(n.value)));return e.entries.some(n=>n.key==="op"||n.key==="kind")?t+1:t}var Ni,ev,Rq,Cq,Eq,Hq,tv,nv,Nq,Mq,vc,ka=ve(()=>{"use strict";Wo();Ko();Ni=class extends Error{constructor(n){super(n.message);this.diagnostic=n}diagnostic};ev=new Set(["rate","ratio","divide","compound","days between","months between"]),Rq=new Set(["actual/365","actual/360","30/360"]),Cq=new Set(["calculate","invoke","set"]),Eq=new Set(["==","!=","<","<=",">",">="]),Hq=["+","-","*","/"],tv=new Set(["sum","minimum","maximum","subtract","multiply","divide","rate","ratio","compound"]),nv=10;Nq=new Set(["divide","rate","ratio","compound","between"]),Mq="36525d",vc=class{constructor(t,n=""){this.tokens=t;this.source=n}tokens;source;index=0;depth=0;guarding=!1;reading=0;failures=[];warnings=[];currencyDeclared=!1;peek(){return this.tokens[this.index]}take(){let t=this.peek();return t.kind!=="eof"&&this.index++,t}at(t){return this.peek().text===t}eat(t){return this.at(t)?(this.take(),!0):!1}fail(t,n,r=this.peek().span,a="HSX1000"){throw new Ni({code:a,message:t,fix:n,span:r})}recover(t){this.index=Math.min(Math.max(this.index,t+1),this.tokens.length-1);let n=r=>r.kind==="name"&&(r.span.start===0||this.source[r.span.start-1]===`
|
|
67
67
|
`);for(;this.peek().kind!=="eof"&&!n(this.peek());)this.take()}expect(t){this.eat(t)||this.fail(`expected ${t}, found ${this.peek().text||"end of file"}`,`write ${t} here`)}identifier(){return this.peek().kind!=="name"&&this.fail("expected a name","write a name starting with a letter"),this.take().text}path(){let t=this.identifier();for(;this.eat(".");)t+="."+this.identifier();return t}separators(){for(;this.eat(",")||this.eat(";"););}span(t){return{start:t,end:this.tokens[Math.max(0,this.index-1)].span.end}}value(){let t=this.expression();return this.peek().kind!=="eof"&&this.fail("expected one value","write one value"),t}program(t){if(this.at("hsx")&&this.tokens[this.index+1]?.kind==="number"){this.take();let n=this.take();n.text!=="1"&&this.fail(`this compiler reads HSX 1, and the source asks for HSX ${n.text}`,"write hsx 1, or remove the line",n.span,"surface_version_unknown")}if(this.eat("header")?t.header=!0:this.expect("program"),t.name=this.identifier(),!t.header&&(this.peek().kind!=="string"&&this.fail("program needs a title","write a quoted title after its name"),t.title=JSON.parse(this.take().text),this.eat("amends"))){let n=this.peek().span.start,r=this.path(),[a,i,...s]=r.split(".");(i!=="programme"||s.length)&&this.fail(`amends takes a base programme, not ${r}`,`write amends ${a}.programme`,this.span(n),"amends_target_invalid"),t.amends={name:a,span:this.span(n)}}for(;this.peek().kind!=="eof";){let n=this.index;try{this.declaration(t)}catch(r){if(!(r instanceof Ni))throw r;this.failures.push(r.diagnostic),this.depth=0,this.recover(n)}}return t}declaration(t){if(this.separators(),this.peek().kind==="eof")return;let n=this.peek().span.start;if(this.at("currency")){this.currencyDeclared&&this.fail("currency is declared twice","keep one currency declaration"),this.take(),this.currencyDeclared=!0,t.currency=this.identifier();return}if(this.at("use")&&this.next(1).kind==="name"){this.take();let s=this.path();(s.split(".").length!==2||t.header)&&this.fail(t.header?"a header uses no other header":`use takes a tenant header, not ${s}`,t.header?"remove the use line":"write use tenant.header, such as use bank.trade",this.span(n),"use_invalid"),t.uses.push({name:s,span:this.span(n)});return}if(this.eat("party")){let s=this.identifier();this.expect(":");let o=this.identifier(),d=this.eat("role")?this.identifier():void 0;t.decls.push({kind:"party",name:s,partyKind:o,...d?{role:d}:{},span:this.span(n)});return}if(this.eat("expose")){let s=this.path();this.expect("as");let o=this.identifier();t.decls.push({kind:"expose",target:s,name:o,span:this.span(n)});return}if(this.at("hide")&&this.next(1).kind==="name"){this.take(),t.decls.push({kind:"hide",target:this.path(),span:this.span(n)});return}if(this.at("accept")&&this.next(1).kind==="name"&&this.next(2).text==="on"){this.take();let s=this.identifier();this.expect("on"),t.decls.push({kind:"accept",property:s,target:this.path(),span:this.span(n)});return}if(this.at("check")&&this.tokens[this.index+1]?.kind==="string"){t.checks.push(this.check());return}if(this.eat("instrument")){let s=this.identifier(),o=this.eat("(")?this.entries(")"):[],d=this.block();t.decls.push({kind:"instrument",name:s,parameters:o,body:d,span:this.span(n)});return}if(this.eat("object")){let s=this.identifier(),o=this.peek().kind==="string"?JSON.parse(this.take().text):s,d=this.eat("amends")?this.named():void 0,p=this.block();t.decls.push({kind:"object",name:s,title:o,...d?{amends:d}:{},body:p,span:this.span(n)});return}let r=this.identifier();this.expect("=");let a=this.path(),i=this.block();t.decls.push({kind:"assignment",name:r,target:a,body:i,span:this.span(n)})}named(){let t=this.peek().span;return{name:this.identifier(),span:t}}text(){return this.peek().kind!=="string"&&this.fail("expected a quoted name",'write a name in quotes, as "Alice"'),JSON.parse(this.take().text)}check(){let t=this.take().span.start,n=this.text();this.expect("{");let r=[];for(;!this.eat("}")&&(this.separators(),!this.eat("}"));){this.peek().kind==="eof"&&this.fail("unclosed check, expected }","add }");let a=this.peek().span.start,i=this.checkStatement();i.kind!=="customer"&&i.kind!=="policy"&&this.eat("balances")&&(i.balances=this.block()),i.span=this.span(a),r.push(i),this.separators()}return{name:n,statements:r,span:this.span(t)}}checkStatement(){let t=this.peek().span;if(this.eat("customer")){let d=this.named(),p=this.text(),u=this.eat("organization"),m=this.eat("funded")?this.atom():void 0,c=[];for(;this.eat("binds");)c.push(this.named());return{kind:"customer",id:d,title:p,organization:u,...m?{fund:m}:{},binds:c,span:t}}if(this.eat("clock")){let d=this.atom();if(!this.eat("until"))return{kind:"clock",at:d,span:t};let p=this.named(),u=this.eat(".")?this.named():void 0;return{kind:"clock",at:d,until:this.read(p,u),span:t}}if(this.eat("record")){let d=this.named();this.expect(":");let p=this.peek().text;p!=="document"&&p!=="message"&&p!=="judgement"&&this.fail("expected document, message or judgement",'write record name: document "Title"'),this.take();let u=this.text(),m=[],c;if(p==="document"&&this.eat("signed")){this.expect("by");do m.push(this.named());while(this.eat(","))}if(p==="message"){let l=this.peek().text;l!=="inbound"&&l!=="outbound"&&this.fail("expected inbound or outbound","write outbound"),this.take(),c=l}return{kind:"record",id:d,form:p,title:u,signers:m,...c?{direction:c}:{},span:t}}if(this.eat("policy")){let d=this.peek().span,p={name:this.text(),span:d};this.expect("{");let u=[];for(;!this.eat("}")&&(this.separators(),!this.eat("}"));){let m=this.peek().span.start;this.expect("by");let c={by:this.atom(),span:this.span(m)};this.eat("count")&&(c.count=this.atom()),this.eat("within")&&(c.within=this.atom()),this.eat("from")&&(c.from=this.atom()),this.eat("below")&&(c.below=this.atom()),c.span=this.span(m),u.push(c),this.separators()}return{kind:"policy",key:p,rows:u,span:t}}if(this.eat("fund")){let d=this.peek().span.start;return{kind:"fund",account:{name:this.path(),span:this.span(d)},amount:this.atom(),span:t}}if(this.at("bill")&&["sadad","moi"].includes(this.next(1).text)&&this.next(2).kind==="string"){this.take();let d=this.named(),p=this.text(),u=this.text();this.expect("due");let m=this.atom(),c;if(this.eat("band")){let l=this.atom();this.expect("to"),c=[l,this.atom()]}return{kind:"bill",category:d,biller:p,number:u,due:m,...c?{band:c}:{},span:t}}if(this.eat("credit")){let d=this.atom();this.expect("to");let p=this.peek().span.start,u={name:this.path(),span:this.span(p)};this.expect("reference");let m=this.text(),c=this.eat("remember")?this.named():void 0;return this.expect("->"),{kind:"credit",amount:d,account:u,reference:m,...c?{remember:c}:{},state:this.named(),span:t}}if(this.eat("approve")){let d=this.named();this.expect(".");let p=this.named();this.eat("as")||this.fail("an approval is decided by a role","write as <role>");let u={kind:"approve",object:d,action:p,role:this.named(),span:t};return this.eat("->")&&this.outcome(u),u}if(this.eat("object")){let d=this.named();this.expect(":");let p=this.named();this.eat("for")||this.fail("an object needs its owner","write for <customer>");let u=this.named(),m=this.at("{")?this.block():void 0;return{kind:"object",id:d,objectKind:p,owner:u,...m?{fields:m}:{},span:t}}if(this.eat("close"))return{kind:"close",customer:this.named(),span:t};if(this.eat("expect")){let d={kind:"expect",span:t};for(;;)if(this.eat("balances"))d.balances=this.block();else if(this.eat("held"))d.held=this.atom();else if(this.eat("pending"))d.pending=this.block();else break;return d}let n=()=>this.at("is")||this.at("record"),r=this.named();if(!this.at(".")&&n())return{kind:"read",...this.read(r),span:t};if(!this.at(".")&&this.at("sent"))return{kind:"sent",...this.sent(r),span:t};let a=this.at(".")?void 0:r,i=a?this.named():r;this.expect(".");let s=this.named();if(!a&&n())return{kind:"read",...this.read(i,s),span:t};if(!a&&this.at("sent"))return{kind:"sent",...this.sent(i,s),span:t};if(!a&&this.at("paid")&&this.next(1).text==="via"){this.take(),this.expect("via");let d=this.named();return this.expect("items"),{kind:"paid",object:i,attachment:s,adapter:d,items:this.block(),span:t}}let o={kind:"action",...a?{actor:a}:{},object:i,action:s,span:t};return this.eat("as")&&(o.role=this.named()),this.at("{")&&(o.input=this.block()),this.eat("fields")&&(o.fields=this.block()),this.eat("on")&&(o.instance=this.named()),this.eat("remember")&&(o.remember=this.named()),this.expect("->"),this.outcome(o),o.state&&this.at("{")&&(o.reads=this.block()),o}outcome(t){this.eat("status")?(t.status=this.atom(),this.peek().kind==="string"&&(t.code=this.text())):t.state=this.named()}sent(t,n){this.expect("sent");let r=this.peek().span,a={name:this.peek().kind==="string"?this.text():this.identifier().toUpperCase(),span:r};this.expect("via");let i=this.named(),s=this.eat("fields")?this.block():void 0;return{object:t,...n?{attachment:n}:{},type:a,adapter:i,...s?{fields:s}:{}}}read(t,n){let r=this.eat("record")?this.path():void 0;this.expect("is");let a=this.named(),i=this.at("{")?this.block():void 0;return{object:t,...n?{attachment:n}:{},...r?{recordPath:r}:{},state:a,...i?{reads:i}:{}}}entries(t,n=!1,r=!1){let a=[],i=new Map,s;for(;!this.eat(t)&&(this.separators(),!this.eat(t));){this.peek().kind==="eof"&&this.fail(`unclosed block, expected ${t}`,`add ${t}`);let o=this.peek().span.start;if(n&&this.at("udl")&&this.next(1).text==="{"){a.push(...this.escape()),this.separators();continue}if(n&&this.at("send")&&this.next(2).text==="via"){a.push(this.send()),this.separators();continue}if(n&&this.at("read")&&this.next(1).text==="bill"&&this.next(2).text==="via"){a.push(this.readBill()),this.separators();continue}let d=n?this.nativeClause():void 0;if(d){let l=d==="calculate"?this.calculation():d==="invoke"?this.invocation():this.assignment(),y=this.span(o),h=d==="set"?a.find(b=>i.get(b)==="set"):i.get(a.at(-1))===d?a.at(-1):void 0;if(h?.value.kind==="block")h.value.entries.push(l);else if(h?.value.kind==="list")h.value.items.push(l);else{let b={key:d,value:d==="set"?{kind:"block",entries:[l],span:y}:{kind:"list",items:[l],span:y},span:y};i.set(b,d),a.push(b)}h&&(h.span={start:h.span.start,end:y.end}),this.separators();continue}if(this.eat("attach")){let l=this.identifier();this.expect("=");let y=this.path(),h=this.block();a.push({key:`attach ${l} = ${y}`,value:h,span:this.span(o)}),this.separators();continue}if(this.at("hide")&&this.next(1).kind==="name"){this.take();let l=this.peek().span.start,y=this.path();a.push({key:"hide",value:{kind:"name",value:y,span:this.span(l)},span:this.span(o)}),this.separators();continue}if(this.eat("rename")){let l=this.block();a.push({key:"rename",value:l,span:this.span(o)}),this.separators();continue}if(this.eat("expose")){let l=this.identifier();this.at(".")&&this.fail(`expose inside an attachment takes one of its own actions, not ${l}.<action>`,`delete this line, or expose a caller action of ${l} at program level: expose <object>.<attachment>.${l}.<action> as <name>`);let y=l;this.eat("as")&&(y=this.identifier()),a.push({key:"expose",value:{kind:"call",name:l,args:[{kind:"name",value:y,span:this.span(o)}],span:this.span(o)},span:this.span(o)}),this.separators();continue}let p=this.path();if(p==="columns"&&!this.at(":")){let l;this.at("[")?l=this.atom():this.at("{")?l=this.block():l={kind:"list",items:[],span:this.span(o)},a.push({key:"columns",value:l,span:this.span(o)}),this.separators();continue}if(p==="checks"&&this.at("{")){a.push({key:p,value:this.checks(),span:this.span(o)}),this.separators();continue}if((p==="action"||p==="report")&&!this.at(":")&&(p+=" "+this.identifier()),p==="economics"&&!this.at(":")&&!this.at("{")&&(p+=" "+this.path()),p==="when"){let l=this.identifier(),y=this.eat("has")?"has":"is";y==="is"&&this.expect("is");let h=[this.identifier()];for(;y==="is"&&this.eat("or");)h.push(this.identifier());a.push({key:`when ${l} ${y} ${h.join(" or ")}`,value:this.block(n,r),span:this.span(o)});continue}let m=["requires","invariants","moves"].includes(p)&&!this.at(":")&&!this.at("{")?{kind:"list",items:[p==="moves"?this.move():this.requirement()],span:this.span(o)}:this.at("{")?this.block(p.startsWith("action "),p==="fields"||p==="input"):(this.expect(":"),this.expression());p==="at"&&(this.at("+")||this.at("rolled"))&&(s=this.bankingDays(m));let c=r&&this.peek().kind==="string"?this.text():void 0;a.push({key:p,value:m,...c!==void 0?{description:c}:{},span:this.span(o)}),this.separators()}if(s){let o=a.find(p=>p.key==="localDay");o?.value.kind!=="block"&&this.fail("a banking clock names the local hour and timezone it falls due at",'add localDay: { hour: 9, timezone: "Asia/Riyadh" }',s.span);let{span:d}=s;o.value.entries.some(p=>["days","direction","banking"].includes(p.key))&&this.fail("the clock already counts its days on localDay","write the banking days on at: or on localDay, not both",d),o.value.entries.push({key:"days",value:s,span:d},{key:"direction",value:{kind:"text",value:"after",span:d},span:d},{key:"banking",value:{kind:"name",value:"true",span:d},span:d})}return a}bankingDays(t){if(this.eat("rolled")){for(let r of["to","the","next","banking","day"])this.expect(r);return{kind:"number",value:"0",span:t.span}}this.expect("+");let n=this.atom();return n.kind!=="number"&&n.kind!=="name"&&this.fail("banking days are a count","write + 5 banking days or + examination banking days",n.span),this.expect("banking"),!this.eat("days")&&!this.eat("day")&&this.fail("expected days after banking","write + 5 banking days"),n}node(t){return{kind:"text",value:t,span:this.peek().span}}record(t){let n=this.peek().span;return{kind:"block",entries:Object.entries(t).map(([r,a])=>({key:r,value:a,span:a.span})),span:n}}operand(t=!1){let n=this.atom();if(t&&this.at("+")){let r=[n];for(;this.eat("+");)r.push(this.atom());return this.record({sum:{kind:"list",items:r,span:this.span(n.span.start)}})}return this.record({[n.kind==="name"&&/^(self|input|party|subject)\./.test(n.value)?"field":"literal"]:n})}operator(){let t=this.take();return["==","!=","<","<=",">",">="].includes(t.text)||this.fail("expected a comparison","write ==, !=, <, <=, >, or >=",t.span),{kind:"text",value:t.text,span:t.span}}checks(){let t=this.peek().span.start;this.expect("{");let n=[];for(;!this.eat("}")&&(this.separators(),!this.eat("}"));){this.peek().kind==="eof"&&this.fail("unclosed checks, expected }","add }");let r=this.peek().span.start,a;if(this.tokens[this.index+1]?.text==="is"){let s=this.atom();this.expect("is"),a=this.record({kind:this.node("is"),tunable:s,is:this.atom()})}else a=this.requirement(!0);let i={rule:{...a,span:this.span(r)}};if(this.eat("when")){let s=this.atom();this.expect("is"),i.when=this.record({selector:s,is:this.atom()})}i.explain=this.block(),n.push({key:"check",value:{...this.record(i),span:this.span(r)},span:this.span(r)}),this.separators()}return{kind:"block",entries:n,span:this.span(t)}}requirement(t=!1){if(this.eat("unique")){let a=this.atom();return this.expect("on"),this.record({kind:this.node("unique"),namespace:a,fields:this.atom()})}if(this.at("count")||this.at("sum")){let a=this.eat("count")?this.node("count"):(this.expect("sum"),this.record({sum:this.atom()}));this.expect("of");let i=this.block(),s=this.operator(),o=this.operand();return this.record({kind:this.node("aggregate"),selection:i,measure:a,operator:s,value:o})}if(this.eat("hours")){let a=this.atom();this.expect("between");let i=this.atom();this.expect("and");let s=this.atom();return this.expect("timezone"),this.record({kind:this.node("hours"),at:a,start:i,end:s,timezone:this.atom()})}if(this.eat("evidence")){if(this.at("record")&&["exists","signed_by"].includes(this.tokens[this.index+1]?.text??"")){let s=this.node("record");this.take();let o=this.node(this.peek().text);this.take();let d=o.kind==="text"&&o.value==="signed_by"?this.atom():this.node("stored");this.expect("for");let p=this.atom(),u=this.eat("within")?this.atom():{kind:"duration",value:Mq,span:this.peek().span};return this.record({kind:this.node("evidence"),subject:p,family:s,check:o,result:d,maxAge:u})}let a=this.atom(),i={kind:this.node("evidence"),subject:a};for(let s of["family","check","result","maxAge"])this.expect(s),i[s]=this.atom();return this.eat("instruction")&&(i.instruction=this.atom()),this.record(i)}if(!t&&this.at("approval")&&(this.next(1).kind==="string"||this.next(1).text==="by"))return this.approval();if(!t)return this.condition();let n=this.operand(t);if(this.eat("in")){let a=n.entries.find(i=>i.key==="field")?.value;return a||this.fail("state requirement needs a reference","write requires self.record in [state]"),this.record({kind:this.node("state"),reference:a,states:this.atom()})}let r=this.operator();return this.record({kind:this.node("compare"),left:n,operator:r,right:this.operand(t)})}approval(){let t=this.take().span.start,n={kind:this.node("approval")},r=()=>this.peek().kind==="name"&&this.next(1).text!==":",a=i=>{let s=["count","within","for","from","below"].find(o=>this.at(o)&&r());s&&this.fail(`\`${s}\` does not belong here in requires approval`,i,this.peek().span,"approval_clause_invalid")};if(this.peek().kind==="string")return n.policy=this.atom(),this.eat("for")&&(n.amount=this.atom()),a('a policy approval takes only for: requires approval "<key>" for self.amount'),{...this.record(n),span:this.span(t)};if(this.expect("by"),n.by=this.atom(),n.count=this.eat("count")?this.atom():{kind:"number",value:"1",span:this.span(t)},this.eat("within")&&(n.within=this.atom()),this.at("for")){let i=this.take().span;n.amount=this.atom();let s={};this.at("from")&&r()&&(this.take(),s.from=this.atom()),this.eat("below")&&(s.below=this.atom()),!s.from&&!s.below&&this.fail("an inline approval reads its amount only for a band","add from <amount>, below <amount> or both after for, or delete for",i,"approval_clause_invalid"),n.band=this.record(s)}return a("write by [...], then count, within and for <amount> from <amount> below <amount>, in that order"),{...this.record(n),span:this.span(t)}}next(t){return this.tokens[Math.min(this.index+t,this.tokens.length-1)]}nameNode(t,n=this.peek().span){return{kind:"name",value:t,span:n}}send(){let t=this.peek().span.start;this.take();let n=this.peek().span,r=this.peek().kind==="string"?this.text():this.identifier().toUpperCase();this.expect("via");let a=this.peek().span,i=this.identifier(),s=this.block();return{key:"send",value:this.record({adapter:this.nameNode(i,a),kind:{kind:"text",value:r,span:n},fields:{...s,entries:s.entries.map(o=>({...o,value:this.clauseValue(o.value)}))}}),span:this.span(t)}}readBill(){let t=this.peek().span.start;this.take();let n=this.peek().span;this.take(),this.expect("via");let r=this.peek().span,a=this.identifier(),i=this.block();this.expect("sets");let s=this.block();return{key:"read",value:this.record({adapter:this.nameNode(a,r),operation:{kind:"text",value:"bill.enquire",span:n},fields:{...i,entries:i.entries.map(o=>({...o,value:this.clauseValue(o.value)}))},sets:s}),span:this.span(t)}}nativeClause(){if(this.at("let")&&this.next(1).kind==="name"&&this.next(2).text==="=")return"calculate";if(this.at("then")&&this.next(1).kind==="name")return"invoke";if(this.peek().kind==="name"&&this.next(1).text==="=")return"set"}clauseValue(t,n=new Set){if(t.kind==="block")return t;if(t.kind==="name"&&t.value==="now")return this.record({field:{...t,value:"self.now"}});let r=t.kind==="name"&&(/^(self|input|party|subject)\./.test(t.value)||t.value==="actor"||n.has(t.value));return this.record({[r?"field":"literal"]:t})}values(t,n,r){return{kind:"list",items:t.map(a=>this.clauseValue(a,r)),span:n}}escape(){let t=this.take().span.start,n=this.block();for(let r of n.entries)Cq.has(r.key)||this.fail(`udl takes calculate, invoke or set, not ${r.key}`,"move this clause out of udl { }",r.span);return this.warnings.push({code:"udl_escape",message:"udl { } writes raw UDL clauses that HSX does not check by name or type",fix:"write let, then or field = value instead",span:this.span(t)}),n.entries}assignment(){let t=this.peek().span.start,n=this.identifier();this.expect("=");let r=this.arithmetic();return this.guarded()?{key:n,value:this.chosen(r,this.nameNode(`self.${n}`),t),span:this.span(t)}:{key:n,value:r,span:this.span(t)}}calculation(){let t=this.take().span.start,n=this.nameNode(this.peek().text);this.take(),this.expect("=");let r=this.computed(n);return{...this.record({target:n,...r}),span:this.span(t)}}computed(t){let n=p=>this.nameNode(p);if(this.at("count")&&this.next(1).text==="of")return this.take(),this.take(),{op:n("aggregate"),selection:this.block(),measure:n("count")};if(this.at("sum")&&this.next(1).text!=="("){this.take();let p=this.peek();p.kind!=="string"&&p.kind!=="name"&&this.fail("expected the field to sum",'write sum "amount" of { ... }'),this.take(),this.expect("of");let u=p.kind==="string"?JSON.parse(p.text):p.text;return{op:n("aggregate"),selection:this.block(),measure:this.record({sum:{kind:"text",value:u,span:p.span}})}}if(this.at("rate_of")&&this.next(1).text==="(")return this.rateOf();if(this.peek().kind==="name"&&this.next(1).text==="("&&!tv.has(this.peek().text))return this.computedCall(this.atom());let r=this.peek().span.start,a=this.arithmetic();if((this.at("workdays")||this.at("businessDays"))&&this.fail(`${this.peek().text} is not a unit`,"write now + 5 banking days, counted on the tenant's banking calendar"),this.at("banking")){let[p,u]=this.pair(a,["sum"]);return(!p||!u)&&this.fail("banking days count forward from one date","write now + 5 banking days or self.presentedAt + examination banking days",a.span),this.take(),!this.eat("days")&&!this.eat("day")&&this.fail("expected days after banking","write + 5 banking days"),{op:n("banking"),date:p,days:u}}if(this.at("rolled")){this.take();for(let p of["to","the","next","banking","day"])this.expect(p);return this.leaf(a)||this.fail("rolled to the next banking day rolls one date","write self.maturesAt rolled to the next banking day",a.span),{op:n("banking"),date:a,days:this.record({literal:{kind:"number",value:"0",span:a.span}})}}let[i,s]=this.pair(a,["sum","subtract"]),o=s&&this.leaf(s),d=/^([1-9]\d{0,3}) ?(month|year)s?$/.exec(o?.kind==="duration"?o.value:"");if(i&&s&&d){this.part(a,"op")?.value!=="sum"&&this.fail("a calendar period only steps forward",`write the date + ${d[0]}`,a.span);let p=o.span;return{op:n("step"),date:i,period:this.record({literal:{kind:"text",value:`P${d[1]}${d[2]==="month"?"M":"Y"}`,span:p}}),times:this.record({literal:{kind:"number",value:"1",span:p}})}}return i&&s&&(this.leaf(i)?.value==="self.now"||this.leaf(s)?.kind==="duration")?{op:n("shift"),date:i,milliseconds:s,direction:n(this.part(a,"op")?.value==="sum"?"after":"before")}:(this.guarded()&&(a=this.chosen(a,this.nameNode(`self.${"value"in t?String(t.value):""}`,t.span),r)),this.rounded(a,"write round: on a let with /, rate, ratio or divide"),this.part(a,"op")?Object.fromEntries(a.entries.map(p=>[p.key,p.value])):{op:n("sum"),values:this.values([a],a.span)})}rounded(t,n){if(!(this.at("round")&&this.next(1).text===":")){this.rounds(t,void 0);return}let r=this.peek().span;this.take(),this.take(),this.rounds(t,this.atom())||this.fail("round: needs a quotient to round",n,r)}amount(t=new Set){let n=this.arithmetic(t);return this.rounded(n,"write round: after an amount with /, rate, ratio or divide"),n}leaf(t){let[n,...r]=t.entries;return!r.length&&(n?.key==="field"||n?.key==="literal")&&"value"in n.value&&typeof n.value.value=="string"?n.value:void 0}part(t,n){let r=t.entries.find(a=>a.key===n)?.value;return r&&"value"in r&&typeof r.value=="string"?r:void 0}pair(t,n){let r=this.part(t,"op")?.value;if(!r||!n.includes(r))return[];let a=t.entries.flatMap(o=>o.key==="op"?[]:o.value.kind==="list"?o.value.items:[o.value]),[i,s]=a;return a.length===2&&i&&s&&a.every(o=>this.leaf(o))?[i,s]:[]}rounds(t,n){if(t.kind==="list")return t.items.map(s=>this.rounds(s,n)).some(Boolean);if(t.kind!=="block")return!1;let r=!1;for(let s of t.entries)s.key!=="when"&&this.rounds(s.value,n)&&(r=!0);let a=this.part(t,"op")?.value??"";if((Nq.has(a)||a==="multiply"&&n)&&!t.entries.some(s=>s.key==="rounding")){let s=n??this.nameNode("floor",t.span);t.entries.push({key:"rounding",value:s,span:s.span}),n&&(r=!0)}return r}chosen(t,n,r){this.expect("when");let a=this.condition(),i=this.eat("otherwise")?this.arithmetic():this.record({field:n});return{...this.record({op:this.nameNode("choose"),when:a,then:t,otherwise:i}),span:this.span(r)}}bounded(t){let n=this.peek().span.start;this.reading++;let r;try{r=t()}finally{this.reading--}let a=this.reading===0?_y(r):0;return a>nv&&this.fail(`expression nests ${a} operators, past ${nv}`,"split the expression into let lines",this.span(n),"nesting_too_deep"),r}nest(){++this.depth>32&&this.fail("expression nesting exceeds 32","split the expression into let lines",this.peek().span,"nesting_too_deep")}condition(t=new Set){return this.bounded(()=>this.junction("any","or",()=>this.junction("all","and",()=>this.unary(t))))}junction(t,n,r){let a=this.peek().span.start,i=r();if(!this.at(n))return i;let s=[i];for(;this.eat(n);)s.push(r());return s.length>32&&this.fail(`a condition joins at most 32 parts with ${n}`,"split the rule into two requires lines",this.span(a)),{...this.record({kind:this.kindNode(t),of:{kind:"list",items:s,span:this.span(a)}}),span:this.span(a)}}unary(t){let n=this.peek().span.start;this.nest();let r;if(this.eat("not"))r=this.record({kind:this.kindNode("not"),condition:this.unary(t)});else if(this.at("(")){let[a,i]=[this.index,this.depth];try{this.take();let s=this.condition(t);this.expect(")");let o=this.peek().text;!Eq.has(o)&&!Hq.includes(o)&&o!=="in"&&(r=s)}catch(s){if(!(s instanceof Ni))throw s}r||([this.index,this.depth]=[a,i])}return r??=this.comparison(t),this.depth--,{...r,span:this.span(n)}}comparison(t){let n=this.arithmetic(t);if(this.eat("in")){let a=n.entries.find(i=>i.key==="field")?.value;return a||this.fail("x in [..] needs a field on the left","write requires self.record in [state]"),this.record({kind:this.kindNode("state"),reference:a,states:this.atom()})}let r=this.operator();return this.record({kind:this.kindNode("compare"),left:n,operator:r,right:this.arithmetic(t)})}kindNode(t){return this.guarding?this.nameNode(t):this.node(t)}arithmetic(t=new Set){return this.bounded(()=>{let n=this.peek().span.start;this.nest();let r,a=[this.term(t)];for(;this.at("+")||this.at("-");){let i=this.take().text==="+"?"sum":"subtract";r&&r!==i&&(a=[this.run(r,a,n)]),r=i,a.push(this.term(t))}return this.depth--,r?this.run(r,a,n):a[0]})}run(t,n,r){let a=this.span(r),[i,...s]=n;return{...t==="sum"?this.record({op:this.nameNode("sum"),values:{kind:"list",items:n,span:a}}):this.record({op:this.nameNode("subtract"),base:i,subtract:{kind:"list",items:s,span:a}}),span:a}}term(t){let n=this.peek().span.start,r=this.factor(t);for(;this.at("*")||this.at("/");){let a=this.take().text==="*",i=this.factor(t),s=[r,i].findIndex(o=>this.leaf(o)?.kind==="percent");r={...a&&s>=0?this.record({op:this.nameNode("rate"),base:s===0?i:r,bps:s===0?r:i}):a?this.record({op:this.nameNode("multiply"),amount:r,units:i}):this.record({op:this.nameNode("divide"),amount:r,divisor:i}),span:this.span(n)}}return r}factor(t){if(this.eat("(")){let r=this.arithmetic(t);return this.expect(")"),r}if(this.peek().kind==="name"&&this.next(1).text==="("&&tv.has(this.peek().text))return this.operatorCall(t);if((this.at("days")||this.at("months"))&&this.next(1).text==="between"&&this.next(2).text==="(")return this.operatorCall(t);let n=this.atom();return this.guarding&&n.kind==="text"&&this.fail(`a guard compares numbers, money, dates or fields, and ${JSON.stringify(n.value)} is text`,"write an amount such as 0 SAR, a number or a field",n.span,"guard_operand_text"),this.clauseValue(n,t)}operatorCall(t){let n=this.peek().span.start,r=this.take().text;this.eat("between")&&(r+=" between"),this.expect("(");let a=[],i,s;for(;!this.eat(")");){if(this.peek().kind==="eof"&&this.fail("unclosed call","add )"),this.at("basis")&&this.next(1).text===":")r!=="rate"&&this.fail(`${r} takes no day-count basis`,"write basis: only on rate(base, percent, to - from, basis: actual/365)"),s&&this.fail("basis is already set","write basis: once"),s=this.basis();else if(this.at("round")&&this.next(1).text===":"){let p=this.peek().span.start;ev.has(r)||this.fail(`${r} does not round`,"write round: only on rate, ratio, divide, compound, days between or months between"),i&&this.fail("round is already set","write round: once"),this.take(),this.take(),i={...this.atom(),span:this.span(p)}}else a.push(this.arithmetic(t));this.separators()}let o={kind:"call",name:r,args:a,...i?{round:i}:{},span:this.span(n)},d=this.computedCall(o,p=>a[p],s);return{...this.record(d),span:o.span}}basis(){this.expect("basis"),this.expect(":");let t=this.peek().span.start,n="";for(;!this.at(",")&&!this.at(")")&&this.peek().kind!=="eof";)n+=this.take().text;return Rq.has(n)||this.fail(`unknown day-count basis ${JSON.stringify(n)}`,"write basis: actual/365, basis: actual/360 or basis: 30/360",this.span(t)),this.nameNode(n,this.span(t))}rateOf(){let t=this.take().span.start;this.expect("(");let n=this.clauseValue(this.atom());this.expect("at");let r=this.clauseValue(this.atom());this.expect(",");let a=u=>{let m=this.peek();return m.kind!=="string"&&m.kind!=="name"&&this.fail(`expected the payment's ${u} field`,'write "payment" at "dueAt" of { ... }'),this.take(),{kind:"text",value:m.kind==="string"?JSON.parse(m.text):m.text,span:m.span}},i=a("amount");this.expect("at");let s=a("date");this.expect("of");let o=this.block();this.expect(",");let d=this.basis();this.expect(")");let p=this.span(t);return this.eat("otherwise")||this.fail("rate_of names no otherwise: flows with no single sign change, or a rate past 100%, have no rate","write rate_of(...) otherwise 0%, or otherwise a percent tunable",p,"rate_of_unhandled"),{op:this.nameNode("rate_of",p),advance:this.record({amount:n,date:r}),selection:o,payment:this.record({amount:i,date:s}),basis:d,otherwise:this.clauseValue(this.atom())}}computedCall(t,n=a=>this.clauseValue(t.args[a]),r){let a=o=>this.nameNode(o,t.span),i=(o,d)=>{t.args.length!==o&&this.fail(`${t.name} takes ${o} operands`,`write ${d}`,t.span,"unknown_calculation")},s=t.round?{rounding:t.round}:{};switch(t.name){case"sum":case"minimum":case"maximum":return t.args.length||i(1,`${t.name}(value, ...)`),{op:a(t.name),values:{kind:"list",items:t.args.map((o,d)=>n(d)),span:t.span}};case"subtract":return t.args.length<2&&i(2,"subtract(base, value, ...)"),{op:a("subtract"),base:n(0),subtract:{kind:"list",items:t.args.slice(1).map((o,d)=>n(d+1)),span:t.span}};case"multiply":return i(2,"multiply(amount, units)"),{op:a("multiply"),amount:n(0),units:n(1)};case"divide":return i(2,"divide(amount, divisor)"),{op:a("divide"),amount:n(0),divisor:n(1),...s};case"rate":{if(t.args.length!==3||!r)return(r||t.args.length===3)&&this.fail("a rate over a period names its day count","write rate(base, percent, to - from, basis: actual/365)",t.span,"unknown_calculation"),i(2,"rate(base, percent)"),{op:a("rate"),base:n(0),bps:n(1),...s};let o=n(2),[d,p]=this.pair(o,["subtract"]);return(!d||!p)&&this.fail("a rate's period is one date minus another","write rate(base, percent, self.endsAt - self.startsAt, basis: actual/365)",o.span,"unknown_calculation"),{op:a("rate"),base:n(0),bps:n(1),days:this.record({from:p,to:d,basis:r}),...s}}case"compound":return i(3,"compound(amount, rate, periods)"),{op:a("compound"),amount:n(0),rate:n(1),periods:n(2),...s};case"days between":case"months between":return i(2,`${t.name}(from, to)`),{op:a("between"),from:n(0),to:n(1),unit:a(t.name.split(" ")[0]),...s};case"ratio":return i(3,"ratio(amount, numerator, denominator)"),{op:a("ratio"),amount:n(0),numerator:n(1),denominator:n(2),...s};case"annuity":return i(5,"annuity(amount, rate, periods, position, principal)"),{op:a("annuity"),amount:n(0),rate:n(1),periods:n(2),position:n(3),part:t.args[4]};case"at":return i(2,"at(list, position)"),{op:a("at"),list:t.args[0],position:n(1)};case"before":case"after":return t.name==="after"&&t.args.length===3?{op:a("step"),date:n(0),period:n(1),times:n(2)}:(i(2,`${t.name}(date, duration)`),{op:a("shift"),date:n(0),milliseconds:n(1),direction:a(t.name)});default:return this.fail(`unknown calculation ${t.name}`,"use sum, minimum, maximum, subtract, multiply, divide, rate, ratio, compound, days between, months between, annuity, at, before, after or rate_of",t.span,"unknown_calculation")}}invocation(){let t=this.take().span.start,n={},r=new Set,a=this.nameNode(this.peek().text);if(this.take(),a.kind==="name"&&a.value==="create"&&!this.at("on")){let s=this.atom();if(this.at("times")){this.take();let o=this.clauseValue(this.atom());this.eat("max")||this.fail("a repeated create needs its maximum","write times n max 366 as position");let d=this.atom();this.expect("as");let p=this.nameNode(this.peek().text);this.identifier(),r.add(p.kind==="name"?p.value:""),n.range=this.record({count:o,maximum:d,bind:p})}n.instrument=s}else if(this.eat("on"))if(this.at("each")&&this.next(1).text==="{")this.take(),n.selection=this.block();else{let s=this.peek().span;n.reference=this.nameNode(this.path(),{start:s.start,end:this.span(s.start).end})}else n.reference=this.nameNode("self.id",a.span);n.action=a;let i={kind:"block",entries:[],span:a.span};if(this.eat("with")){let s=this.peek().span.start;this.expect("{");let o=[];for(;!this.eat("}")&&(this.separators(),!this.eat("}"));){this.peek().kind==="eof"&&this.fail("unclosed with, expected }","add }");let d=this.peek().span.start,p=this.path();this.expect(":"),o.push({key:p,value:this.amount(r),span:this.span(d)}),this.separators()}i={kind:"block",entries:o,span:this.span(s)}}if(this.guarded()){this.take(),this.guarding=!0;try{n.guard=this.condition(r)}finally{this.guarding=!1}}return n.input=i,{...this.record(n),span:this.span(t)}}guarded(){return this.at("when")&&!(this.next(1).kind==="name"&&["is","has"].includes(this.next(2).text))}move(){let t={};if(this.at("post")||this.at("void"))t.operation=this.node("internal_transfer."+this.take().text),t.transfer=this.atom();else{this.eat("reserve")&&(t.operation=this.node("internal_transfer.reserve"));let n=this.amount(),[r,...a]=n.entries;t.amount=!a.length&&(r?.key==="field"||r?.key==="literal")?r.value:n,this.expect("from"),t.from=this.atom(),this.eat("to")?t.to=this.atom():(this.expect("shares"),t.shares=this.atom())}for(let n of["fee","capture","key"])this.eat(n)&&(t[n]=this.atom());if(this.eat("economics")){let{span:n}=this.peek();t.economics=this.at("{")?this.block():{kind:"name",value:this.identifier(),span:n}}return this.eat("boundary")&&(t.boundary=this.at("{")?this.block():this.record({adapter:this.atom(),...this.eat("items")?{items:this.block()}:{}})),this.record(t)}block(t=!1,n=!1){let r=this.peek().span.start;this.expect("{"),++this.depth>32&&this.fail("block nesting exceeds 32","reduce nested blocks",this.peek().span,"nesting_too_deep");let a=this.entries("}",t,n);return this.depth--,{kind:"block",entries:a,span:this.span(r)}}expression(){++this.depth>32&&this.fail("expression nesting exceeds 32","reduce nested values",this.peek().span,"nesting_too_deep");let t=this.peek().span.start,n=this.atom();return this.at("cap")&&this.tokens[this.index+1]?.text!==":"&&(this.take(),n={kind:"capped",rate:n,cap:this.atom(),span:this.span(t)}),this.eat("=")&&(n={kind:"default",type:n,value:this.expression(),span:this.span(t)}),this.depth--,n}atom(){let t=this.peek(),n=t.span.start;if(this.at("{"))return this.block();if(this.eat("[")){let p=[];for(;!this.eat("]");)this.peek().kind==="eof"&&this.fail("unclosed list","add ]"),p.push(this.expression()),this.separators();return{kind:"list",items:p,span:this.span(n)}}if(t.kind==="number"){if(this.take(),t.text.endsWith("%"))return{kind:"percent",value:t.text.slice(0,-1),span:t.span};if(/[a-z]$/.test(t.text))return{kind:"duration",value:t.text,span:t.span};if(/^(?:minute|hour|day|week|month|year)s?$/.test(this.peek().text)&&this.peek().kind==="name"&&this.tokens[this.index+1]?.text!==":"){let p=this.take().text;return{kind:"duration",value:`${t.text} ${p}`,span:this.span(n)}}if(/^[A-Z]{3}$/.test(this.peek().text)){let p=this.take().text;return{kind:"money",value:t.text+" "+p,span:this.span(n)}}return{kind:"number",value:t.text,span:t.span}}if(t.kind==="string"||t.kind==="date")return this.take(),{kind:t.kind==="string"?"text":"date",value:t.kind==="string"?JSON.parse(t.text):t.text,span:t.span};let r=this.path();if(this.eat("(")){let p=[],u;for(;!this.eat(")");){if(this.at("round")&&this.tokens[this.index+1]?.text===":"){let l=this.peek().span.start;ev.has(r)||this.fail(`${r} does not round`,"write round: only on rate, ratio or divide"),u&&this.fail("round is already set","write round: once"),this.take(),this.take(),u={...this.atom(),span:this.span(l)}}else p.push(this.expression());this.separators()}let m=this.currency(r),c=this.eat("?");return{kind:"call",name:r,args:p,...u?{round:u}:{},...m?{currency:m}:{},...c?{optional:c}:{},span:this.span(n)}}let a,i;["ref","list","digest"].includes(r)&&this.eat("<")&&(a=this.path(),this.expect(">"));let s=r==="ref"&&this.eat("[");s&&this.expect("]"),this.eat("of")&&(i=this.path());let o=this.currency(r),d=this.eat("?");return a||i||o||d||s?{kind:"type",name:r,...a?{target:a}:{},...i?{owner:i}:{},...o?{currency:o}:{},optional:d,...s?{many:!0}:{},span:this.span(n)}:{kind:"name",value:r,span:this.span(n)}}currency(t){let n=this.tokens[this.index+1];if(!(t!=="money"&&t!=="account"||!this.at("in")||n?.kind!=="name"||!/^[A-Z]{3}$/.test(n.text)))return this.take(),this.take().text}}});function ai(e,t){let n=ar(e);if(n.diagnostics.length)throw new St({...n.diagnostics[0],source:t});let r=n.program,a=d=>{if(!(!d||typeof d!="object")){"span"in d&&Object.assign(d,{source:t});for(let p of Object.values(d))a(p)}};a(r);let i=t.slice(t.indexOf(".")+1);(!r.header||r.name!==i)&&U(r,`${t}: expected header ${i}`,`start with header ${i}`);let s=new Map([[t,e]]),o=new Map;for(let d of r.decls){if(d.kind!=="instrument")continue;let p=o.get(d.name);p&&Bn(s,`instrument ${t}.${d.name} is declared twice`,p,d,"give each instrument a distinct name"),o.set(d.name,d);let u=new Map;for(let m of d.parameters){let c=u.get(m.key);c&&Bn(s,`parameter ${m.key} is declared twice`,c,m,"declare each parameter once"),u.set(m.key,m);let l=m.value.kind==="default"?m.value.type:m.value;l.kind==="call"&&!["enum","integer"].includes(l.name)&&U(l,`unsupported tunable constructor ${l.name}`,"Only enum(choices) and integer(minimum, maximum) are supported tunable constructors. This constructor's restrictions cannot be enforced.","field_type_invalid")}}return r}function wc(e){let t=r=>{let a=r?.kind==="name"?e.parameters.find(i=>i.key===r.value):void 0;return a||U(r??e,`a check of ${e.name} names a tunable it does not declare`,`name one of ${e.parameters.map(i=>i.key).join(", ")}`,"header_check_invalid"),a},n=r=>{let[a]=r?.kind==="block"?r.entries:[],i=a?.key==="sum"&&a.value.kind==="list"?a.value.items:a?.key==="literal"?[a.value]:U(a?.value??e,"a check compares tunables and literals","name a tunable or write a literal","header_check_invalid");for(let s of i)s.kind==="name"&&t(s);return i};return e.body.entries.filter(r=>r.key==="checks").flatMap(r=>r.value.kind==="block"?r.value.entries:U(r,"checks needs a block","write checks { rule { message, fix } }","header_check_invalid")).map(r=>{let a=$c(r.value),i=a.get("rule"),s=$c(i),o=$c(a.get("explain")),d=o.get("message"),p=o.get("fix");(o.size!==2||d?.kind!=="text"||p?.kind!=="text")&&U(r,"a check needs a message and a fix",'write { message: "...", fix: "..." } after the rule',"header_check_invalid");let u=s.get("kind"),m;if(u?.kind==="text"&&u.value==="compare")m={kind:"compare",left:n(s.get("left")),operator:s.get("operator").value,right:n(s.get("right"))};else if(u?.kind==="text"&&u.value==="is"){let y=t(s.get("tunable")),h=s.get("is"),b=av(y),A=b.kind==="type"||b.kind==="call"?b.name:b.kind==="name"?b.value:"";(h?.kind!=="name"||h.value!=="set"&&h.value!==A)&&U(h??r,`${y.key} is ${A}, so its check reads ${y.key} is set or ${y.key} is ${A}`,`write ${y.key} is set, or ${y.key} is ${A} to explain its type rule`,"header_check_invalid"),m={kind:h.value==="set"?"set":"type",tunable:y.key}}else U(i,"a check is a comparison, x is set, or x is its type","write a < b, a + b <= c, x is set or x is money","header_check_invalid");let c=$c(a.get("when")),l;if(a.has("when")){let y=t(c.get("selector")),h=c.get("is"),b=av(y),A=(b.kind==="type"||b.kind==="call")&&b.name!=="enum"&&!!b.optional&&h?.kind==="name"&&["set","unset"].includes(h.value),Z=b.kind==="call"&&b.name==="enum"&&b.args.some(k=>k.kind==="name"&&h?.kind==="name"&&k.value===h.value);(!A&&!Z||h?.kind!=="name"||m.kind==="type")&&U(a.get("when"),"when must select a declared enum choice, or set or unset of an optional tunable","write when kind is <choice>, or when every is unset","header_check_invalid"),l={selector:y.key,is:h.value}}return{rule:i,test:m,...l?{when:l}:{},message:d.value,fix:p.value,span:r.span,..."source"in r?{source:r.source}:{}}})}var $c,av,Ls=ve(()=>{"use strict";ka();Er();$c=e=>new Map(e?.kind==="block"?e.entries.map(t=>[t.key,t.value]):[]),av=e=>e.value.kind==="default"?e.value.type:e.value});function sv(e,t){if(t.startsWith("party."))return{party:t.slice(6)};let n=/^self\.([A-Za-z_][A-Za-z0-9_]*)$/.exec(t)?.[1],r=n?e.fields.find(a=>a.name===n):void 0;if(!(r?.type!=="account"||typeof r.owner!="string"))return r.owner==="self"?{holding:n}:{party:r.owner}}function Bq(e,t){if("from"in t)return{from:t.from,to:t.to};if(t.operation==="internal_transfer.post"){for(let n of Object.values(e.actions))for(let r of n.moves)if(r.operation==="internal_transfer.reserve"&&`self.${r.capture}`===t.transfer)return{from:r.from,to:r.to}}}function by(e,t){return e.due!==void 0&&e.follows===void 0&&!t.exposed&&!t.invoked&&!e.input.length&&!e.subject?.requirements.length&&!e.subject?.adapters.length}function xy(e,t,n,r,a){if(n.follows!==void 0)return{actor:"caller"};if(a.invoked&&!a.exposed)return{actor:"caller"};if(by(n,a))return{actor:"clock"};let i=new Set;for(let o of n.moves){let d=Bq(e,o);if(!d)continue;let p=sv(e,d.from);if(!p||!("party"in p))continue;let u=sv(e,d.to);u&&"party"in u&&u.party===p.party||i.add(p.party)}if(i.size>1)return{spenders:[...i].sort()};let[s]=i;if(s)return{actor:{party:s}};if(n.due)return{actor:{party:iv}};if(t==="create"){let o=new Set(Object.values(r??{}).flatMap(d=>"role"in d?[d.role]:[]));if(o.has("actor"))return{actor:{party:"actor"}};if(o.has("owner"))return{actor:{party:"owner"}}}return{actor:{party:iv}}}var iv,ov=ve(()=>{"use strict";iv="programOperator"});function $y(e){let t=cv(e);return t.kind==="name"?t.value==="party":(t.kind==="type"||t.kind==="call")&&t.name==="party"}function Kq(e){let t=e.body.entries.find(n=>n.key==="action create")?.value;return wy(Yo(Yo(t,"actor"),"party"))}function Ic(e,t,n){if(e&&(e.kind==="list"&&e.items.forEach(r=>Ic(r,t,n)),e.kind==="block"))for(let r of e.entries)if(r.key==="moves"){let a=r.value.kind==="list"?r.value.items:[r.value];for(let i of a){let s=wy(Yo(i,"from"))?.replace(/^self\./,"");s&&t.has(s)&&n.add(s)}}else Ic(r.value,t,n)}function Xq(e,t){let n=new Set,r=a=>{for(let i of a)if(i.key.startsWith("action "))Ic(i.value,t,n);else if(i.key==="records"&&i.value.kind==="block")for(let s of i.value.entries)s.value.kind==="block"&&r(s.value.entries)};return r(e.body.entries),n}function dv(e){let t=Kq(e);if(t)return{party:t};let n=e.body.entries.find(a=>a.key==="action create")?.value;if(Yo(n,"actor"))return;let r=new Set;return Ic(n,new Set(e.parameters.filter($y).map(a=>a.key)),r),r.size===1?{party:[...r][0]}:r.size||Yo(n,"due")?void 0:"actor"}function Vq(e){let t=pv.get(e);if(t)return t;t=new Set;for(let[n,r]of e)for(let a of ai(r,n).decls){if(a.kind!=="instrument")continue;let i=a.parameters.filter($y).map(s=>s.key);for(let s of i)for(let o of i)s!==o&&t.add(`${s} ${o}`)}return pv.set(e,t),t}function uv(e,t,n,r,a,i){let s=[],o=new Map;for(let y of e){let h=y.template.parameters.filter($y),b=[];for(let q of h){let R=y.rows.find(x=>x.key===q.key),H=wy(R?.value);(H===vy||H==="owner"||H==="actor"||!R&&Fq(q)&&!Uq(q)&&!i(q.key))&&b.push({key:q.key,row:R,written:H==="owner"||H==="actor"?H:void 0,expected:void 0,reason:""})}if(b.length>2){s.push({code:"customer_binding_rule",message:`${y.name} binds ${b.length} customers: ${b.map(q=>q.key).join(", ")}. An agreement has two customer sides, the record's owner and the customer who starts it.`,fix:"Bind a declared business or operator for every other party.",span:y.entry.span});continue}let A=y.exposed.get("create"),Z=A!==void 0&&t.has(A),k=new Set(b.map(q=>q.key)),f=[...Xq(y.template,k)],z=dv(y.template),P=typeof z=="object"?z.party:void 0,T=P&&k.has(P)?P:b.length===2&&f.length===1?f[0]:void 0,$=z==="actor"?b.length===1?b[0].key:T:P;for(let q of b)if(Z)q.expected=q.key===$?"actor":"owner",q.reason=q.key===$?`Entry action ${A} lets ${q.key} start ${y.name} on a record they do not own`:`Entry action ${A} starts ${y.name} for ${$??"another customer"}`;else if(b.length===2){if(!T){let R=b.find(H=>H!==q);q.written||(q.expected=R.written?R.written==="actor"?"owner":"actor":q===b[0]?"actor":"owner");continue}q.expected=q.key===T?"actor":"owner",q.reason=T===P?`In ${y.name}, create runs for ${T}`:`In ${y.name}, ${T} is the customer who pays in`}o.set(y,b)}let d=new Map;for(let[y,h]of o)h.length===1&&!h[0].expected&&!h[0].written&&(h[0].expected=n?"actor":"owner",!n&&!d.has(h[0].key)&&d.set(h[0].key,y));let p=Vq(a),u=[...d.keys()],m=u.find((y,h)=>u.slice(0,h).some(b=>p.has(`${b} ${y}`)));if(m){let y=u.find(Z=>p.has(`${Z} ${m}`)),[h,b]=[y,m].map(Z=>({key:Z,site:d.get(Z)})),A=[h.site,b.site].flatMap(Z=>{let k=Z.exposed.get("create");return k?[k]:[]});s.push({code:"customer_binding_rule",message:`${r}: ${h.key} on ${h.site.name} and ${b.key} on ${b.site.name} are customers no rule places, so both would bind owner and one person would take both sides of the money.`,fix:`List in entryActions the create of the attachment the non-owner starts${A.length?` (${A.join(" or ")})`:", exposing it first"}, so that customer binds actor. If the company owns ${r}, mark it \`belongs_to: company\` instead.`,span:b.site.entry.span})}let c=new Map,l=[];for(let[y,h]of o){let b=[...y.rows],A=y.exposed.get("create"),Z=dv(y.template);A&&h.some(k=>!k.written&&k.expected==="actor"&&(Z==="actor"||typeof Z=="object"&&k.key===Z.party))&&l.push(A);for(let k of h){let f=k.row?.value.span??y.entry.span;if(k.written){if(!k.expected||k.written===k.expected)continue;s.push({code:"customer_binding_rule",message:`${y.name}: \`${k.key}: ${k.written}\` breaks the binding rule. ${k.reason}, so ${k.key} ${k.expected==="actor"?"starts it and binds actor":"owns the record and binds owner"}.`,fix:`Write \`${k.key}: customer\`; the compiler places it on ${k.expected}.`,span:f});continue}if(!k.expected)continue;let z={kind:"name",value:k.expected,span:f};k.row?b[b.indexOf(k.row)]={...k.row,value:z}:b.push({key:k.key,value:z,span:f})}c.set(y,b)}return{rows:c,entryActions:l,diagnostics:s}}var vy,cv,Uq,Fq,wy,Yo,pv,lv=ve(()=>{"use strict";Ls();vy="customer",cv=e=>e.value.kind==="default"?e.value.type:e.value;Uq=e=>{let t=cv(e);return(t.kind==="type"||t.kind==="call")&&!!t.optional},Fq=e=>e.value.kind==="default"&&e.value.value.kind==="call"&&e.value.value.name==="party"&&e.value.value.args.length===1&&e.value.value.args[0].kind==="name"&&e.value.value.args[0].value==="person",wy=e=>e?.kind==="name"?e.value:void 0,Yo=(e,t)=>e?.kind==="block"?e.entries.find(n=>n.key===t)?.value:void 0;pv=new WeakMap});function Go(e,t,n){if(Array.isArray(e))return e.map(i=>Go(i,t,n));if(!e||typeof e!="object")return e;let r=e,a=typeof r.key=="string"&&zc.test(r.key)?"value":r.kind==="assignment"?"body":void 0;return Object.fromEntries(Object.entries(e).map(([i,s])=>[i,i==="span"?{...t}:i===a&&s.kind==="block"?Jo(s.entries.map(o=>mv(o,t,n)),{...t}):Go(s,t,n)]))}function mv(e,t,n){return e.key==="expose"?Go(e,t,n):{key:e.key,value:zy(e.value,n),span:{...t}}}function zy(e,t){if(Array.isArray(e))return e.map(r=>zy(r,t));if(!e||typeof e!="object")return e;let n=Object.fromEntries(Object.entries(e).map(([r,a])=>[r,zy(a,t)]));return"span"in n?{...n,source:t}:n}function Jq(e,t,n){let r=ky.get(e);if(r)return r;let a=ar(e),i=a.diagnostics[0];return i&&je(t,i.code,`base ${n} does not parse: ${i.message}`,"fix the base, or amend another one"),a.program.amends&&je(t,"amends_target_invalid",`base ${n} amends ${a.program.amends.name}, and a base must be written in full`,"amend a base that does not amend another"),ky.set(e,a.program),a.program}function yv(e,t,n){let r=[];if(!e.amends){for(let f of e.decls)ot(r,()=>{(f.kind==="hide"||f.kind==="object"&&f.amends)&&je(f.kind==="object"?f.amends:f,"amend_without_base",f.kind==="hide"?`hide ${f.target} needs a base to drop it from`:`object ${f.name} amends ${f.amends.name}, and the program amends no base`,'write program <name> "<Title>" amends <base>.programme')});return r.length?{ok:!1,diagnostics:r}:{ok:!0,program:e}}let a=e.amends,i=t.get(a.name);if(i===void 0)return{ok:!1,diagnostics:[{code:"unknown_base",message:`unknown base ${a.name}.${en(a.name,[...t.keys()])}`,fix:`amend one of ${[...t.keys()].join(", ")}`,span:a.span}]};let s;try{s=Jq(i,a,a.name)}catch(f){if(!(f instanceof St))throw f;return{ok:!1,diagnostics:[f.diagnostic]}}let o={name:a.name,digest:Qr(i)},d=kc(o),p=f=>Go(f,a.span,d),u=s.decls.flatMap(f=>f.kind==="party"?[f]:[]),m=new Set;for(let f of e.decls)ot(r,()=>{f.kind==="expose"&&je(f,"expose_in_amendment",`expose ${f.target} in an amendment; its object's names table exposes actions`,`write names { ${f.target.split(".").slice(1,-1).join(".")} { ${f.target.split(".").at(-1)}: ${f.name} } } in object ${f.target.split(".")[0]}`),f.kind==="hide"&&(u.some(z=>z.name===f.target)||je(f,"amend_unknown_name",`base ${a.name} declares no party ${f.target}.${en(f.target,u.map(z=>z.name))}`,"hide a party the base declares, or hide an exposure inside the object that amends it"),m.add(f.target))});let c=new Map(s.decls.flatMap(f=>f.kind==="object"?[[f.name,f]]:[])),l=new Map;for(let f of e.decls)ot(r,()=>{if(f.kind!=="object"||!f.amends)return;let z=f.amends.name;c.has(z)||je(f.amends,"amend_unknown_name",`base ${a.name} declares no object ${z}.${en(z,[...c.keys()])}`,`amend one of ${[...c.keys()].join(", ")}`);let P=l.get(z);P&&je(f.amends,"amended_twice",`objects ${P.name} and ${f.name} both amend ${z}`,`amend ${z} once, and attach what the second adds there`),l.set(z,f)});if(r.length)return{ok:!1,diagnostics:r};let y=new Map,h=[];for(let f of s.decls){if(f.kind!=="expose")continue;let[z,...P]=f.target.split(".");if(!l.has(z)){h.push(p(f));continue}let T=y.get(z)??[];T.push({key:P.join("."),name:f.name,program:!0}),y.set(z,T)}let b=new Map;for(let[f,z]of l){let P=ot(r,()=>eL(c.get(f),z,y.get(f)??[],m,n,a.name,d,r));P&&b.set(z,P)}if(r.length)return{ok:!1,diagnostics:r};let A=[];for(let f of s.decls)f.kind!=="expose"&&(f.kind==="party"&&m.has(f.name)||f.kind==="object"&&l.has(f.name)||A.push(p(f)));let Z=[...h];for(let f of e.decls){if(f.kind==="hide")continue;let z=f.kind==="object"?b.get(f):void 0;if(!z){A.push(f);continue}A.push(z.object),Z.push(...z.exposes)}A.push(...Z);let k={...e,decls:A};delete k.amends;for(let f of u)m.has(f.name)||Qq(A,f.name,n)||ot(r,()=>je(a,"orphan_party",`base ${a.name} declares party ${f.name}, and nothing in the amendment binds it any more`,`bind ${f.name} in an attachment, or write hide ${f.name} to drop it on purpose`));return r.length?{ok:!1,diagnostics:r}:{ok:!0,program:k,base:o}}function gv(e,t){let n=e.amends,r=n&&t.get(n.name);if(!n||r===void 0)return i=>i;let a=kc({name:n.name,digest:Qr(r)});return i=>{let s=ky.get(r);if(i.source!==a||!s)return i;let{source:o,...d}=i,{start:p}=i.span,u=h=>h.span.start<=p&&p<h.span.end,m=s.decls.find(h=>h.kind==="object"&&u(h)),c=e.decls.find(h=>h.kind==="object"&&!!m&&h.amends?.name===m.name),{line:l,column:y}=_n(r,p);return{...d,message:`${i.message} (inherited from base ${n.name} at ${l}:${y})`,span:{...(c?.amends??n).span}}}}function Gq(e,t){let n=e?.parameters.find(a=>a.key===t);if(!n)return!1;let r=n.value.kind==="default"?n.value.type:n.value;return r.kind==="call"&&r.name==="enum"}function hv(e,t,n){return e.value.kind==="name"&&e.value.value===t&&!Gq(n,e.key)}function Qq(e,t,n){let r=(a,i)=>{if(Array.isArray(a))return a.some(o=>r(o,i));if(!a||typeof a!="object")return!1;let s=a;if(s.kind==="name"&&typeof s.value=="string")return s.value===t||s.value.startsWith(`${t}.`);if(typeof s.key=="string"&&"value"in s){let o=s,d=zc.exec(o.key);return d?r(o.value,n(d[2])):o.value.kind==="name"?hv(o,t,i):r(o.value,i)}return Object.entries(s).some(([o,d])=>o!=="span"&&r(d,i))};return e.some(a=>a.kind!=="party"&&a.kind!=="expose"&&a.kind!=="hide"&&r(a,a.kind==="assignment"?n(a.target):void 0))}function eL(e,t,n,r,a,i,s,o){let d=t.amends,p=_=>Go(_,d.span,s),u=o.length,m=[],c=[],l=[];for(let _ of e.body.entries){let S=zc.exec(_.key);if(!S){l.push(p(_));continue}let C=[];for(let E of _.value.entries)E.key==="expose"&&E.value.kind==="call"?c.push({key:`${S[1]}.${E.value.name}`,name:E.value.args[0].value,program:!1}):C.push(mv(E,d.span,s));m.push({name:S[1],target:S[2],rows:C,site:_,inherited:!0})}c.push(...n);let y=new Map(m.map(_=>[_.name,_])),h=new Map,b=new Map,A=[],Z=[],k=new Map,f,z,P=[],T=_=>{for(let S of P.splice(0))A[S].before=_},$=_=>{for(let S of _)S.key==="expose"&&S.value.kind==="call"&&ot(o,()=>je(S,"expose_in_amendment",`expose ${S.value.kind==="call"?S.value.name:""} in an amended object; the names table exposes actions`,"move it to names { <attachment> { <action>: <name> } }"))};for(let _ of t.body.entries)ot(o,()=>{let S=zc.exec(_.key);if(S){let C=_.value.entries;$(C);let E={name:S[1],target:S[2],rows:C,site:_,inherited:!1},F=y.get(E.name);if(!F){P.push(A.length),A.push({attachment:E});return}F.target!==E.target&&je(_,"amend_instrument_changed",`attachment ${E.name} of base object ${e.name} is ${F.target}, and an amendment cannot make it ${E.target}`,`restate it as attach ${E.name} = ${F.target} { ... }, or attach ${E.target} under a new name`),(b.has(E.name)||h.has(E.name))&&je(_,"given_twice",`attachment ${E.name} is amended twice`,"amend each attachment in one place"),b.set(E.name,E),T(E.name);return}if(_.key==="names"){f&&je(_,"given_twice","names is given twice","keep one names table"),f=_;return}if(_.key==="hide"){let C=_.value.value;c.some(E=>E.key===C)||je(_.value,"amend_unknown_name",`base object ${e.name} has no exposure ${C}.${en(C,c.map(E=>E.key))}`,`hide one of ${c.map(E=>E.key).join(", ")}`),k.set(C,_.value);return}if(_.key==="fields"){z=_;return}if(Wq.has(_.key)){Z.push(_);return}if(y.has(_.key)&&_.value.kind==="block"){$(_.value.entries),(h.has(_.key)||b.has(_.key))&&je(_,"given_twice",`attachment ${_.key} is amended twice`,"amend each attachment in one place"),h.set(_.key,_),T(_.key);return}je(_,"amend_unknown_name",`base object ${e.name} has no attachment ${_.key}.${en(_.key,[...y.keys()])}`,`amend one of ${[...y.keys()].join(", ")} as <attachment> { <tunable>: <value> }, or attach a new one with attach ${_.key} = <template> { ... }`)});let q=new Map([...m.map(_=>[_.name,b.get(_.name)??_]),...A.map(({attachment:_})=>[_.name,_])]),R=new Map;if(f)for(let _ of f.value.kind==="block"?f.value.entries:[])ot(o,()=>{let S=_.key.split(".")[0];q.has(S)||je(_,"amend_unknown_name",`object ${t.name} has no attachment ${S}.${en(S,[...q.keys()])}`,`name the actions of one of ${[...q.keys()].join(", ")}`),_.value.kind!=="block"&&je(_,"HSX1001",`names ${_.key} takes a block`,`write ${_.key} { <action>: <public name> }`),R.has(_.key)&&je(_,"given_twice",`names ${_.key} is given twice`,"keep one row per attachment");let C=new Map;for(let E of _.value.entries)E.value.kind!=="name"&&je(E,"HSX1001",`names ${_.key}.${E.key} takes a name`,`write ${E.key}: <public name>`),C.set(E.key,E);R.set(_.key,C)});if(o.length>u)return{object:t,exposes:[]};let H=_=>{let S=a(_.target);return S?new Set(S.body.entries.filter(C=>C.key.startsWith("action ")).map(C=>C.key.slice(7))):void 0},x=(_,S)=>{if(_.includes("."))return!0;let C=H(q.get(_));return!C||C.has(S)};for(let _ of c){let[S]=_.key.split(".");if(!b.has(S)||k.has(_.key))continue;let C=_.key.split(".").slice(0,-1).join("."),E=_.key.split(".").at(-1);R.get(C)?.has(E)||ot(o,()=>je(b.get(S).site,"exposure_dropped",`base ${i} exposes ${_.key} as ${_.name}, and restating attach ${S} drops it`,`name it in names { ${C} { ${E}: ${_.name} } }, or write hide ${_.key} to drop it on purpose`))}if(o.length>u)return{object:t,exposes:[]};let w=_=>{let S=a(_.target),C=_.rows.filter(G=>G.key!=="expose");if(_.inherited){let G=h.get(_.name),se=new Map((G?G.value.entries:[]).map(te=>[te.key,te]));C=C.filter(te=>se.has(te.key)||![...r].some(Q=>hv(te,Q,S))).map(te=>se.get(te.key)??te);let B=new Set(C.map(te=>te.key));C.push(...[...se.values()].filter(te=>!B.has(te.key)))}let E=_.name,F=R.get(E)??new Map,X=[...F.values()].filter(G=>!x(E,G.key));if(X.length){let G=C.findIndex(Q=>Q.key==="rename"),se=G<0?[]:C[G].value.entries,B=new Set(X.map(Q=>Q.key)),te={key:"rename",value:Jo([...se.filter(Q=>!B.has(Q.key)),...X],f.span),span:f.span};G<0?C.push(te):C[G]=te}let ae=new Set;if(_.inherited)for(let G of c){if(G.program||!G.key.startsWith(`${E}.`))continue;let se=G.key.slice(E.length+1);if(ae.add(se),k.has(G.key))continue;let B=F.get(se);C.push(B?Iy(se,B.value.value,B.span):Iy(se,G.name,d.span))}for(let G of F.values())x(E,G.key)&&!ae.has(G.key)&&C.push(Iy(G.key,G.value.value,G.span));let W=_.inherited?p(_.site):_.site;return{...W,value:Jo(C,W.value.span)}},v=[];for(let _ of m){for(let{attachment:S,before:C}of A)C===_.name&&v.push(S);v.push(b.get(_.name)??_)}for(let{attachment:_,before:S}of A)S||v.push(_);let L=[],j=l.find(_=>_.key==="fields");if(z||j){let _=z?z.value.entries:[],S=new Set(_.map(F=>F.key)),C=j?j.value.entries.filter(F=>!S.has(F.key)):[],E=z??j;L.push({...E,value:Jo([..._,...C],E.value.span)})}let g=new Set(Z.map(_=>_.key));L.push(...l.filter(_=>_.key!=="fields"&&!g.has(_.key)),...Z.filter(_=>_.key!=="names"&&_.key!=="hide"),...v.map(w));let I=[],O=new Set;for(let _ of n){if(O.add(_.key),k.has(_.key))continue;let S=_.key.split(".").slice(0,-1).join("."),C=_.key.split(".").at(-1),E=R.get(S)?.get(C);I.push({kind:"expose",target:`${t.name}.${_.key}`,name:E?E.value.value:_.name,span:E?.span??d.span})}for(let[_,S]of R)if(_.includes("."))for(let C of S.values())O.has(`${_}.${C.key}`)||I.push({kind:"expose",target:`${t.name}.${_}.${C.key}`,name:C.value.value,span:C.span});return{object:{kind:"object",name:t.name,title:t.title,body:Jo(L,t.body.span),span:t.span},exposes:I}}var Wq,zc,kc,Yq,Iy,Jo,ky,qy=ve(()=>{"use strict";In();Ha();Er();ka();Wq=new Set(["fields","columns","entryActions","belongs_to","names","hide"]),zc=/^attach\s+([A-Za-z0-9_]+)\s*=\s*(.+)$/,kc=e=>`bases/${e.name}.hsx@${e.digest}`;Yq=(e,t)=>({kind:"name",value:e,span:t}),Iy=(e,t,n)=>({key:"expose",value:{kind:"call",name:e,args:[Yq(t,n)],span:n},span:n}),Jo=(e,t)=>({kind:"block",entries:e,span:t}),ky=new Map});function Lc(e,t,n=r=>tL[r]??"unique"){let r=new Map;for(let a of t.entries){let i=r.get(a.key),s=n(a.key);if(!i)r.set(a.key,a);else if(s==="concat"){let o=d=>d.kind==="list"?d.items:[d];r.set(a.key,{...a,value:{kind:"list",items:[...o(i.value),...o(a.value)],span:a.span}})}else(s==="unique"||JSON.stringify(ed(i.value))!==JSON.stringify(ed(a.value)))&&Bn(e,`${a.key} is ${s==="equal"?"set":"given"} twice`,i,a,"keep one",s==="equal"?{values:[i.value,a.value]}:{})}return r}function Fe(e,t){return new Map([...Lc(e,t)].map(([n,r])=>[n,r.value]))}function Se(e){return e?(e.kind!=="block"&&U(e,"expected a block","write { name: value }"),e):qc}function Te(e){return"value"in e&&typeof e.value=="string"?e.value:U(e,"expected a name or literal","write a single name or literal")}function jy(e,t=new Map){return kr(ed(Ly(Qo(e,t))))}function Qo(e,t){if(Array.isArray(e))return e.map(r=>Qo(r,t));if(!e||typeof e!="object")return e;let n=e;if(n.kind==="block"&&n.entries){let r=_v(n,t);return{...n,entries:n.entries.filter(a=>!a.key.startsWith("economics ")).map(a=>Qo(a,r))}}return n.key==="economics"&&n.value?.kind==="name"&&t.has(n.value.value)?{...n,value:Qo(t.get(n.value.value),t)}:Object.fromEntries(Object.entries(n).map(([r,a])=>[r,Qo(a,t)]))}function _v(e,t=new Map){let n=e.entries.filter(r=>r.key.startsWith("economics "));return n.length?new Map([...t,...n.map(r=>[r.key.slice(10),r.value])]):t}function nL(e,t,n,r){let a=fv.get(e);a||fv.set(e,a=new Map);let i=a.get(t);if(i?.source===n)return i.templates;let s=t.slice(t.indexOf(".")+1),o;try{o=ai(n,t)}catch(m){throw!(m instanceof St)||!r?m:new St({...m.diagnostic,related:[{source:r.source??"program",span:r.span,message:`Header ${t} is named here`}]})}let d=new Map([[t,n]]),p=[],u=(m,c,l)=>{p.push({prefix:c,decl:m,digest:jy(m,l)});let y=Fe(d,Se(Fe(d,m.body).get("records")));for(let[h,b]of y)u({kind:"instrument",name:h,parameters:[],body:Se(b),span:m.span},`${c}.${h}`,_v(m.body,l))};for(let m of o.decls)m.kind==="instrument"&&u(m,`${s}.${m.name}`);return a.set(t,{source:n,templates:p}),p}function rL(e){let t=e,n=(t.key==="literal"||t.key==="value")&&t.value?.kind==="money"?/^(\d+)(?:\.(\d+))? ([A-Z]{3})$/.exec(t.value.value):null;if(!n||!Xa(n[3]))return e;let r=Dn(n[3]),a=n[2]??"";if(a.length>r)return e;let i=BigInt(n[1]+a.padEnd(r,"0"));return i!==0n&&n[3]!==Ka?e:{...t,value:{kind:"text",value:i.toString(),span:t.value.span}}}function aL(e,t,n=new Map){let r=new Map,a=new Map,i=new Map,s=new Map,o=new Set,d=(l,y)=>{if(o.has(l))return!0;let h=n.get(l)??l,b=e.std.get(h);if(b===void 0)return!1;t.set(h,b);let A=nL(e,h,b,y);o.add(l);for(let{prefix:Z,decl:k,digest:f}of A){let z=r.get(Z);z&&Bn(t,`instrument ${Z} is declared twice`,z,k,"give each instrument a distinct name"),r.set(Z,k),a.set(k,h),i.set(Z,f);let[,P,...T]=Z.split(".");s.set(k,{key:`${l}.${P}`,recordPath:T.join("."),digest:f})}return!0},p=(l,y)=>{let h=l.indexOf(".");return h>0&&d(l.slice(0,h),y)},u=(l,y)=>(p(l,y),r.get(l));return{templates:r,declarationSources:a,familyDigests:i,standardOrigins:s,loadPath:p,templateAt:u,requireTemplate:(l,y)=>{let h=u(l,y);if(h)return h;let b=l.split(".")[0],A=(Z,k,f)=>{let z=en(k,f);return z?`unknown ${Z} ${k}.${z}`:`unknown ${Z} ${k}`};return l.includes(".")&&!e.std.has(n.get(b)??b)&&U(y,A("header",b,[...e.std.keys()]),"name a published header","unknown_header"),U(y,A("instrument",l,[...r.keys()].filter(Z=>Z.startsWith(`${b}.`))),l.includes(".")?`choose an instrument header ${b} declares`:"choose a declared instrument","unknown_instrument")},resolveFamily:(l,y,h=!0)=>{let b=l.split(".");if(b.length<2){if(!h)return;je(y,"unknown_family",`invalid family ${l}`,"use module.instrument or module.instrument.record")}p(l,y);let A=i.get(l);if(!A){if(!h)return;je(y,"unknown_family",`unknown family declaration ${l}`,"choose a declared standard instrument")}return{module:b[0],exportPath:b.slice(1).join("."),digest:A}}}}function Ay(e,t,n,r,a){let{texts:i,header:s,override:o}=a,d=Lc(i,r,()=>"equal"),p=new Map([...d].map(([y,h])=>[y,h.value])),u=new Map(a.inherited),m=new Map(a.inheritedTerms),c=[],l;for(let y of e.parameters){let h=y.value.kind==="default"?y.value.type:y.value,b=o?.instrument===t&&o.name===y.key,A=y.value.kind==="default"&&!b?y.value.value:void 0,Z=h.kind==="type"||h.kind==="call"?h.name:Te(h),k=a.attached&&Z==="party",f=(h.kind==="type"||h.kind==="call")&&!!h.optional,z=k&&!f&&!b&&(un.includes(y.key)||a.parties[y.key])?{kind:"name",value:y.key,span:n}:void 0,P=!b||o.text==="unset"?void 0:{...rv(o.text)??U({span:n},`${y.key} cannot hold ${o.text}`,"override with text the term once held","tunable_type_mismatch"),source:"override"},T=b?P:p.get(y.key);b&&o.from==="std"&&(l={...e,parameters:e.parameters.map(q=>q!==y?q:{...q,value:P?{kind:"default",type:h,value:P,span:q.span}:h})}),m.set(y.key,b?{...P?{value:P}:{},from:o.from,span:P?.span??n,source:"override"}:T?{value:T,from:"program",span:T.span,source:T.source??"program"}:z?{value:z,from:"party",span:n,source:"program"}:{...A?{value:A}:{},from:"std",span:(A??y).span,source:s});let $=T??z??(A&&{...A,source:s});if(!$){if(f)continue;c.push({span:n,code:k?"subject_party_unbound":"HSX1001",message:k?`\`${y.key}\` has no binding. An attached ${y.key} must resolve to a subject role or an eligible declared party.`:`${t} needs ${y.key}`,fix:k?`Use \`${y.key}: customer\` for a customer, \`${y.key}: operator\` for your company, or a declared business for a fixed company counterparty.`:`add ${y.key}: value inside ${t}`,related:[{source:s,span:y.span,message:`Parameter ${y.key}`}]});continue}u.set(y.key,$)}return{supplied:d,terms:m,environment:u,missing:c,...l?{revertedHeader:l}:{}}}function bv(e,t,n,r){let a=e.entries.filter(s=>s.key.startsWith("action ")).map(s=>s.key.slice(7)),i=a.length?{name:t,actions:a}:r;for(let s of e.entries){let o=s.value.kind==="list"?s.value.items:s.value.kind==="block"?[s.value]:[];if(s.key!=="invoke"){for(let d of o)d.kind==="block"&&bv(d,s.key,n,i);continue}for(let d of o){if(d.kind!=="block"||!i)continue;let p=new Map(d.entries.map(c=>[c.key,c.value])),u=p.get("reference"),m=p.get("action");u?.kind==="name"&&u.value==="self.id"&&m?.kind==="name"&&!i.actions.includes(m.value)&&ot(n,()=>je(m,"unknown_action",`\`${m.value}\` is not an action of \`${i.name}\`.${en(m.value,[...i.actions])}`,`Name an action \`${i.name}\` declares (${i.actions.join(", ")}), or write \`on <reference>\` for another instrument's action.`))}}}function xv(e,t,n,r){let a=[],i=new Map;for(let q of e.uses)ot(a,()=>{let R=q.name.slice(q.name.indexOf(".")+1);t.std.has(q.name)||U(q,`unknown header ${q.name}`,`publish ${q.name} to this tenant, or remove the use line`,"unknown_header"),(i.has(R)||t.std.has(R))&&U(q,`${R} already names ${i.get(R)??`the std header ${R}`}`,"use each header name once","given_twice"),i.set(R,q.name)});let s=aL(t,n,i),o=new Map(e.decls.flatMap(q=>q.kind==="instrument"?[[q.name,q]]:[])),d=yv(e,t.bases,q=>{try{return o.get(q)??s.templateAt(q)}catch(R){if(R instanceof St)return;throw R}});if(!d.ok)return{ok:!1,diagnostics:d.diagnostics};e=d.program,d.base&&n.set(kc(d.base),t.bases.get(d.base.name));let p=Object.assign(Object.create(null),{programOperator:{kind:"business",role:"program_operator"},programTax:{kind:"business",role:"tax_payable"}}),u=new Map,m=new Map,c=new Map,l=new Map;try{e.header&&U(e,"compile a program, not a header",'start with program product_name "Title"',"program_is_header"),Xa(e.currency)||ot(a,()=>U(e,`${e.currency} is not an ISO 4217 currency with minor units`,"write a three-letter ISO 4217 code such as SAR, USD or JPY","currency_unknown"));for(let q of e.decls)q.kind==="instrument"&&(s.templates.set(q.name,q),bv(q.body,q.name,a));for(let q of e.decls)ot(a,()=>{if(q.kind==="expose"||q.kind==="hide"||q.kind==="accept")return;let R=l.get(q.name);if(R&&Bn(n,`${q.name} is declared twice`,R,q,"give this declaration a distinct name"),l.set(q.name,q),q.kind==="object"){u.set(q.name,q);for(let H of q.body.entries){let x=/^attach\s+(\w+)\s*=\s*(.+)$/.exec(H.key);if(!x)continue;let w=`${q.name}_${x[1]}`;m.set(w,{kind:"assignment",name:w,target:x[2],body:Se(H.value),span:H.span}),c.set(w,q.name)}}q.kind==="assignment"&&m.set(q.name,q),q.kind==="party"&&((un.includes(q.name)||q.name===vy)&&je(q,"party_name_reserved",`${q.name} is a reserved subject role`,"choose a party name other than owner, actor, operator or customer"),["person","business","staff"].includes(q.partyKind)||U(q,`unknown party kind ${q.partyKind}`,"choose person, business, or staff","unknown_party_kind"),p[q.name]={kind:q.partyKind,...q.role?{role:q.role}:{}})})}catch(q){if(q instanceof St)return{ok:!1,diagnostics:[...a,q.diagnostic]};throw q}if(a.length)return{ok:!1,diagnostics:a};let y=(q,R,H)=>ot(a,()=>{q.arguments=H,q.tunables=Ay(R,q.id,q.site.span,H,{texts:n,header:s.declarationSources.get(R)??"program",attached:q.subject!==void 0,parties:p,override:r})}),h=(q,R)=>ot(a,()=>{let H=s.requireTemplate(q.target,R);q.familyDeclaration=s.resolveFamily(q.target,R,!1),q.standardOrigin=s.standardOrigins.get(H),q.template=H}),b=new Map,A=new Map;for(let q of e.decls){if(q.kind==="assignment"){let H={id:q.name,site:q,target:q.target};b.set(q,H),h(H,q),H.template&&y(H,H.template,q.body)}if(q.kind!=="object")continue;let R=q.body.entries.flatMap(H=>{let x=iL.exec(H.key);if(!x)return[];let w={id:`${q.name}_${x[1]}`,site:H,target:x[2],subject:q.name,attachmentName:x[1]};return b.set(H,w),h(w,H),[w]});ot(a,()=>{let H=Fe(n,q.body),x=H.get("belongs_to"),w=H.get("entryActions"),v=new Set(w?.kind==="list"?w.items.filter(g=>g.kind==="name").map(Te):[]),L=new Map;for(let g of R){if(!g.template)continue;let I=g.site,O=Se(I.value).entries;L.set(I,{name:g.attachmentName,entry:I,template:g.template,rows:O.filter(D=>!D.key.startsWith("economics ")&&D.key!=="rename"&&D.key!=="expose"),exposed:new Map(O.flatMap(D=>D.key==="expose"&&D.value.kind==="call"?[[D.value.name,Te(D.value.args[0])]]:[]))})}let j=uv([...L.values()],v,x?.kind==="name"&&x.value==="company",q.name,t.std,g=>un.includes(g)||!!p[g]);a.push(...j.diagnostics),A.set(q,{sites:L,placement:j});for(let g of R){let I=L.get(g.site);I&&y(g,g.template,{kind:"block",entries:j.rows.get(I)??I.rows,span:g.site.value.span})}})}let Z=(q,R)=>[q,...[...Fe(n,Se(Fe(n,R).get("records")))].flatMap(([H,x])=>Z(`${q}_${H}`,Se(x)))],k=new Map,f=a.length;for(let q of b.values())ot(a,()=>{if(q.template)for(let R of Z(q.id,q.template.body)){let H=k.get(R);H&&H!==q&&Bn(n,`attachments \`${H.attachmentName??H.id}\` and \`${q.attachmentName??q.id}\` both lower to ${R}`,H.site,q.site,"rename one attachment",{code:"attachment_id_clash"}),k.set(R,q)}});if(a.length>f)return{ok:!1,diagnostics:a};let z=new Set(e.decls.flatMap(q=>q.kind==="expose"&&q.target.endsWith(".create")?[q.target.split(".").slice(0,-1).join("_")]:[])),P=new Set(e.decls.flatMap(q=>{if(q.kind!=="expose")return[];let R=q.target.split("."),H=R.pop();return[`${R.join("_")} ${H}`]})),T=new Set,$=q=>{if(q.kind==="list"&&q.items.forEach($),q.kind==="block")for(let R of q.entries){if(R.key==="invoke")for(let H of R.value.kind==="list"?R.value.items:[R.value]){let x=H.kind==="block"?H.entries.find(w=>w.key==="action")?.value:void 0;x&&"value"in x&&typeof x.value=="string"&&T.add(x.value)}$(R.value)}};for(let q of e.decls)"body"in q&&$(q.body);return{ok:!0,bound:{program:e,...d.base?{base:d.base}:{},sources:n,headers:s,parties:p,names:l,objects:u,assignments:m,attachmentSubjects:c,attachments:b,placements:A,exposedCreates:z,exposedActions:P,invokedActions:T,diagnostics:a}}}var qc,tL,ed,Ly,fv,iL,Py=ve(()=>{"use strict";Er();In();ka();Ls();lv();qy();qc={kind:"block",entries:[],span:{start:0,end:0}},tL={requires:"concat",moves:"concat",invariants:"concat",invoke:"concat",calculate:"concat",expose:"concat"},ed=e=>Array.isArray(e)?e.map(ed):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="span"||t==="source"||n===void 0?[]:[[t,ed(n)]])):e;Ly=e=>Array.isArray(e)?e.filter(t=>!(t?.key==="actor"&&t.value?.kind==="name"&&t.value.value==="caller")).map(Ly):e&&typeof e=="object"?Object.fromEntries(Object.entries(rL(e)).flatMap(([t,n])=>t==="round"&&n?.kind==="name"&&n.value==="floor"?[]:[[t,Ly(n)]])):e,fv=new WeakMap;iL=/^attach\s+([A-Za-z0-9_]+)\s*=\s*(.+)$/});function Bi(e){let t=new Map;for(let n of e)t.has(n.path)||t.set(n.path,n);return n=>{for(let r=n;;){let a=t.get(r);if(a)return a;let i=/(?:\.[^.[]*|\[\d+\])$/.exec(r);if(!i||!i.index)return;r=r.slice(0,i.index)}}}function Dy(e,t){return Bi(e)(t)}function Ry(e,t,n){let r=/^\$\.objects(?:\[(\d+)\]|\.(\w+))(?:\.(\w+))?/.exec(n);if(!r)return;let a=e.get(r[2]??t.objects[Number(r[1])]?.id??"");return a&&(a.body.entries.find(i=>i.key===r[3])??a)}function kv(e){let t=e.value.kind==="default"?e.value.type:e.value;return t.kind!=="call"||t.name!=="sensitive"?{type:t,sensitive:!1}:(t.args.length!==1&&U(t,"sensitive needs one field type","write sensitive(text)","field_type_invalid"),{type:t.args[0],sensitive:!0})}function qv(e,t,n=r=>r){let{type:r,sensitive:a}=kv(t);if(r.kind==="block"){let d=Fe(e,r);if(d.has("family")||d.has("target")||d.has("instrument")){let p=d.get("instrument")??d.get("target"),u;if(p){let m=n(p);if(m.kind==="list"){let c=m.items.map(l=>Te(n(l)));u=c.length===1?c[0]:c}else u=Te(m)}return{name:t.key,type:"ref",targetKind:"instrument",...u!==void 0?{target:u}:{},...a?{sensitive:!0}:{},...t.description!==void 0?{description:t.description}:{}}}}let i=r.kind==="type"||r.kind==="call"?r.name:Te(r),s={name:t.key,type:i,...(r.kind==="type"||r.kind==="call")&&r.optional?{optional:!0}:{},...a?{sensitive:!0}:{},...t.description!==void 0?{description:t.description}:{}},o=r.kind==="type"||r.kind==="call"?r.currency:void 0;if(o!==void 0&&(Xa(o)||U(r,`${o} is not an ISO 4217 currency with minor units`,"write a three-letter ISO 4217 code such as SAR, USD or JPY","currency_unknown"),o!==gr&&(s.currency=o)),i==="enum"&&r.kind==="call"&&(s.values=r.args.map(Te)),i==="text"&&r.kind==="call"&&((r.args.length<2||r.args.length>3)&&U(r,"bounded text needs length bounds and an optional pattern","write text(1, 80)","field_type_invalid"),s.minLength=Wt(n(r.args[0])),s.maxLength=Wt(n(r.args[1])),r.args[2]&&(s.pattern=Wt(n(r.args[2])))),["integer","money"].includes(i)&&r.kind==="call"&&(r.args.length!==2&&U(r,"bounded fields need a minimum and maximum",`write integer(1, 12) or money(0 ${gr}, 100 ${gr})`,"field_type_invalid"),s.minimum=Wt(n(r.args[0])),s.maximum=Wt(n(r.args[1])),i==="money"))for(let d of r.args)Hy(n(d),o??gr,t.key);if(r.kind==="call"&&!["enum","text","integer","money","list","account"].includes(i)&&U(r,`unknown field constructor ${i}`,"use a field type without arguments","field_type_invalid"),i==="list"&&r.kind==="call"){(r.args.length<1||r.args.length>2)&&U(r,"list needs an item type and optional bound","write list(text, 12)","field_type_invalid");let d=r.args[0];s.item=d.kind==="type"?d.name:Te(d),d.kind==="type"&&d.name==="ref"&&(s.target=d.target,s.targetKind="object"),s.maxItems=r.args[1]?Wt(n(r.args[1])):366}if(i==="list"&&r.kind==="type"&&(s.item=r.target,s.maxItems=366),i==="digest"){let d=r.kind==="type"?r.target:void 0;d||U(t,"a digest names the kind of record it identifies","write digest<document>","field_type_invalid"),Vp.includes(d)||U(t,`${d} is not a record kind`,`write digest<${Vp.join(" | ")}>`,"field_type_invalid"),s.kind=d}if(i==="ref"){let d=r.kind==="type"?r.target:s.target;!d&&r.kind!=="block"&&U(t,"reference needs a target","write ref<object>","field_type_invalid"),s.targetKind=s.targetKind??"object",d&&(s.target=d)}return s}function vv(e,t,n=r=>r){let r=qv(e,t,n);r.type==="digest"&&U(t,"an object field cannot hold a digest","declare the digest field on the instrument the object attaches","field_type_invalid");let a=t.value.kind==="default"?n(t.value.value):void 0;a&&!(a.kind==="name"&&a.value==="runtime")&&(r.value=r.type==="enum"&&a.kind==="name"?a.value:Wt(a,String(r.type)),r.type==="money"&&Hy(a,r.currency??gr,t.key));let i=Ga.safeParse(r);return i.success||U(t,i.error.message,"use a UDL object field type and its constraints"),i.data}function sL(e){let t=e.fields.flatMap(n=>n.type==="account"&&typeof n.owner=="string"?[n.owner]:[]);for(let n of Object.values(e.actions)){typeof n.actor=="object"&&"party"in n.actor&&t.push(n.actor.party);for(let r of n.moves){r.economics&&t.push(r.economics.sourceParty);for(let a of"from"in r?[r.from,r.to]:[])a.startsWith("party.")&&t.push(a.slice(6))}}return t}function Lv(e,t,n){e.startsWith("-")&&U(n,"literal cannot be negative","write a positive value; a move's from and to set its direction","literal_negative");let[r="",a=""]=e.split(".");return(!/^\d+$/.test(r)||a.length>t)&&U(n,`literal has more than ${t} decimal places`,`write at most ${t} decimal places`,"decimal_places"),(BigInt(r)*10n**BigInt(t)+BigInt(a.padEnd(t,"0")||"0")).toString()}function oL(e){if(!["duration","text","name"].includes(e.kind))return;let t=e.value.trim(),n={d:"D",w:"W",m:"M",y:"Y"},r=/^([1-9]\d{0,3}) ?(day|week|month|year)s?$/.exec(t),a=/^([1-9]\d{0,3})(d|w)$/.exec(t),i=/^P(?!$)(?:[1-9]\d{0,3}Y)?(?:[1-9]\d{0,3}M)?(?:[1-9]\d{0,3}W)?(?:[1-9]\d{0,3}D)?$/.exec(t);return r?`P${r[1]}${n[r[2][0]]}`:a?`P${a[1]}${n[a[2]]}`:i?t:void 0}function dL(e){let t=Se(e);return{...t,entries:t.entries.map(n=>{if(n.key!=="fields")return n;let r=Se(n.value);return{...n,value:{...r,entries:r.entries.map(a=>{let i=Se(a.value),[s]=i.entries,o=s?.value;if(s?.key!=="literal"||!o)return a;let d;if(o.kind==="money"){let{amount:p,currency:u}=jc(o),m=Dn(u),c=p.padStart(m+1,"0");d=m?`${u} ${c.slice(0,-m)}.${c.slice(-m)}`:`${u} ${c}`}else o.kind==="date"&&(d=String(Wt(o)).slice(0,10));return d===void 0?a:{...a,value:{...i,entries:[{...s,value:{kind:"text",value:d,span:o.span}}]}}})}}})}}function jc(e){let[t,n]=e.value.split(" ");Xa(n)||U(e,`${n} is not an ISO 4217 currency with minor units`,"write a three-letter ISO 4217 code such as SAR, USD or JPY","currency_unknown");let r=Lv(t,Dn(n),e);return r.length>18&&U(e,"amount exceeds 18 minor-unit digits","write a smaller amount","amount_too_large"),{amount:r,currency:n}}function Wt(e,t){if(e.kind==="text"&&t==="duration")return Wt({...e,kind:"duration"});if(e.kind==="text"&&t==="money"&&js.push(mc(e,"this field",gr)),e.kind==="money"){let{amount:n,currency:r}=jc(e);return r!==gr&&!/^0+$/.test(n)&&Mi.set(Sy(e),{expr:e,count:(Mi.get(Sy(e))?.count??0)+1}),n}if(e.kind==="percent"){let n=Number(Lv(e.value,6,e));return n>Cy&&U(e,"percentage exceeds 100%","write a percentage from 0% to 100%","percent_over_100"),n}if(e.kind==="number"){let n=Number(e.value);return Number.isSafeInteger(n)||U(e,"expected a safe integer",`write an integer, a percentage, or an amount with ${gr}`),n}if(e.kind==="duration"||e.kind==="name"&&/^P(?:\d|T)/.test(e.value)){let n=/^(\d+)(ms|s|m|h|d|w)$/.exec(e.value),r={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5},a=n?Number(n[1])*r[n[2]]:Sm(e.value)??NaN;return(!Number.isSafeInteger(a)||a<0||a>8e15)&&U(e,e.value.includes(" ")?`${e.value} is not a fixed duration`:"invalid duration","write a fixed duration such as 0d, 48h, 3d or 30d","invalid_duration"),a}if(e.kind==="date"){let n=e.value.length===10?e.value+"T00:00:00Z":e.value,r=Date.parse(n),a=Date.parse(n.slice(0,10)+"T00:00:00Z");return(!Number.isFinite(r)||!Number.isFinite(a)||new Date(a).toISOString().slice(0,10)!==n.slice(0,10))&&U(e,"invalid date","write a calendar date or a timestamp with an explicit offset","invalid_date"),new Date(r).toISOString()}return e.kind==="text"?e.value:e.kind==="name"&&["true","false"].includes(e.value)?e.value==="true":(e.kind==="name"&&e.value==="runtime"&&U(e,"this value is fixed when the program compiles, so it cannot be runtime","write a literal value","runtime_not_allowed"),U(e,"expected a literal","write a typed constant"))}function pL(e,t){let n=o=>{let d=o;if(d?.kind!=="block")return;let p=d.entries.find(u=>u.key==="adapter");return p?.value.kind==="name"?p.value.value:void 0},r=new Map,a=(o,d)=>{if(Array.isArray(o)){for(let u of o)a(u,d||u?.key==="boundary"&&n(u.value)!==void 0);return}if(!o||typeof o!="object")return;let p=o;if(p.kind==="name"&&typeof p.value=="string"){let u=r.get(p.value)??{all:0,boundary:0};u.all++,d&&u.boundary++,r.set(p.value,u)}for(let u of Object.values(o))a(u,d)};a(e.body,!1);let i=new Set([...t].filter(o=>{let d=r.get(o);return d&&d.boundary>0&&d.all===d.boundary}));if(i.size===0)return;let s=o=>Array.isArray(o)?o.filter(d=>!(d?.key==="boundary"&&i.has(n(d.value)))).map(s):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([d,p])=>[d,s(p)])):o;return{...e,parameters:e.parameters.filter(o=>!i.has(o.key)),body:s(e.body)}}function Ey(e){let t=Sy(e),n=Mi.get(t);n&&(n.count>1?n.count-=1:Mi.delete(t))}function cL(){let e=[...Mi.values()].map(({expr:t})=>yc(t,"this amount",gr));return Mi=new Map,e}function Hy(e,t,n){if(e?.kind!=="money")return;Ey(e);let[r,a]=e.value.split(" ");a!==t&&!/^0+(?:\.0*)?$/.test(r)&&js.push(yc(e,n,t))}function uL(e,t){if(!e||!("literal"in e)||typeof e.literal!="string")return;let n=t.get(e),r=n?.kind==="block"?n.entries.find(a=>a.key==="literal")?.value:void 0;return r?.kind==="text"?r:void 0}function Ny(e,t){if(!e||!("literal"in e))return;let n=t.get(e),r=n?.kind==="block"?n.entries.find(a=>a.key==="literal")?.value:n;return r?.kind==="money"?r:void 0}function aa(e,t,n,r){let a=mt(e,t,/^(self|input|party|subject)\./.test(n)?n:`self.${n}`,r?.input,r);return a?.type==="money"||a?.type==="account"?a.currency??e.currency:void 0}function lL(e,t){for(let n of e.instruments){let r=i=>{let s=d=>ft(d)?d.op==="rate"?s(d.base):d.op==="multiply"||d.op==="divide"?s(d.amount):d.op==="ratio"?d.currency===void 0?s(d.amount):void 0:ln(d).map(s).find(p=>p!==void 0):"field"in d?aa(e,n,d.field,i):Ny(d,t)?.value.split(" ")[1],o=(d,p)=>{if(!ft(d))return;if(d.op==="ratio"&&d.currency===void 0){let m=s(d.amount);p&&m&&m!==p&&(d.currency=m)}let u=d.op==="ratio"?d.currency??p:p;for(let m of ln(d))o(m,u)};return(d,p)=>o(d,aa(e,n,p,i))},a=r();for(let i of n.calculate??[])nr(i)&&a(i,i.target);for(let i of Object.values(n.actions)){let s=r(i);for(let o of i.calculate??[])nr(o)&&s(o,o.target);for(let[o,d]of Object.entries(i.set??{}))s(d,o);for(let o of i.moves)"amount"in o&&s(o.amount,o.from)}}}function mL(e,t,n){let r=t.retired.map(d=>new RegExp(d)),a=new Set(Object.keys(t.adapters)),i=(d,p)=>ot(n,()=>{a.has(d)&&U(p,`${d} is the id of a bound adapter`,"name it in the business's words","name_reserved"),r.some(u=>u.test(d))&&U(p,`${d} is a retired name`,"name it in the business's words","name_reserved")}),s=(d,p="")=>{let u=d.span.start+p.length;i(d.key.slice(p.length),{span:{start:u,end:u+d.key.length-p.length}})},o=d=>d?.kind==="block"?d.entries:[];i(e.name,e);for(let d of e.decls)if((d.kind==="party"||d.kind==="expose")&&i(d.name,d),!(d.kind!=="instrument"&&d.kind!=="object")){i(d.name,d);for(let p of d.body.entries){if(p.key==="fields")for(let u of o(p.value))s(u);for(let u of["action ","attach "])p.key.startsWith(u)&&s(p,u);if(p.key==="lifecycle"){for(let u of o(p.value))if(u.key==="states"&&u.value.kind==="list")for(let m of u.value.items)m.kind==="name"&&i(m.value,m)}}}}function yL(e,t,n,r){let a=[-1/0,1/0],i=new Map(e.instruments.map(T=>[T.id,T])),s=new Map,o=new Map,d=new Map;for(let T of e.instruments){let $=new Set(T.fields.flatMap(R=>R.type==="integer"&&R.value===void 0&&R.minimum===void 0&&R.maximum===void 0?[R.name]:[])),q=(R,H,x,w)=>{if(!$.has(R))return;let v=`${T.id}.${R}`;d.set(v,[...d.get(v)??[],{how:H,action:w,phase:x}])};for(let R of T.calculate)q(R.target,R,"none");for(let R of Object.values(T.actions)){for(let H of R.input)q(H.name,{field:`input.${H.name}`},"none",R);for(let[H,x]of Object.entries(R.set??{}))q(H,x,"set",R);for(let H of R.calculate??[])q(H.target,H,"let",R)}}let p=T=>T?.type!=="integer"?a:T.value!==void 0?[T.value,T.value]:[T.minimum??-1/0,T.maximum??1/0],u=T=>!!T&&typeof T=="object"&&(["unique","evidence","approval"].includes(T.kind)||Object.values(T).some(u)),m=(T,$)=>!!T&&typeof T=="object"&&("field"in T&&typeof T.field=="string"&&$.has(T.field.split(".")[1]??"")||Object.values(T).some(q=>m(q,$))),c=(T,$,q,R,H)=>{if(!q||H==="none")return T;let[x,w]=T,v=new Set((q.calculate??[]).map(g=>g.target)),L=q.requires.findIndex(u),j=H==="set"?q.requires:q.requires.slice(0,L<0?void 0:L).filter(g=>!m(g,v));for(let g of j){if(g.kind!=="compare")continue;let I=[[g.left,g.operator,g.right],[g.right,{"<":">","<=":">=",">":"<",">=":"<="}[g.operator]??g.operator,g.left]];for(let[O,D,_]of I){if(!("field"in O)||O.field!==$||"field"in _&&_.field===$)continue;let S="literal"in _?k(R,_,q,"none"):"field"in _?h(R,_.field,q):void 0;if(!S)continue;let[C,E]=S;(D==="<="||D==="==")&&(w=Math.min(w,E)),D==="<"&&(w=Math.min(w,E-1)),(D===">="||D==="==")&&(x=Math.max(x,C)),D===">"&&(x=Math.max(x,C+1))}}return[x,w]},l=(T,$)=>d.has(`${T}.${$}`)?s.get(`${T}.${$}`):p(i.get(T)?.fields.find(q=>q.name===$)),y=T=>{let $=T.filter(q=>q!==void 0);if($.length)return[Math.min(...$.map(q=>q[0])),Math.max(...$.map(q=>q[1]))]},h=(T,$,q)=>{let[R,H,x]=$.split(".");return x!==void 0||!H?a:R==="input"?p(q?.input.find(w=>w.name===H)):R==="self"?l(T.id,H):a},b=(T,$,q,R)=>{let[H,x,w,...v]=$.split(".");if(v.length||!x)return a;if(H==="input"){let g=q?.input.find(I=>I.name===x);return w===void 0?c(p(g),$,q,T,R):a}if(H!=="self")return a;if(w===void 0){let g=l(T.id,x);return g&&(R==="set"||!q?.calculate?.some(I=>I.target===x))?c(g,$,q,T,R):g}let L=T.fields.find(g=>g.name===x);if(L?.type!=="ref"||L.targetKind!=="instrument")return a;let j=st(L.target).map(g=>l(g,w));return j.some(g=>g===void 0)?void 0:y(j)},A=(T,$)=>T===0||$===0?0:T*$,Z=(T,$,q)=>{let R=[q(T[0],$[0]),q(T[0],$[1]),q(T[1],$[0]),q(T[1],$[1])].filter(H=>!Number.isNaN(H));return[Math.min(...R),Math.max(...R)]},k=(T,$,q,R)=>{if("literal"in $)return Number.isSafeInteger($.literal)?[$.literal,$.literal]:a;if("field"in $)return b(T,$.field,q,R);let H=w=>k(T,w,q,R),x=w=>{let v=w.map(H);return v.some(L=>L===void 0)?void 0:v};switch($.op){case"aggregate":{if($.measure==="count")return[0,$.selection.limit];let[w,v]=$.measure.sum.replace(/^self\./,"").split(".");if(v!==void 0)return a;let L=y(st($.selection.instrument).map(g=>l(g,w)));if(!L)return;let j=$.selection.limit;return[Math.min(0,A(L[0],j)),Math.max(0,A(L[1],j))]}case"sum":{let w=x($.values);return w?[w.reduce((v,L)=>v+L[0],0),w.reduce((v,L)=>v+L[1],0)]:void 0}case"subtract":{let w=x([$.base,...$.subtract]);if(!w)return;let[v,...L]=w;return[L.reduce((j,g)=>j-g[1],v[0]),L.reduce((j,g)=>j-g[0],v[1])]}case"minimum":case"maximum":{let w=x($.values);if(!w)return;let v=$.op==="minimum"?Math.min:Math.max;return[v(...w.map(L=>L[0])),v(...w.map(L=>L[1]))]}case"multiply":{let w=x([$.amount,$.units]);return w&&Z(w[0],w[1],A)}case"divide":{let w=x([$.amount,$.divisor]);if(!w)return;if(w[1][0]<=0)return a;let v=Z(w[0],w[1],(L,j)=>L/j);return[Math.floor(v[0]),Math.ceil(v[1])]}case"between":return $.unit==="milliseconds"?a:[0,1/0];case"choose":return y([H($.then),H($.otherwise)]);default:return a}},f=new Set,z=(T,$)=>{if(typeof T=="number"&&Number.isSafeInteger(T)){if(["literal","minimum","maximum","value","limit"].includes($))for(let q of[T-1,T,T+1])f.add(q)}else if(Array.isArray(T))T.forEach(q=>z(q,$));else if(T&&typeof T=="object")for(let[q,R]of Object.entries(T))z(R,q)};z(e.instruments);let P=[...f].sort((T,$)=>T-$);for(let T=!0;T;){T=!1;for(let[$,q]of d){let R=i.get($.slice(0,$.indexOf("."))),H=y(q.map(L=>k(R,L.how,L.action,L.phase))),x=s.get($),w=y([x,H]);if(!w||x&&w[0]===x[0]&&w[1]===x[1])continue;let v=(o.get($)??0)+1;o.set($,v),s.set($,v>4&&x?[w[0]<x[0]?[...P].reverse().find(L=>L<=w[0])??-1/0:x[0],w[1]>x[1]?P.find(L=>L>=w[1])??1/0:x[1]]:w),T=!0}}for(let[T,[$,q]]of s){if(!Number.isSafeInteger($)||!Number.isSafeInteger(q))continue;let R=T.indexOf("."),H=i.get(T.slice(0,R)).fields.find(x=>x.name===T.slice(R+1));H?.type==="integer"&&(H.minimum=$,H.maximum=q)}for(let T of e.instruments){let $=v=>v.type==="integer"&&(v.minimum===void 0||v.maximum===void 0),q=new Set(Object.values(T.actions).flatMap(v=>v.input.flatMap(L=>{let j=T.fields.find(I=>I.name===L.name),g=Object.entries(v.set??{}).flatMap(([I,O])=>"field"in O&&O.field===`input.${L.name}`?[I]:[]);return $(L)?[...j&&$(j)?[j.name]:[],...g]:[]}))),R=(v,L)=>{if(!("field"in v))return!1;let[j,g,I]=v.field.split(".");if(I!==void 0)return!1;if(j==="input"){let D=L?.input.find(_=>_.name===g);return!!D&&$(D)}let O=T.fields.find(D=>D.name===g);return j==="self"&&q.has(g)&&O?.type==="integer"&&$(O)&&O.value===void 0},H=(v,L,j)=>ot(r,()=>U(t.get(v)??t.get(L)??n.get(T),`${"field"in v?v.field:"this integer"} is an integer the caller sends with no declared bounds, and it is ${j}`,`declare its bounds, for example ${("field"in v?v.field:"n").split(".").pop()}: integer(1, 360)`,"integer_unbounded")),x=(v,L)=>{if(ft(v)){if(v.op==="divide"&&R(v.divisor,L)&&H(v.divisor,v,"a divisor"),v.op==="ratio"&&(R(v.denominator,L)&&H(v.denominator,v,"a divisor"),R(v.numerator,L)&&H(v.numerator,v,"a money factor")),v.op==="multiply")for(let[j,g]of[[v.units,v.amount],[v.amount,v.units]])R(j,L)&&w(g,L)&&H(j,v,"a money factor");for(let j of ln(v))x(j,L)}},w=(v,L)=>ft(v)?ln(v).some(j=>w(j,L)):"field"in v?aa(e,T,v.field,L)!==void 0:!!Ny(v,t);for(let v of T.calculate)nr(v)&&x(v);for(let v of Object.values(T.actions)){for(let L of v.calculate??[])nr(L)&&x(L,v);for(let L of Object.values(v.set??{}))x(L,v);for(let L of v.moves)"amount"in L&&x(L.amount,v)}}}function gL(e,t){let n=[],r=new Map(e.instruments.map(i=>[i.id,i])),a=(i,s)=>i.map(o=>r.get(o)).map(o=>o&&aa(e,o,s)).find(o=>o!==void 0);for(let i of e.instruments){let s=(c,l)=>mt(e,i,/^(self|input|party|subject)\./.test(c)?c:`self.${c}`,l?.input,l)?.type==="money",o=(c,l,y)=>{let h=Ny(c,t);h&&Ey(h);let[b,A]=h?.value.split(" ")??[];h&&A!==y&&!/^0+(?:\.0*)?$/.test(b)&&n.push(yc(h,l,y))},d=(c,l,y=e.currency)=>{if(c&&ft(c)){let b=c.op==="rate"?[c.base]:c.op==="multiply"||c.op==="divide"||c.op==="ratio"?[c.amount]:ln(c),A=c.op==="ratio"?c.currency??y:y;b.forEach(Z=>d(Z,l,A));return}let h=uL(c,t);h&&n.push(mc(h,l,y)),o(c,l,y)},p=c=>{for(let[l,y]of Object.entries(c.where??{})){let h=a(st(c.instrument),l);h&&d(y,l,h)}},u=(c,l)=>{if(c.kind==="all"||c.kind==="any")c.of.forEach(y=>u(y,l));else if(c.kind==="not")u(c.condition,l);else if(c.kind==="compare")"field"in c.left&&s(c.left.field,l)&&d(c.right,c.left.field,aa(e,i,c.left.field,l)),"field"in c.right&&s(c.right.field,l)&&d(c.left,c.right.field,aa(e,i,c.right.field,l));else if(c.kind==="aggregate"&&(p(c.selection),typeof c.measure=="object")){let y=a(st(c.selection.instrument),c.measure.sum);y&&d(c.value,c.measure.sum,y)}},m=(c,l)=>{let y=`self.${c.target}`,h=aa(e,i,y,l);c.op==="aggregate"||c.op==="rate_of"?p(c.selection):c.op==="annuity"?d(c.amount,y,h):nr(c)&&s(y,l)&&d(c,y,h)};for(let c of i.invariants??[])u(c);for(let c of i.calculate??[])m(c);for(let c of Object.values(i.actions)){for(let l of c.requires)u(l,c);for(let l of c.calculate??[])m(l,c);for(let[l,y]of Object.entries(c.set??{}))s(l,c)&&d(y,`self.${l}`,aa(e,i,l,c));for(let l of c.moves){let y=t.get(l),h=y?.kind==="block"?y.entries.find(A=>A.key==="amount")?.value:void 0,b="from"in l&&aa(e,i,l.from,c)||e.currency;if(h?.kind==="text"&&n.push(mc(h,"a move amount",b)),"amount"in l&&d(l.amount,"a move amount",b),l.operation==="internal_transfer.post"&&l.boundary?.amount){let A=Object.values(i.actions).flatMap(Z=>Z.moves.map(k=>({reserve:k,item:Z}))).find(({reserve:Z})=>Z.operation==="internal_transfer.reserve"&&`self.${Z.capture}`===l.transfer);o(l.boundary.amount,"a capture amount",A&&"from"in A.reserve&&aa(e,i,A.reserve.from,A.item)||e.currency)}}for(let l of c.invoke??[]){l.guard&&u(l.guard,c);let y=[];if("instrument"in l)y=st(l.instrument);else if("selection"in l)p(l.selection),y=st(l.selection.instrument);else{let h=mt(e,i,l.reference,c.input,c);h?.type==="ref"&&(y=st(h.target))}for(let[h,b]of Object.entries(l.input)){let A=y.map(Z=>{let k=r.get(Z);return k?.actions[l.action]?.input.find(f=>f.name===h)??k?.fields.find(f=>f.name===h)}).find(Z=>Z?.type==="money");A?.type==="money"&&d(b,`${l.action} input ${h}`,A.currency??e.currency)}}}}return n}function hL(e,t){let n=t.parameters.flatMap(a=>{let i=a.value.kind==="default"?a.value.type:a.value;return i.kind==="name"&&i.value==="party"?[a.key]:[]}),r=Fe(e,t.body).get("persons");for(let a of r?.kind==="list"?r.items:r?[r]:[])a.kind==="type"?n.push(a.name):a.kind==="name"&&n.push(a.value);return n}function Oy(e,t){if(!e.round)return"floor";let n=t(e.round),r=wm.safeParse(n.kind==="name"?n.value:void 0);return r.success||U(e.round,`${e.name} cannot round ${n.kind==="name"?n.value:"by that value"}`,"write round: floor, round: ceiling, round: half_even or round: half_up"),r.data}function wv(e,t){let{id:n,objects:r,calculations:a,authored:i,resolve:s,val:o}=e,d=[];for(let p of e.branchRows(t)){let{type:u}=kv(p),m=p.value.kind==="default"?s(p.value.value):void 0,c=qv(e.texts,p,s),l=c.type;if(l==="list"&&u.kind==="call"){let y=u.args[0];y.kind==="type"&&y.name==="ref"&&y.target&&(c.target=Te(s({kind:"name",value:y.target,span:y.span})).replaceAll(".","_"),c.targetKind=r.has(String(c.target))?"object":"instrument")}if(l==="ref"){if(u.kind==="block"){let y=Fe(e.texts,u),h=y.get("targetFamily")??y.get("family"),b;if(h){let A=h.kind==="name"?h.value:Te(h);b=e.resolveFamily(A,h),c.targetFamily=b}if(y.has("target")||y.has("instrument")){let A=y.get("target")??y.get("instrument"),Z=s(A),k;if(Z.kind==="list"){let f=Z.items.map(z=>Te(s(z)).replaceAll(".","_"));k=f.length===1?f[0]:f}else k=Te(Z).replaceAll(".","_");c.target=k,b&&e.checkTargetFamily(k,b,A)}else if(b){let A=e.resolveFamilyInstruments(b,n,h);c.target=A.length===1?A[0]:A}}else{let y=u.kind==="type"?u.target:void 0;y||U(p,"reference needs a target","write ref<object>","field_type_invalid");let[h,...b]=y.split("."),A=e.environment.get(h);if(!A&&c.optional&&e.decl.parameters.some(f=>f.key===h))continue;let k=(A?.kind==="list"?A.items:A?[A]:[]).map(f=>[Te(s(f)).replaceAll(".","_"),...b].join("_"));c.target=y==="self"?n:k.length===1?k[0]:k.length?k:y}c.targetKind=typeof c.target=="string"&&r.has(c.target)?"object":"instrument",u.kind==="type"&&u.owner&&(c.sharedParty=Te(s({kind:"name",value:u.owner,span:u.span})),e.sharedParties.push({instrument:n,decl:e.decl,field:p.key,party:u.owner,targets:[c.target].flat(),targetKind:c.targetKind,site:u}))}else if(l==="account")if(u.kind==="call"){(u.args.length<1||u.args.length>4)&&U(u,"account needs an owner, optional book, mode and key","write account(buyer, claim, contra)","field_type_invalid");let y=u.args[0];y.kind==="call"&&y.name==="adapter"?(y.args.length!==1&&U(y,"adapter needs one binding",'write account(adapter(binding), cash, "premium")',"field_type_invalid"),c.owner={adapter:Te(s(y.args[0]))}):c.owner=Te(s(y)),c.book=u.args[1]?Te(u.args[1]):"cash";let[,,h,b]=u.args,A=h?.kind==="name"&&["contra","debit"].includes(h.value);A&&h.value==="contra"?c.contra=!0:A?c.normal="debit":h&&h.kind!=="text"?U(h,`account takes contra, debit or a quoted key third, not ${h.kind==="name"?h.value:h.kind}`,'write account(owner, book, "key") or account(owner, book, debit, "key")',"field_type_invalid"):h&&(c.key=Te(h)),b&&!A?U(b,"account takes one key; a fourth argument follows only contra or debit",'write account(owner, book, "key") or account(owner, book, debit, "key")',"field_type_invalid"):b&&b.kind!=="text"?U(b,"the account key is quoted text",'write account(owner, book, contra, "key")',"field_type_invalid"):b&&(c.key=Te(b))}else u.kind==="type"&&u.owner?(c.owner=u.owner==="self"?"self":Te(s({kind:"name",value:u.owner,span:p.span})),c.book="cash"):U(p,"account needs an owner","write account of buyer or account of self","field_type_invalid");if(m&&!(m.kind==="name"&&m.value==="runtime"))if(m.kind==="call"){let y=m.name==="aggregate"?[]:m.args.map(o),h=p.key;m.name==="aggregate"&&m.args.length===2?a.push({target:h,op:"aggregate",selection:e.data(m.args[0]),measure:Te(m.args[1])==="count"?"count":{sum:Te(m.args[1])}}):m.name==="at"&&y.length===2?a.push({target:h,op:"at",list:e.path(m.args[0]),position:y[1]}):m.name==="ratio"&&y.length===3?a.push({target:h,op:"ratio",amount:y[0],numerator:y[1],denominator:y[2],rounding:Oy(m,s)}):m.name==="rate"&&y.length===2?a.push({target:h,op:"rate",base:y[0],bps:y[1],rounding:Oy(m,s)}):m.name==="sum"||m.name==="minimum"?a.push({target:h,op:m.name,values:y}):m.name==="subtract"&&y.length>=2?a.push({target:h,op:"subtract",base:y[0],subtract:y.slice(1)}):m.name==="multiply"&&y.length===2?a.push({target:h,op:"multiply",amount:y[0],units:y[1]}):m.name==="divide"&&y.length===2?a.push({target:h,op:"divide",amount:y[0],divisor:y[1],rounding:Oy(m,s)}):["before","after"].includes(m.name)&&y.length===2?a.push({target:h,op:"shift",date:y[0],milliseconds:y[1],direction:m.name}):m.name==="after"&&y.length===3?a.push({target:h,op:"step",date:y[0],period:y[1],times:y[2]}):U(m,`unknown calculation ${m.name}`,"use rate, sum, minimum, subtract, multiply, divide, before or after","unknown_calculation"),i.set(a.at(-1),m)}else l==="enum"&&m.kind==="name"?c.value=m.value:l==="money"&&m.kind==="name"?a.push({target:p.key,op:"sum",values:[o(m)]}):(c.value=Wt(m,String(l)),l==="money"&&Hy(m,c.currency??gr,p.key));i.set(c,p.value),d.push(c)}return d}function My(e,t){let{fields:n,calculations:r,actionTargets:a}=e;if(ft(t))return Li(t).every(p=>My(e,p));if(!("field"in t))return!0;let[i,s,...o]=t.field.split("."),d=n.find(p=>p.name===s);return i==="self"&&!o.length&&!!d&&!a.has(s)&&(!d.optional||"value"in d||r.some(p=>p.target===s))}function Iv(e,t){return t.kind==="block"?e.data(t):e.val(t)}function fL(e,t,n,r){let a=new Map(n);for(let[i,s]of Lc(e,t.body)){if(!i.startsWith("economics "))continue;let o=i.slice(10);/^[A-Za-z]\w*$/.test(o)||je(s,"economics_name_invalid",`economics ${o} is not a name`,"name the body with one word, such as economics release { ... }"),s.value.kind!=="block"&&je(s,"economics_name_invalid",`economics ${o} needs a body`,`write economics ${o} { purpose: earning, sourceParty: payer }`);let d=n.get(o);d&&Bn(e,`economics ${o} is declared twice`,d,s,"reference the parent's body, or give this one another name",{code:"economics_name_taken"}),(o==="unclassified"||r.has(o))&&je(s,"economics_name_taken",`economics ${o} has the name of ${o==="unclassified"?"the unclassified branch":`the tunable ${o}`}`,`rename the body, such as economics ${o}_purpose`),a.set(o,s)}return a}function bL(e,t,n){let r=e.economics.get(t.value);if(!r)return je(t,"economics_unknown",`economics ${t.value} is not declared in ${e.decl.name}.${en(t.value,[...e.economics.keys()])}`,e.economics.size?`reference one of ${[...e.economics.keys()].join(", ")}, or declare economics ${t.value} { ... } in the instrument`:`declare economics ${t.value} { purpose: ..., sourceParty: ... } in the instrument`);let a=Se(r.value).entries.map(s=>s.key),i=a.filter(s=>_L.includes(s));return n&&(!i.length||i.length!==a.length)&&je(t,"economics_shape_mismatch",`this move charges a fee, so economics ${t.value} takes payee, fee and tax legs; it has ${a.join(", ")}`,"reference a body shaped { payee: { ... }, fee: { ... }, tax: { ... } }, or drop the fee"),!n&&i.length&&je(t,"economics_shape_mismatch",`economics ${t.value} has ${i.join(", ")} legs for a fee, and this move charges no fee`,"reference a body with purpose and sourceParty, or add fee to the move"),r.value}function xL(e){for(let t of e.moves){let n=t.economics&&jv.get(t.economics);if(!n)continue;let r=JSON.stringify(n.amount),a=e.moves.filter(i=>i!==t&&"amount"in i&&JSON.stringify(i.amount)===r);(a.length!==1||!a[0].economics)&&U(n.expr,a.length>1?"taxOn matches more than one move":"taxOn names no move with economics in this action","name the amount of exactly one other classified move of the action"),t.economics={...t.economics,taxOn:a[0].key}}}function Ac(e,t){let{resolve:n,data:r,isParty:a}=e;if(t){let l=n(t);if(l.kind==="name"&&l.value==="unclassified")return;let y=Fe(e.texts,Se(n(t)));if(y.has("recipient")){for(let A of y.keys())["recipient","company","participant"].includes(A)||U(t,`unknown economics choice ${A}`,"use recipient, company and participant");let h=String(r(y.get("recipient")));(!a(h)||!y.has("company")||!y.has("participant"))&&U(t,"economics choice needs a bound recipient and both branches","declare recipient, company and participant");let b=h==="operator"||h==="programOperator"||e.document.parties[h]?.role==="program_operator";return Ac(e,y.get(b?"company":"participant"))}}let i=t?Fe(e.texts,Se(n(t))):void 0;if(i)for(let l of i.keys())["purpose","sourceParty","reversalOf","taxOn"].includes(l)||U(t,`unknown economics term ${l}`,"use purpose, sourceParty, reversalOf or taxOn");let s=i?.get("purpose"),o=i?.get("sourceParty");i&&(!s||!o)&&U(t,"economics needs purpose and sourceParty","declare both economics fields");let d=s?String(r(s)):void 0;d&&!Zo.includes(d)&&U(s,`unknown economic purpose ${d}`,"choose a declared economic purpose");let p=o?String(r(o)):void 0,u=p&&!a(p)?e.reachedParty(p):void 0;if(u&&(e.attachmentInfo.parties[p]=u,p="role"in u?u.role:u.party),p&&!a(p)&&U(o,`unknown source party ${p}`,"bind an authored party","unknown_party"),!i)return;let m={purpose:d,sourceParty:p,...i.has("reversalOf")?{reversalOf:e.path(i.get("reversalOf"))}:{}},c=i.get("taxOn");return c&&jv.set(m,{amount:e.val(c),expr:c}),m}function zv(e,t,n){let r=Fe(e.texts,Se(t));for(let u of r.keys())["adapter","operation","amount","refundOf","items"].includes(u)||U(t,`boundary has no ${u}`,"name adapter, operation, amount, refundOf or items");let a=r.get("adapter");a||U(t,"boundary needs an adapter","name a bound ADL adapter");let i=Te(e.resolve(a)),s=r.get("operation"),o=s?Te(s):void 0,d=vL[n]??[];return n!=="internal_transfer.reserve"&&!o&&U(t,`a ${n.slice(18)} on a boundary hold names its operation`,`write boundary { adapter: ${i}, operation: ${d[0]} }`),o&&!d.includes(o)&&U(s,`a ${n.slice(18)} cannot ${o} at the provider`,`name ${d.join(" or ")}`),r.has("amount")&&o!=="capture"&&U(t,"only a capture names an amount","remove amount"),r.has("items")&&(n!=="internal_transfer.reserve"||o)&&U(r.get("items"),"only a payout carries items","move items to a reserve that names no operation"),!(n==="internal_transfer.reserve"&&!o&&!r.has("items")&&r.has("refundOf"))&&r.has("refundOf")!==(o==="refund")&&U(t,"a refund names the authorization it returns money from, and only a refund or a single payout does","write refundOf: self.<authorization receipt>"),{adapter:i,...o?{operation:o}:{},...r.has("amount")?{amount:e.val(r.get("amount"))}:{},...r.has("refundOf")?{refundOf:e.path(r.get("refundOf"))}:{},...r.has("items")?{items:e.data(r.get("items"))}:{}}}function $L(e,t,n,r){let{name:a,action:i,calculations:s}=t,{attachmentInfo:o,fields:d,calculations:p,authored:u,resolve:m,moneyPath:c,data:l}=e,y=i.moves.length,h=Fe(e.texts,Se(n)),b=h.has("operation")?String(l(h.get("operation"))):"internal_transfer.create";if(h.has("boundary")&&e.boundaryOff(h.get("boundary"))&&h.delete("boundary"),b==="internal_transfer.reserve"&&!h.has("capture")){h.has("boundary")||U(n,"reserve needs a receipt field","add capture: receipt_name");let P=`${a}Receipt`;d.some(T=>T.name===P)&&U(n,"boundary receipt name is already used","name each reservation with an explicit capture"),d.push({name:P,type:"text",optional:!0}),e.boundaryReceipts.set(a,P),h.set("capture",{kind:"text",value:P,span:n.span})}(b==="internal_transfer.post"||b==="internal_transfer.void")&&!h.has("transfer")&&U(n,"post and void need a receipt","add transfer: receipt_name");let A=h.has("key")?String(l(h.get("key"))):`move${r+1}`,Z=h.get("economics"),k=Z?.kind==="name"?bL(e,Z,h.has("fee")):Z,f=h.has("fee")&&k?Fe(e.texts,Se(m(k))):void 0;if(f)for(let P of f.keys())["payee","fee","tax"].includes(P)||U(k,`unknown fee economics leg ${P}`,"declare payee, fee or tax economics separately");let z=Ac(e,f?f.get("payee"):k);if(b==="internal_transfer.create"||b==="internal_transfer.reserve"){let P=h.get("amount"),T=h.get("from"),$=h.get("to");if(P){let H=m(P);if(H.kind==="name"&&H.value.startsWith("subject.")){let x=H.value.split(".")[1],w=i.subject?.requirements.find(v=>v.field.name===x);w&&w.field.type!=="money"&&U(P,`move amount subject.${x} must have type money`,"use a money field")}}if(h.has("shares")){(!P||!T||b!=="internal_transfer.create"||h.has("fee"))&&U(n,"split needs a posted amount and source","declare amount, from and shares without a fee");let H=[...Fe(e.texts,Se(m(h.get("shares"))))];(!H.length||H.length>64)&&U(n,"split needs 1 to 64 recipients","name the receiving parties and percentages","split_recipients");let x=0,w=[],v=Iv(e,P),L=!My(e,v);for(let[j,[g,I]]of H.entries()){let O=m({kind:"name",value:g,span:I.span});(O.kind!=="name"||!e.isParty(O.value)||I.kind!=="percent")&&U(I,"split needs party percentages","write party_name: 70%"),x+=Number(Wt(I));let D=un.includes(O.value);if(o&&(D||e.document.parties[O.value]?.kind==="business")&&!Object.values(o.parties).some(C=>"role"in C&&C.role===O.value||"party"in C&&C.party===O.value)){let C="splitRecipient";for(let E=2;Object.hasOwn(o.parties,C);E++)C=`splitRecipient${E}`;o.parties[C]=D?{role:O.value}:{party:O.value}}let _=`${a}_${A}_share${j+1}`;d.some(C=>C.name===_)&&U(n,"split field name conflicts","rename the move key"),d.push({name:_,type:"money",...L?{optional:!0}:{}}),(L?s:p).push(j===H.length-1&&w.length?{target:_,op:"subtract",base:v,subtract:[...w]}:{target:_,op:"rate",base:v,bps:{literal:Wt(I)},rounding:"floor"});let S={field:`self.${_}`};w.push(S),i.moves.push({key:`${A}_${j+1}`,operation:"internal_transfer.create",...z?{economics:z}:{},amount:S,from:c(T),to:`party.${O.value}`}),e.splitMoves.add(i.moves.at(-1))}x!==Cy&&U(n,"split percentages must sum to 100%","give the recipients exactly 100% together","split_not_whole");for(let j of i.moves.slice(y))u.set(j,n);return}(!P||!T||!$)&&U(n,"move needs amount, from and to","declare all three move operands","move_incomplete");let q={key:A,operation:b,...z?{economics:z}:{},...h.has("capture")?{capture:String(l(h.get("capture")))}:{},amount:Iv(e,P),from:c(T),to:c($)},R=h.get("fee");R?(b!=="internal_transfer.create"&&U(n,"fees settle with a posted transfer","declare a separate posted settlement after releasing the reservation"),wL(e,t,n,R,q,f)):i.moves.push(b==="internal_transfer.reserve"?{...q,operation:b,capture:String(l(h.get("capture"))),...h.has("boundary")?{boundary:zv(e,h.get("boundary"),b)}:{}}:{...q,operation:b})}else b==="internal_transfer.post"||b==="internal_transfer.void"?i.moves.push({key:A,operation:b,...z?{economics:z}:{},transfer:e.path(h.get("transfer")),...h.has("capture")?{capture:String(l(h.get("capture")))}:{},...h.has("boundary")?{boundary:zv(e,h.get("boundary"),b)}:{}}):U(n,`unknown transfer instruction ${b}`,"choose create, reserve, post, or void from internal_transfer");for(let P of i.moves.slice(y))u.set(P,n)}function wL(e,{name:t,action:n,calculations:r},a,i,s,o){let{document:d,fields:p,calculations:u,resolve:m}=e,{key:c}=s,l=Fe(e.texts,Se(m(i)));for(let x of l.keys())["seller","buyer","tax"].includes(x)||U(i,`unknown fee term ${x}`,"choose seller or buyer, and optional tax","fee_shape");let y=l.has("seller")?"seller":"buyer";l.has("seller")===l.has("buyer")&&U(i,"fee needs exactly one paying party","write seller: 1% or buyer: 1%","fee_shape");let h=l.get(y);y==="buyer"&&p.some(x=>`self.${x.name}`===s.from&&x.type==="account"&&x.owner==="self")&&U(h,`a buyer fee cannot come from \`${s.from.slice(5)}\`, which holds only the moved amount`,"use a seller fee, which comes out of the held amount");let b=h.kind==="capped"?h.rate:h;b.kind!=="percent"&&U(b,"fee rate needs a percentage","write a percentage such as 1%","fee_shape");let A=`${t}_${c}`,Z=!My(e,s.amount),k=(x,w,v)=>{let L=A+"_"+x;return p.some(j=>j.name===L)&&U(a,`generated fee field ${L} conflicts with a field`,"rename the authored field or move key"),p.push({name:L,type:"money",label:w,...Z?{optional:!0}:{}}),(Z?r:u).push({...v,target:L}),{field:`self.${L}`}},f=`${y==="seller"?"Seller":"Buyer"} fee`,z=k("feeGross",h.kind==="capped"?`${f} before cap`:f,{op:"rate",base:s.amount,bps:{literal:Wt(b)},rounding:"floor"}),P=z;h.kind==="capped"&&(h.cap.kind!=="money"&&U(h.cap,"fee cap needs money",`write an amount such as 750 ${gr}`,"fee_shape"),P=k("fee",f,{op:"minimum",values:[z,{literal:Wt(h.cap)}]}));let T=l.get("tax");if(T&&T.kind!=="percent"&&U(T,"tax needs a percentage of the fee","write tax: 15%","fee_shape"),y==="seller"&&(!("literal"in s.amount)||Zi({name:"amount",type:"money"},er).safeParse(s.amount.literal).success)){let x=BigInt(Cy),w=BigInt(Number(Wt(b))),v=BigInt(T?Number(Wt(T)):0),L=h.kind==="capped"?BigInt(String(Wt(h.cap))):void 0,j=L===void 0&&w*(x+v)>x*x;if("literal"in s.amount){let g=BigInt(String(s.amount.literal)),I=g*w/x,O=L!==void 0&&L<I?L:I;j=O+O*v/x>g}j&&je(h,"seller_fee_exceeds_amount","seller fee plus tax exceeds the base amount","lower the seller fee, cap or tax so the combined charge fits within the amount")}let $=T?k("tax","Fee tax",{op:"rate",base:P,bps:{literal:Wt(T)},rounding:"floor"}):void 0,q=$?[P,$]:[P];k("debit","Payer debit",{op:"sum",values:y==="buyer"?[s.amount,...q]:[s.amount]});let R=y==="seller"?k("net","Amount after fee",{op:"subtract",base:s.amount,subtract:q}):s.amount;for(let[x,w]of[["programOperator","program_operator"],["programTax","tax_payable"]])d.parties[x]&&d.parties[x].role!==w&&U(a,`${x} is reserved for fees`,"rename this party","name_reserved"),d.parties[x]={kind:"business",role:w};n.moves.push({...s,operation:"internal_transfer.create",amount:R}),n.moves.push({key:c+"Fee",...o?.has("fee")?{economics:Ac(e,o.get("fee"))}:{},operation:"internal_transfer.create",amount:P,from:s.from,to:"party.programOperator"});let H=o?.has("tax")?Ac(e,o.get("tax")):void 0;$&&n.moves.push({key:c+"Tax",...H?{economics:o?.has("fee")?{...H,taxOn:c+"Fee"}:H}:{},operation:"internal_transfer.create",amount:$,from:s.from,to:"party.programTax"})}function IL(e,t,n){let r,a,i;for(let s of e.instruments){let o=p=>{let u=k=>{if(!k||typeof k!="object")return;let f=k;if(typeof f.field=="string")return mt(e,s,f.field,p?.input,p)?.type;if("literal"in f)return n.has(f)?"percent":typeof f.literal=="number"?"integer":typeof f.literal=="string"&&/^-?\d+$/.test(f.literal)?"money":void 0;if(["rate","ratio","compound"].includes(f.op))return"money";if(f.op==="between")return f.unit==="milliseconds"?"duration":"integer";if(f.op==="multiply"||f.op==="divide")return u(f.amount);for(let z of["values","base","then","otherwise"]){let P=f[z],T=u(Array.isArray(P)?P[0]:P);if(T)return T}},m=k=>{if(Array.isArray(k))return k.forEach((T,$)=>k[$]=m(T)),k;if(!k||typeof k!="object")return k;let f=k;for(let T of Object.keys(f))f[T]=m(f[T]);let z=b(f),P=t.get(f);return z!==f&&P&&z&&typeof z=="object"&&t.set(z,P),z},c,l=k=>u(k)==="percent"||!!k&&typeof k=="object"&&t.get(k)?.kind==="percent",y=k=>!!k&&typeof k=="object"&&"literal"in k&&typeof k.literal=="number"&&k.literal!==0&&!l(k),h=k=>k.some(l)?k.find(y):void 0,b=k=>{let f=k.kind==="compare"?[k.left,k.right]:k.op==="ratio"?[k.numerator,k.denominator]:k.op==="subtract"?[k.base,...Array.isArray(k.subtract)?k.subtract:[]]:["sum","minimum","maximum"].includes(k.op)&&Array.isArray(k.values)?k.values:[],z=h(f);z&&(i??=t.get(z)??t.get(k));let P=Array.isArray(k.subtract)?k.subtract:[];if(k.op==="subtract"&&P.length===1&&u(k.base)==="date"&&u(P[0])==="date"){let{base:T,subtract:$,...q}=k;return{...q,op:"between",from:P[0],to:T,unit:"milliseconds",rounding:"floor"}}if(k.op==="multiply"){let[T,$]=[u(k.amount),u(k.units)],{rounding:q,...R}=k,H={...R};return delete H.amount,delete H.units,T==="percent"||$==="percent"?{...H,op:"rate",base:T==="percent"?k.units:k.amount,bps:T==="percent"?k.amount:k.units,rounding:q??"floor"}:T==="integer"&&($==="money"||$==="duration")?{...R,amount:k.units,units:k.amount}:(q!==void 0&&(c??=t.get(k)),R)}if(k.kind==="state"&&typeof k.reference=="string"){let T=mt(e,s,k.reference,p?.input,p),$=Array.isArray(k.states)?k.states:[];if(T&&T.type!=="ref"&&$.length){let q=$.map(R=>({kind:"compare",left:{field:k.reference},operator:"==",right:{literal:R}}));return q.length===1?q[0]:{kind:"any",of:q}}}return k};return{shape:m,calculations:k=>{for(let[f,z]of(k??[]).entries()){c=void 0;let P=k[f]=m(z);c&&!JSON.stringify(P).includes('"rounding"')&&(r??={site:c,target:P.target});let T=t.get(P);if(P.op==="between"&&P.unit==="milliseconds"&&T&&u({field:`self.${P.target}`})==="integer"){let $=q=>q&&typeof q=="object"&&"field"in q?String(q.field):"the earlier date";a??={site:T,target:P.target,from:$(P.from),to:$(P.to)}}}},amounts:k=>{for(let f of k)"amount"in f&&ft(f.amount)&&(c=void 0,f.amount=m(f.amount),c&&!JSON.stringify(f.amount).includes('"rounding"')&&(r??={site:c,target:`move ${f.key}`}))}}},d=o();d.calculations(s.calculate),d.shape(s.invariants);for(let p of Object.values(s.actions)){let{shape:u,calculations:m,amounts:c}=o(p);m(p.calculate);for(let l of[p.requires,p.set,p.invoke])u(l);c(p.moves)}}i&&je(i,"percent_whole_literal","a whole number stands beside a percent, and a percent is not counted in whole units","write the number as a percent, such as 100% for the whole"),a&&je(a.site,"date_difference_count",`${a.target} is an integer, and one date minus another is a duration`,`write days between(${a.from}, ${a.to}) or months between(${a.from}, ${a.to})`),r&&je(r.site,"round_unread",`round: on ${r.target} rounds nothing: its only product is a whole count`,"delete round:, or divide or take a rate on the line so it has a quotient to round")}function Ty(e,t=!1){switch(e.kind){case"compare":return ft(e.left)||ft(e.right)?void 0:[[{kind:"compare",left:e.left,operator:t?zL[e.operator]:e.operator,right:e.right}]];case"state":return;case"not":return Ty(e.condition,!t);case"all":case"any":{let n=e.of.map(a=>Ty(a,t));if(n.some(a=>!a))return;if(e.kind==="any"!==t){let a=n.flatMap(i=>i);return a.length>Zy?void 0:a}let r=[[]];for(let a of n){if(r.length*a.length>Zy)return;r=r.flatMap(i=>a.map(s=>[...i,...s]))}return r}}}function qL(e,t){let n=!0,r=0,a=e.instruments.reduce((i,s)=>i+s.actionOrder.length,0);for(;n&&r<a;){n=!1,r++;for(let i of e.instruments)for(let[s,o]of Object.entries(i.actions))for(let d of o.invoke??[]){let p=[];if("instrument"in d)p=[d.instrument];else if("selection"in d)p=Array.isArray(d.selection.instrument)?d.selection.instrument:[d.selection.instrument];else if("reference"in d){let u=mt(e,i,d.reference,o.input,o);u?.type==="ref"&&u.targetKind==="instrument"&&(p=Array.isArray(u.target)?u.target:[u.target])}for(let u of p){let m=e.instruments.find(c=>c.id===u);if(m&&i.subject&&m.subject&&i.subject===m.subject){let c=m.actions[d.action];if(!c?.subject)continue;o.subject||(o.subject={requirements:[],adapters:[]});for(let l of d.guard?[]:c.subject.adapters)o.subject.adapters.some(y=>y.binding===l.binding)||(o.subject.adapters.push(l),n=!0);for(let l of c.subject.requirements){let y=l.objectField??l.field.name,h=o.subject.requirements.find(z=>(z.objectField??z.field.name)===y),b=z=>{if(!("field"in z)||!z.field.startsWith("subject."))return z;let P=o.subject?.requirements.find(T=>T.field.name===z.field.slice(8));return{field:`subject.${P?.objectField??P?.field.name??z.field.slice(8)}`}},A=z=>{let P=[z.left,z.right].flatMap(T=>"field"in T?[mt(e,i,T.field,o.input,o)?.type]:[]).find(T=>T==="money"||T==="date");return{instrument:i.id,action:s,guard:{...z,left:b(z.left),right:b(z.right)},...P==="money"||P==="date"?{valueType:P}:{}}},Z=d.guard?Ty(d.guard):void 0,k=Z?Z.flatMap(z=>(l.when??[[]]).map(P=>{let T=z.map(A);return[...T,...P.filter($=>T.every(q=>Vt($)!==Vt(q)))]})):void 0,f=k&&k.length<=Zy&&k.every(z=>z.length<=kL)?k:l.when;if(h)if(Qa(h.field,l.field)){if(h.when)if(!f)delete h.when,n=!0;else for(let z of f)h.when.some(P=>Vt(P)===Vt(z))||(h.when.push(z),n=!0)}else{let z=t.get(h),P=t.get(l);throw new St({code:"subject_field_conflict",message:`${z.message} conflicts with ${P.message}: conflicting requirement '${y}'`,fix:"give invoked actions matching requirement definitions",span:z.span,source:z.source,related:[z,P]})}else{let z={field:{...l.field,name:y},...f?{when:f.map(P=>[...P])}:{}};o.subject.requirements.push(z),t.set(z,t.get(l)),n=!0}}}}}}}function LL(e,t,n,r,a,i){let s=new Map(t.instruments.map($=>[$.id,$])),o=($,q,R)=>{let H=n.get($);return H?.kind==="block"?H.entries.find(x=>x.key===q)?.value??H:H?.kind==="list"&&Array.isArray($)?H.items.length===$.length?H.items[Number(q)]:H:H??R},d=($,q,R)=>{let H=n.get($),x=H?.kind==="block"?H.entries.find(w=>w.key===q):void 0;return x?{...x,span:{start:x.span.start,end:x.span.start+q.length}}:R},p=$=>["id","now","createdAt","productRevision","status",...$.subject?["subject"]:[]],u=$=>[...Object.keys(t.parties),...$.subject?un:[],...($.persons??[]).map(q=>q.name)],m=$=>{if($.type==="account")return Object.keys(Lo);if($.type!=="ref")return[];let[q]=[$.target].flat(),R=$.targetKind==="object"?t.objects.find(H=>H.id===q):s.get(q);return R?[...R.fields.map(H=>H.name),..."lifecycle"in R?p(R):[]]:[]},c=($,q,R)=>{let H=u(R);H.includes($)||U(q,`\`${$}\` is not a declared party.${en($,H)}`,un.includes($)?`Declare a party parameter such as \`holder: party\` on the instrument, use it here, and bind \`holder: ${$}\` where you attach it.`:`Declare it with \`party ${$}: business\`, or name a declared party (${H.join(", ")}).`,"unknown_party")},l=($,q,R,H)=>{let x=H.map(w=>w.name);x.includes($)||U(q,`\`${$}\` is not an input of \`${R}\`.${en($,x)}`,`Declare \`${$}\` in the input of \`${R}\`${x.length?`, or use one of ${x.join(", ")}`:""}.`,"unknown_field")},y=($,q,R=!1)=>{let H=[...s.keys(),...R?t.objects.map(w=>w.id):[]],x=R?"instrument or object":"instrument";H.includes($)||U(q,`\`${$}\` is not a declared ${x}.${en($,H)}`,`Name a declared ${x}.`)},h=($,q,R)=>{let{inst:H,action:x}=R,w=$.split("."),v=O=>mt(t,H,w.slice(0,O).join("."),x?.input,x);if(v(w.length)||w[0]==="subject"||w[0]==="party"&&w[1]&&(c(w[1],q,H),!v(2)))return;["self","input","party"].includes(w[0])||w.unshift("self");let L=2;for(;L<=w.length&&v(L);)L++;if(L>w.length)return;let j=w[L-1];if(L>2){let O=w.slice(0,L-1).join("."),D=m(v(L-1));U(q,`\`${j}\` is not a field of \`${O}\`.${en(j,D)}`,D.length?`Use one of ${D.join(", ")}.`:`\`${O}\` has no fields.`,"unknown_field")}if(w[0]==="input")return l(j,q,R.label,x?.input??[]);let g=r.get(H).name,I=H.fields.map(O=>O.name);U(q,`\`${j}\` is not a field or party of \`${g}\`.${en(j,[...I,...p(H),...u(H)])}`,`Use a field declared in \`${g}\` (${I.join(", ")}) or a declared party (${u(H).join(", ")}).`,"unknown_field")},b=$=>({inst:$,label:r.get($).name}),A=$=>{let q=[$.instrument].flat(),R=$.family?a(`${$.family.module}.${$.family.exportPath}`):void 0;return!R||!Fe(e,Se(Fe(e,R.body).get("fields"))).has($.reference)?q:q.filter(H=>mt(t,s.get(H),`self.${$.reference}`))},Z=($,q)=>{let R=s.get($),H=s.get(q);return!!R&&!!H&&r.get(R)===r.get(H)},k=($,q,R)=>A($).filter(H=>{let x=s.get(H);if(!x)return!0;let w=mt(t,q,$.anchor,R?.input,R),v=mt(t,x,`self.${$.reference}`);if(w?.type!=="ref"||v?.type!=="ref")return!0;let L=[w.target].flat();return![v.target].flat().every(g=>!L.includes(g)&&L.some(I=>Z(I,g)))});for(let $ of t.instruments)for(let q of Object.values($.actions))q.calculate&&(q.calculate=q.calculate.map(R=>R.op==="aggregate"&&R.measure==="count"&&!k(R.selection,$,q).length?{target:R.target,op:"sum",values:[{literal:0}]}:R)),q.requires=q.requires.map(R=>R.kind==="aggregate"&&R.measure==="count"&&!k(R.selection,$,q).length?{kind:"compare",left:{literal:0},operator:R.operator,right:R.value}:R);let f=($,q,R)=>{T($.overlaps,"overlaps",o($,"overlaps",q),R),T($.anchor,"anchor",o($,"anchor",q),R),T($.where,"where",o($,"where",q),R);let H=k($,R.inst,R.action);H.length&&H.length<[$.instrument].flat().length&&($.instrument=H);let x=[$.instrument].flat().flatMap(j=>s.get(j)?.lifecycle.states??[]),w=o($,"instrument",q),v="kind"in w?w.kind==="list"?w.items:[w]:[],L=[...x,...v.flatMap(j=>{if(j.kind!=="call"||j.name!=="all")return[];let g=a(Te(j.args[0])),I=g&&Fe(e,Se(Fe(e,g.body).get("lifecycle"))).get("states");return I?.kind==="list"?I.items.map(Te):[]})];for(let j of x.length?$.states:[])L.includes(j)||U(o($,"states",q),`\`${j}\` is not a state of any instrument this selection names.${en(j,L)}`,`Use one of ${[...new Set(L)].join(", ")}.`,"unknown_state");x.length&&$.states.some(j=>x.includes(j))&&($.states=$.states.filter(j=>x.includes(j)));for(let j of[$.instrument].flat()){y(j,o($,"instrument",q));let g=b(s.get(j)),I=(O,D)=>h(O.startsWith("self.")?O:`self.${O}`,D,g);for(let O of Object.keys($.where??{}))I(O,d($.where,O,q));if(I($.reference,o($,"reference",q)),$.order?.forEach((O,D)=>I(O,o($.order,D,q))),$.overlaps)for(let O of["start","end"])I($.overlaps[O],o($.overlaps,O,q));$.window&&I($.window.field,o($.window,"field",q))}},z=($,q,R)=>{let H="range"in $?$.range?.bind:void 0;for(let[v,L]of Object.entries($))v!=="input"&&T(L,v,o($,v,q),R);for(let[v,L]of Object.entries($.input))(!("field"in L)||L.field!==H)&&T(L,v,o($.input,v,q),R);"instrument"in $&&y($.instrument,o($,"instrument",q));let x="reference"in $?mt(t,R.inst,$.reference,R.action?.input,R.action):void 0,w="instrument"in $?[$.instrument]:"selection"in $?[$.selection.instrument].flat():x?.type==="ref"&&x.targetKind==="instrument"?[x.target].flat():[];for(let v of w){let L=s.get(v);if(!L)continue;let j=L.actions[$.action];j||U(o($,"action",q),`\`${$.action}\` is not an action of \`${v}\`.${en($.action,L.actionOrder)}`,`Use one of ${L.actionOrder.join(", ")}.`,"unknown_action");for(let g of Object.keys($.input))l(g,d($.input,g,q),`${v}.${$.action}`,j.input)}},P=["field","reference","anchor","at","list","from","to","transfer","subject","instruction","installment","recipient","dueAt","fields"],T=($,q,R,H)=>{if(typeof $=="string"){q==="party"&&c($,R,H.inst),q==="target"&&h(`self.${$}`,R,H),P.includes(q)&&h($,R,H);return}if(!(!$||typeof $!="object")){if(Array.isArray($))return $.forEach((x,w)=>T(x,q,o($,w,R),H));if(q==="selection")return f($,R,H);if(q==="boundary"&&"items"in $){let{items:x,...w}=$;f(x,o($,"items",R),H);for(let[v,L]of Object.entries(w))T(L,v,o($,v,R),H);return}if($.kind==="approval"){let x=$,w=o(x,"by",R);x.by?.forEach((v,L)=>c(v,o(x.by,L,w),H.inst)),x.amount&&h(x.amount,o(x,"amount",R),H);return}if(q==="invoke")return z($,R,H);if(q==="set")for(let x of Object.keys($))h(`self.${x}`,d($,x,R),H);for(let[x,w]of Object.entries($))T(w,x,o($,x,R),H)}};for(let $ of t.instruments){let q=r.get($),R=b($);ot(i,()=>{for(let H of[...$.fields,...Object.values($.actions).flatMap(x=>x.input)])if("target"in H&&H.target!==void 0)for(let x of[H.target].flat())y(x,o(H,"target",q),!0)}),ot(i,()=>T($.calculate,"calculate",q,R)),ot(i,()=>T($.invariants,"invariants",q,R));for(let[H,x]of Object.entries($.actions))ot(i,()=>{for(let[w,v]of Object.entries(x))w!=="input"&&w!=="subject"&&T(v,w,o(x,w,q),{inst:$,label:`${q.name}.${H}`,action:x})})}}function jL(e,t,n){let r=new Map;e.instruments.forEach((a,i)=>{let s=`$.instruments[${i}]`,o=m=>{n.push({path:`${s}.actions.${m}`,value:a.actions[m],schema:tr},{path:`${s}.lifecycle.transitions.${m}`,value:a.lifecycle.transitions[m],schema:Do.shape.transitions.valueType}),delete a.actions[m],delete a.lifecycle.transitions[m]};if(!a.lifecycle.states.includes(a.lifecycle.initial)||Object.values(a.lifecycle.transitions).some(m=>m.from.some(c=>!a.lifecycle.states.includes(c))||m.to!=="preserve"&&!a.lifecycle.states.includes(m.to)))return;let d=t.has(a.id);for(let[m,c]of Object.entries(a.actions)){let l=y=>{if(ft(y))return;if("literal"in y)return y.literal;let h=a.fields.find(b=>`self.${b.name}`===y.field);return h&&"value"in h?h.value:void 0};c.requires.some(y=>{if(y.kind!=="compare")return!1;let h=l(y.left),b=l(y.right);return h===void 0||b===void 0?!1:y.operator==="=="?h!==b:y.operator==="!="?h===b:!1})&&(o(m),d=!0)}if(!d)return;let p=new Set([a.lifecycle.initial]);for(let m=0;m<a.lifecycle.states.length;m++)for(let c of Object.values(a.lifecycle.transitions))c.from.some(l=>p.has(l))&&c.to!=="preserve"&&p.add(c.to);for(let[m,c]of Object.entries(a.lifecycle.transitions))if(!c.from.every(l=>p.has(l))){if(!c.from.some(l=>p.has(l))){o(m);continue}c.from.forEach((l,y)=>{p.has(l)||n.push({path:`${s}.lifecycle.transitions.${m}.from[${y}]`,value:l,schema:Do.shape.states.element})}),c.from=c.from.filter(l=>p.has(l))}r.set(a.id,new Set(a.lifecycle.states.filter(m=>!p.has(m)))),a.lifecycle.states.forEach((m,c)=>{p.has(m)||n.push({path:`${s}.lifecycle.states[${c}]`,value:m,schema:Do.shape.states.element})}),a.lifecycle.states=a.lifecycle.states.filter(m=>p.has(m));let u=a.lifecycle.ends?.filter(m=>p.has(m));u?.length?a.lifecycle.ends=u:delete a.lifecycle.ends,a.actionOrder=a.actionOrder.filter(m=>a.actions[m])});for(let a of e.instruments)for(let i of Object.values(a.actions))for(let s of i.requires){if(s.kind!=="state")continue;let o=a.fields.find(d=>`self.${d.name}`===s.reference);o?.type==="ref"&&(s.states=s.states.filter(d=>!(typeof o.target=="string"?[o.target]:o.target).some(p=>r.get(p)?.has(d))))}}function Av(e,t,n){let{program:r,sources:a,names:i,objects:s,assignments:o,attachmentSubjects:d,placements:p,exposedCreates:u,exposedActions:m,invokedActions:c}=e,l=e.attachments,{declarationSources:y,templateAt:h,requireTemplate:b}=e.headers,A=e.headers.resolveFamily,Z=a.get("program");js=[],Mi=new Map,gr=r.currency;let k=[...e.diagnostics],f,z=_=>f!==void 0&&H()||{ok:!1,diagnostics:[..._]},P=new WeakMap,T=[],$=new Map,q=[],R=()=>q.flatMap(({path:_,value:S,schema:C})=>(C.safeParse(S).error?.issues??[]).map(E=>({code:"UDL1003",path:_+E.path.map(F=>typeof F=="number"?`[${F}]`:`.${String(F)}`).join(""),message:E.message,fix:"use the UDL typed clause shape"}))),H=()=>{let _=Mo(I),S=[...R(),..._.ok?[]:_.issues];return S.length?x(S):void 0},x=_=>{let S=k.slice(0,f),C=new Set;for(let E of _){let F=/^\$\.instruments\[(\d+)\]/.exec(E.path),X=F?Number(F[1]):void 0,ae=X===void 0?void 0:P.get(I.instruments[X]),W=/\.actions\.(\w+)\.publicAction$/.exec(E.path)?.[1],G=W&&r.decls.find(le=>le.kind==="expose"&&le.target.endsWith(`.${W}`)&&le.target.split(".").slice(0,-1).join("_")===I.instruments[X]?.id);if(G){S.push({code:E.code,message:`${E.path}: ${E.message}`,fix:E.fix,span:G.span});continue}if(!F||!ae){let le=/^\$\.parties\.(\w+)/.exec(E.path)?.[1];S.push({code:E.code,message:`${E.path}: ${E.message}`,fix:E.fix,span:(r.decls.find(ue=>ue.kind==="party"&&ue.name===le)??Ry(s,I,E.path)??r).span});continue}if(C.has(X))continue;C.add(X);let se=E.path.slice(F[0].length+1).replace(/\[(\d+)\]/g,".$1"),[B,te]=se.split("."),Q=ae.body.entries.find(le=>le.key===(B==="actions"?`action ${te}`:B))??ae;S.push({code:E.code,message:`${ae.name}${se?`.${se}`:""}: ${E.message}`,fix:"use the UDL typed clause shape",span:Q.span,source:y.get(ae)??"program"})}return{ok:!1,diagnostics:S}},w=_=>{let S=t.adapters;if(!Object.hasOwn(S,_))return;let C=S[_];return C&&Object.hasOwn(C.adapter.operationMap,C.operation)?C:void 0},v=new Map,L=new Map,j=new Map,g=new Set,I={udl:er,version:1,product:r.name,title:r.title,currency:r.currency,parties:Object.assign(Object.create(null),e.parties),objects:[],instruments:[]},O=[],D=(_,S,C)=>U(_,`${S} spends money of ${C.join(" and ")}, so no one party can run it`,"split it into one action per paying party","spends_two_parties");try{let _=[],S=new WeakMap,C=new WeakMap,E=new WeakSet,F=new WeakSet,X=[],ae=new Map,W=[],G=new Map,se=(M,oe,ce,ie,{inherited:me=new Map,inheritedEnums:be=new Map,inheritedTerms:ze=new Map,inheritedEconomics:gt=new Map,inheritedOwnNames:et,attachmentInfo:xe,familyDeclaration:Qe,standardOrigin:Nt,tunables:Ft}={})=>{let Xn=(N,K,V)=>{let ee=new Set;if(K&&Qe&&N.module===Qe.module&&N.exportPath.startsWith(`${Qe.exportPath}.`)){let Re=N.exportPath.slice(Qe.exportPath.length+1).replaceAll(".","_");ee.add(`${K}_${Re}`)}let de=N.exportPath.split(".")[0],re=N.exportPath.includes(".")?N.exportPath.slice(de.length+1).replaceAll(".","_"):void 0;for(let Re of o.values())Re.target===`${N.module}.${de}`&&(re?ee.add(`${Re.name}_${re}`):ee.add(Re.name));for(let Re of I.instruments)Re.family&&Re.family.module===N.module&&Re.family.exportPath===N.exportPath&&"digest"in Re.family&&Re.family.digest===N.digest&&ee.add(Re.id);let De=[...ee];return De.length===0&&V&&je(V,"HSX1001",`no instruments found for family ${N.module}.${N.exportPath}`,"declare an attachment matching this family"),De},ui=(N,K)=>{let V=Fe(a,Se(Fe(a,N.body).get("records"))),ee=[];for(let[de]of V)K===de&&ee.push(de);for(let[de,re]of V)if(K.startsWith(`${de}_`)){let De=ui({kind:"instrument",name:de,parameters:[],body:Se(re),span:N.span},K.slice(de.length+1));for(let Re of De)ee.push(`${de}.${Re}`)}return ee},_t=(N,K)=>{let V=ui(N,K);return V.length>1&&je(N,"HSX1001",`ambiguous child export path suffix '${K}': multiple candidates (${V.join(", ")})`,"rename conflicting records to remove duplicate export path suffixes"),V[0]},Fr=N=>{let K=I.instruments.find(V=>V.id===N);if(K?.family)return K.family;if(N.startsWith(`${oe}_`)&&Qe){let V=_t(M,N.slice(oe.length+1));if(V){let ee=`${Qe.exportPath}.${V}`;return A(`${Qe.module}.${ee}`,{span:ie},!1)}}for(let[V,ee]of o)if(N===V||N.startsWith(`${V}_`)){let de=h(ee.target);if(!de)continue;let re=y.get(de);if(!re||re==="program")continue;if(N===V)return A(ee.target,ee,!1);{let De=_t(de,N.slice(V.length+1));if(De){let Re=`${ee.target}.${De}`;return A(Re,ee,!1)}}}},Pr=(N,K,V)=>{let ee=Array.isArray(N)?N:[N];for(let de of ee){typeof de!="string"&&U(V,"instrument target needs a name","name a declared instrument or a list of instruments");let re=Fr(de);Ai(re,K)||je(V,"HSX1001",`target instrument ${de} family does not match expected family ${K.module}.${K.exportPath}`,"ensure target instrument matches the declared family")}},qn=new Map(be);for(let N of M.parameters){let K=N.value.kind==="default"?N.value.type:N.value;K.kind==="call"&&K.name==="enum"&&qn.set(N.key,K.args.map(Te))}let sn=Ft??Ay(M,oe,ie,ce,{texts:a,header:y.get(M)??"program",attached:!!xe,parties:I.parties,override:n,inherited:me,inheritedTerms:ze}),pr=sn.supplied,Ln=new Map([...pr].map(([N,K])=>[N,K.value])),Jt=new Map(sn.environment),cr=new Map(sn.terms),Kr=N=>(cr.get(N)?.from??"std")!=="std",Xs=new Set(M.parameters.flatMap(N=>{let K=N.value.kind==="default"?N.value.type:N.value;return(K.kind==="type"||K.kind==="call")&&K.optional?[N.key]:[]})),Vs=N=>{let K=Fe(a,Se(N)).get("adapter");return K?.kind==="name"&&Xs.has(K.value)&&!Kr(K.value)},Xr=[...sn.missing],li=sn.revertedHeader,ua=wc(M),tt=N=>N.replaceAll("{attachment}",xe?.attachmentName??oe).replaceAll("{instrument}",o.get(oe)?.target??M.name),Lt=N=>{try{N()}catch(K){if(!(K instanceof St))throw K;Xr.push(K.diagnostic)}},jn=new Set;for(let N of Ln.keys()){if(M.parameters.some(re=>re.key===N))continue;let K=Ln.get(N),V=M.body.entries.filter(re=>re.key.startsWith("action ")).flatMap(re=>Se(Se(re.value).entries.find(De=>De.key==="subject")?.value).entries),ee=[...new Set(V.filter(re=>{let De=re.value;return De.kind==="name"?De.value==="money":(De.kind==="type"||De.kind==="call")&&De.name==="money"}).map(re=>re.key))];if(xe&&(K.kind==="money"||K.kind==="name")&&ee.length===1){let re=ee[0],De=s.get(xe.subjectKindId),Re=Se(Fe(a,De.body).get("fields")).entries.filter(ke=>ke.value.kind==="name"?ke.value.value==="money":(ke.value.kind==="type"||ke.value.kind==="call")&&ke.value.name==="money"),He=Re.length===1?Re[0].key:"yourMoneyField";U(K,`\`${o.get(oe)?.target??M.name}\` has no \`${N}\` tunable. Its actions require the object's \`${re}\` field.`,`Remove \`${N}\`. To use your object's money field, add \`rename { ${re}: ${He} }\`.`,"unknown_tunable")}let de=M.parameters.map(re=>re.key);U(pr.get(N)??K,`${o.get(oe)?.target??xe?.template??M.name} has no tunable "${N}".${en(N,de)} Tunables: ${de.join(", ")}`,`remove ${N}, or set one of ${de.join(", ")}`,"unknown_tunable")}let An=Fe(a,M.body).get("persons"),pn=An?(An.kind==="list"?An.items:[An]).map(N=>N.kind==="name"?{name:N.value}:N.kind==="type"&&N.optional&&!N.target&&!N.owner&&!N.currency&&!N.many?{name:N.name,optional:!0}:U(N,"persons names people the agreement binds","write persons: [co_borrower?, guarantor]")):[];for(let N of pn)M.parameters.some(K=>K.key===N.name)&&U(An,`person ${N.name} is also a parameter of ${M.name}`,"give the person its own name"),(I.parties[N.name]||un.includes(N.name))&&U(An,`person ${N.name} names a party the instrument already binds`,"give the person its own name");let rt=N=>pn.some(K=>K.name===N),on=N=>!!I.parties[N]||!!xe&&un.includes(N)||rt(N),Yi=new Set,qd=N=>{if(!xe)return;let K=Ji.flatMap(de=>de.type==="ref"&&de.targetKind==="instrument"?[de.target].flat():[]),V=xe.attachments.flatMap(de=>K.some(re=>re===de.instrument||re.startsWith(`${de.instrument}_`))&&de.parties[N]?[de.parties[N]]:[]);return new Set(V.map(de=>JSON.stringify(de))).size===1?V[0]:void 0},Sa=new WeakSet,vu=N=>{Sa.add(N),N.kind==="list"&&N.items.forEach(vu),N.kind==="block"&&N.entries.forEach(K=>vu(K.value))};Jt.forEach(vu);let Ld=new Set(et??wm.options),rg=N=>{for(let{key:K,value:V}of N.entries)if(V.kind==="block"){if(K==="fields"&&V.entries.forEach(ee=>Ld.add(ee.key)),K==="lifecycle"){for(let ee of V.entries)if(!(ee.key!=="states"||ee.value.kind!=="list"))for(let de of ee.value.items)de.kind==="name"&&Ld.add(de.value)}rg(V)}};rg(M.body);let fn=(N,K=new Set,V=!1)=>{if(N.kind==="call"&&["object","all","party"].includes(N.name)){N.args.length!==1&&U(N,`${N.name} needs one type`,"supply one declared object or party kind");let He=Te(N.args[0]),ke=N.name==="party"?Object.entries(I.parties).filter(([Ze,Xt])=>Xt.kind===He&&(!V||i.has(Ze))).map(([Ze])=>Ze):[...o.values()].filter(Ze=>N.name==="all"||!d.has(Ze.name)||d.get(Ze.name)===xe?.subjectKindId).filter(Ze=>Ze.target===He||He.startsWith(`${Ze.target}.`)).map(Ze=>Ze.name+He.slice(Ze.target.length).replaceAll(".","_"));if(N.name==="object"&&ke.length!==1&&xe){let Ze=[...Jt].find(([,It])=>It===N)?.[0]??M.parameters.find(It=>It.value.kind==="default"&&It.value.value.span.start===N.span.start)?.key??"reference",Xt=It=>d.has(It)?It.slice(xe.subjectKindId.length+1):`${It} (program)`,nt=[...o.values()].filter(It=>It.target===He&&d.has(It.name)&&d.get(It.name)!==xe.subjectKindId).map(It=>{let qe=d.get(It.name);return`\`${qe}.${It.name.slice(qe.length+1)}\``}),Vr=h(He)?.parameters.filter(It=>It.value.kind!=="default"&&!((It.value.kind==="type"||It.value.kind==="call")&&It.value.optional)).map(It=>It.key)??[];U({span:ie},`Attachment \`${xe.attachmentName}\` needs a \`${Ze}\` binding. ${ke.length===0?`No \`${He}\` attachment exists on \`${xe.subjectKindId}\`.`:`Several \`${He}\` attachments match on \`${xe.subjectKindId}\`: ${ke.map(Xt).join(", ")}.`}`,ke.length?`Bind \`${Ze}\` explicitly to one of: ${ke.map(Xt).join(", ")}.`:`Attach \`${He}\` to \`${xe.subjectKindId}\` and bind \`${Ze}\` to that attachment's name. Choose ${Vr.map(It=>`\`${It}\``).join(", ")||"its required bindings"} explicitly.${nt.length?` ${nt.join(", ")} ${nt.length===1?"is":"are"} on another object, which this binding cannot reach.`:""}`,"attachment_binding_missing")}N.name!=="all"&&ke.length!==1&&je(N,V?"subject_party_unbound":"HSX1001",`${oe} needs ${N.name==="all"?"at least one":"exactly one"} ${He}`,"declare the required object or supply this tunable explicitly");let Ve=ke.map(Ze=>({kind:"name",value:Ze,span:ie}));return N.name==="all"?{kind:"list",items:Ve,span:ie}:Ve[0]}if(N.kind!=="name")return N;let ee=Jt.get(N.value);if(xe&&un.includes(N.value)&&(!ee||ee.kind==="name"&&ee.value===N.value))return N;if(xe&&(Sa.has(N)||!Ld.has(N.value.split(".")[0]))&&!Yi.has(N.value)){let[He,...ke]=N.value.split("."),Ve=Jt.get(He),Ze=Ve!==void 0&&!(Ve.kind==="name"&&Ve.value===He),Xt=`${xe.subjectKindId}_${He}`;if(!Ze&&d.has(Xt))return{...N,value:[Xt,...ke].join("_")}}if(N.value.startsWith("party.")){let[,He,...ke]=N.value.split("."),Ve=Jt.get(He);if(Ve?.kind==="name"&&on(Ve.value))return{...N,value:["party",Ve.value,...ke].join(".")}}let[de,...re]=N.value.split("."),De=Jt.get(de);if(!De||De.kind==="name"&&De.value===de)return N;if(K.has(de))return je(N,V?"subject_party_unbound":"HSX1001",`cyclic tunable ${de}`,"replace the cycle with a literal or declared reference");let Re=Yi.has(de)||!V&&(Ln.has(de)||me.has(de)||qn.has(de))?De:fn(De,new Set([...K,de]),V);for(let He of re){if(Re.kind!=="block")return N;let ke=Fe(a,Re).get(He);if(!ke)return U(N,`missing tunable ${N.value}`,`declare ${He} in ${de}`,"unknown_tunable");Re=fn(ke,new Set([...K,de]),V)}return Re};for(let N of M.parameters)try{let K=Jt.get(N.key);if(!K)continue;let V=N.value.kind==="default"?N.value.type:N.value,ee=V.kind==="type"||V.kind==="call"?V.name:Te(V),de=Ln.has(N.key)&&!xe||ee==="enum",re=de?K:fn(K,new Set,!!xe&&ee==="party");ee==="duration"&&(re.kind==="text"||re.kind==="name")&&/^P/.test(re.value)&&(re={...re,kind:"duration"});let De=ee==="period"?oL(re):void 0;if(De&&(re={kind:"text",value:De,span:re.span}),Jt.set(N.key,re),ee==="enum"&&V.kind==="call")(re.kind!=="name"||!V.args.some(Re=>Te(Re)===re.value))&&U(re,`invalid ${N.key}`,`choose ${V.args.map(Te).join(", ")}`);else if(ee==="list")re.kind!=="list"&&U(re,`${N.key} needs a list`,"write [value, value]","tunable_type_mismatch");else if(ee==="party")(re.kind!=="name"||!on(re.value)||rt(re.value))&&je(K,xe?"subject_party_unbound":"HSX1001",xe?`\`${N.key}: ${"value"in K&&typeof K.value=="string"?K.value:N.key}\` has no binding. An attached ${N.key} must resolve to a subject role or an eligible declared party.`:`${N.key} needs a declared party`,xe?`Use \`${N.key}: customer\` for a customer, \`${N.key}: operator\` for your company, or a declared business for a fixed company counterparty.`:"declare a party and use its name here"),xe&&I.parties[re.value]?.kind==="person"&&je(K,"party_kind_mismatch",`\`${re.value}\` is a declared person. Bind a customer with \`customer\`, rather than a fixed person declaration.`,"Replace this binding with the appropriate subject role. Use declared businesses for fixed counterparties and staff parties for authorized actions."),Yi.add(N.key),xe&&(xe.parties[N.key]=un.includes(re.value)?{role:re.value}:{party:re.value});else if(ee==="ref"){let Re=re.kind!=="list"?[re]:de?re.items:re.items.map(ke=>fn(ke));re.kind==="list"&&Jt.set(N.key,{...re,items:Re}),re.kind==="list"&&(V.kind!=="type"||!V.many)&&U(re,`${N.key} accepts one reference`,"use one object name"),Re.length||U(re,"reference union needs at least one object","name a declared object");let He=new Map;for(let ke of Re){ke.kind!=="name"&&U(ke,"reference needs an object name","name a declared object");let Ve=s.get(ke.value)?.name,Ze=[...[...o.values()].map(nt=>[nt.name,nt.target]),...r.decls.filter(nt=>nt.kind==="instrument").map(nt=>[nt.name,nt.name])];for(let[nt,We]of Ze){if(ke.value===nt){Ve=We;break}if(!ke.value.startsWith(`${nt}.`)&&!ke.value.startsWith(`${nt}_`))continue;let Vr=h(We);if(!Vr)continue;let It=ke.value.slice(nt.length+1).replaceAll(".","_"),qe=_t(Vr,It);qe&&(Ve=`${We}.${qe}`)}(!Ve||V.kind==="type"&&V.target&&Ve!==V.target)&&U(ke,`${N.key} has the wrong object type`,`use an object of type ${V.kind==="type"?V.target:"ref"}`,"tunable_type_mismatch");let Xt=He.get(ke.value);Xt&&Bn(a,`${N.key} lists ${ke.value} twice`,Xt,ke,"list each object once"),He.set(ke.value,ke)}V.kind==="type"&&V.many&&re.kind!=="list"&&Jt.set(N.key,{kind:"list",items:[re],span:re.span})}else if(ee==="period")De||U(re,`${N.key} needs a calendar period`,`write ${N.key}: 1 month, 2 weeks, 1 year or 7 days`,"tunable_type_mismatch");else if(ee==="fee"||ee==="split"||ee==="policy")re.kind!=="block"&&U(re,`${N.key} needs a block`,`write ${N.key} { ... }`,"tunable_type_mismatch");else if(ee==="money"||ee==="percent"||ee==="date"||ee==="duration"||ee==="integer"||ee==="text"||ee==="boolean"){let Re=fc(V);if(re.kind==="name"&&re.value==="runtime")continue;let He=ee==="integer"?"number":ee==="boolean"?"name":ee;if(re.kind!==He||ee==="boolean"&&re.kind==="name"&&!["true","false"].includes(re.value)){if(ee==="money"&&re.kind==="name"&&xe){let ke=re.value.replace(/^subject\./,""),Ve=N.value.kind==="default"?N.value.value:void 0,Ze=Ve?.kind==="name"&&Ve.value==="runtime"?`omit \`${N.key}\``:`set \`${N.key}: runtime\``;U(re,`\`${N.key}\` cannot read \`${re.value}\` as a tunable. This position accepts a fixed money amount or a runtime amount.`,`For a varying deposit, ${Ze} and add \`rename { ${N.key}: ${ke} }\`. Use a literal only for a fixed charge.`,"tunable_type_mismatch")}ee==="money"&&re.kind==="percent"&&U(re,`\`${o.get(oe)?.target??M.name}.${N.key}\` accepts a fixed amount. It cannot express a percentage-based charge.`,"Use a fixed amount only if that is the intended policy. A percentage charge needs an authored rate calculation; do not approximate it with a cash amount.","tunable_type_mismatch"),U(re,`${N.key} needs ${ee}`,`write a ${ee} literal`,"tunable_type_mismatch")}try{let ke=re.kind==="money"?jc(re).amount:Wt(re);Re&&(BigInt(String(ke))<BigInt(Re.minimum)||BigInt(String(ke))>BigInt(Re.maximum))&&U(re,`value is outside ${Re.minimum}..${Re.maximum}`,"choose a value inside the tunable's bounds","value_out_of_bounds")}catch(ke){throw ke instanceof St&&U(re,`${N.key}: ${ke.diagnostic.message}`,ke.diagnostic.fix,ke.diagnostic.code),ke}}else U(V,`unknown tunable type ${ee}`,"use a declared HSX tunable type","field_type_invalid")}catch(K){if(!(K instanceof St))throw K;let V=[{source:y.get(M)??"program",span:N.span,message:`Parameter ${N.key}`}],ee=Ln.get(N.key),de=ee?.kind==="name"?r.decls.find(De=>De.kind==="party"&&De.name===ee.value):void 0;de?.kind==="party"&&V.push({source:"program",span:de.span,message:`Declared party ${de.name}`});let re=ua.find(({test:De})=>De.kind==="type"&&De.tunable===N.key);jn.add(N.key),Xr.push({...K.diagnostic,...re?{message:tt(re.message),fix:re.fix}:{},related:V})}let fr=Fe(a,M.body);for(let N of Se(fr.get("ceilings")).entries)Lt(()=>{let K=Fe(a,Se(N.value)),V=K.get("by"),ee=V&&Jt.get(Te(V));(!V||ee?.kind!=="name")&&U(N,`ceiling ${N.key} needs by: an enum tunable`,"write by: kind and one maximum per enum value");let de=K.get(ee.value);if(de?.kind!=="number"&&U(N,`ceiling ${N.key} has no maximum for ${ee.value}`,`add ${ee.value}: number to the ceiling`),!Kr(N.key)){let De=cr.get(N.key);De&&cr.set(N.key,{...De,value:de,span:de.span}),Jt.set(N.key,{...de,span:ie});return}let re=Jt.get(N.key);(re.kind!=="number"||BigInt(re.value)>BigInt(de.value))&&U(re,`${N.key} for ${ee.value} is at most ${de.value}`,`choose ${N.key} of ${de.value} or less, or omit it`,"value_out_of_bounds")});for(let N of ua)Lt(()=>{let{test:K,when:V}=N;if(V){let de=Jt.get(V.selector);if(!(qn.has(V.selector)?de?.kind==="name"&&de.value===V.is:cr.has(V.selector)&&Kr(V.selector)===(V.is==="set")))return}if(K.kind==="type")return;let ee;if(K.kind==="set"){if(Kr(K.tunable))return}else{let de=[...K.left,...K.right],re=nt=>nt.kind==="name"?Jt.get(nt.value):nt;if(de.some(nt=>nt.kind==="name"&&jn.has(nt.value)||!re(nt)||re(nt).kind==="name"&&re(nt).value==="runtime"))return;let De=nt=>{let We=re(nt);return We.kind==="name"&&/^P(?:\d|T)/.test(We.value)?"duration":We.kind};(new Set(de.map(De)).size!==1||!["money","number","percent","duration"].includes(De(de[0])))&&U(N.rule,"check compares values of different types","compare amounts, integers, percentages or durations of one type");let He=new Set(de.flatMap(nt=>{let We=re(nt);return We.kind==="money"?[We.value.split(" ")[1]]:[]}));He.size>1&&U(N.rule,`check compares amounts in ${[...He].join(" and ")}`,"compare amounts in one currency","currency_mismatch");let ke=nt=>nt.reduce((We,Vr)=>We+BigInt(String(Wt(re(Vr)))),0n),[Ve,Ze]=[ke(K.left),ke(K.right)];for(let nt of de)re(nt).kind==="money"&&Ey(re(nt));if({"<":Ve<Ze,"<=":Ve<=Ze,">":Ve>Ze,">=":Ve>=Ze,"==":Ve===Ze,"!=":Ve!==Ze}[K.operator])return;ee=de.map(nt=>nt.kind==="name"?pr.get(nt.value):void 0).find(Boolean)}throw new St({code:"header_check_failed",message:tt(N.message),fix:N.fix,span:ee?.value.span??ie,related:[{source:N.source??"program",span:N.span,message:"Header check"}]})});if(Xr.length)throw k.push(...Xr.slice(1)),new St(Xr[0]);for(let N of fr.keys())!["fields","lifecycle","records","summary","invariants","checks","ceilings","reports","revisioned","scope","once_per_record","persons"].includes(N)&&!N.startsWith("action ")&&!N.startsWith("report ")&&!N.startsWith("economics ")&&U(M,`unknown instrument clause ${N}`,"use fields, lifecycle, actions, invariants, or records","unknown_clause");let ag=fL(a,M,gt,Jt),jd=Fe(a,Se(fr.get("records")));me.size||Jt.set("parent",{kind:"name",value:oe,span:ie});for(let N of jd.keys())M.parameters.some(K=>K.key===N)||Jt.set(N,{kind:"name",value:`${oe}_${N}`,span:ie});let s$=N=>{let K=Iu(N),V=K.slice(6);return xe&&K.startsWith("party.")&&un.includes(V)&&!Object.values(xe.parties).some(ee=>"role"in ee&&ee.role===V)&&je(N,"subject_party_unbound",`\`${V}\` has no money account in \`${M.name}\``,V==="operator"?"Use `programOperator` for the company's own account.":`Add a party parameter to \`${M.name}\` and bind it to \`${V}\` where you attach it.`),K},Ji=[],$u=new Map,ig=[],Ad,wu,Iu=N=>{let K=fn(N),V=Te(K);if(on(V))return`party.${V}`;if(V.startsWith("subject.")){let ee=V.split(".")[1];Ad?Ad.subject?.requirements.find(re=>re.field.name===ee)||je(N,"subject_field_unknown",`subject.${ee} names no declared subject requirement in action ${wu}`,`declare ${ee} in subject { ... }`):M.body.entries.some(re=>{if(!re.key.startsWith("action "))return!1;let De=Fe(a,Se(re.value)).get("subject");return De?Se(De).entries.some(Re=>Re.key===ee?!0:Re.key==="adapter"?(Re.value.kind==="list"?Re.value.items.map(Te):[Te(Re.value)]).some(ke=>{let Ve=w(ke);return Ve?Ve.adapter.operationMap[Ve.operation]?.subjectRequirements?.some(Xt=>Xt.name===ee):!1}):!1):!1})||je(N,"subject_field_unknown",`subject.${ee} names no declared subject requirement in instrument ${oe}`,`declare ${ee} in an action subject { ... }`)}return/^(self|input|party|subject)\./.test(V)?V:`self.${V}`},o$=N=>{let K=fn(N);if(K.kind!=="name"||["true","false"].includes(K.value)){let ee={literal:Wt(K)};return K.kind==="money"&&S.set(ee,K),ee}let V={field:Iu(K)};return S.set(V,N),V},d$=N=>{let K=fn(N);return K.kind!=="block"?yn(K):Object.fromEntries([...Fe(a,K)].map(([V,ee])=>{let de=fn(ee);return de.kind!=="money"&&U(de,`approval band ${V} must be an amount in a currency`,`write ${V} 1000 SAR`,"approval_clause_invalid"),[V,jc(de)]}))},yn=N=>{if(N.kind==="call"&&N.name==="current"&&!N.args.length)return oe;let K=fn(N);if(K.kind==="block"){let V=Fe(a,K);if(V.has("family")&&!V.has("kind")||(V.has("states")||V.has("reference")||V.has("anchor"))&&V.has("instrument")){let He;if(V.has("family")){let Ze=V.get("family"),Xt=Ze.kind==="name"?Ze.value:Te(Ze);He=A(Xt,Ze)}let ke;if(V.has("instrument")){let Ze=yn(V.get("instrument"));ke=Array.isArray(Ze)?Ze.flat():Ze,He&&Pr(ke,He,V.get("instrument"))}else if(He){let Ze=Xn(He,oe,V.get("family"));ke=Ze.length===1?Ze[0]:Ze}let Ve={};He&&(Ve.family=He),ke!==void 0&&(Ve.instrument=ke);for(let[Ze,Xt]of V)Ze==="family"||Ze==="instrument"||(Ve[Ze]=yn(Xt));return S.set(Ve,K),Ve}let ee=V.get("kind"),de=ee?.kind==="text"&&ee.value==="approval",re=Object.fromEntries([...V].map(([He,ke])=>[He,de&&He==="band"?d$(ke):yn(ke)])),De=V.get("literal");V.size===1&&De&&fn(De).kind==="percent"&&E.add(re);let Re=re.selection;return Array.isArray(Re?.instrument)&&Re.instrument.length===0?re.op==="aggregate"?{target:re.target,op:"sum",values:[{literal:re.measure==="count"?0:"0"}]}:re.kind==="aggregate"?{kind:"compare",left:{literal:re.measure==="count"?0:"0"},operator:re.operator,right:re.value}:null:(S.set(re,K),re)}if(K.kind==="list"){let V=K.items.map(yn).filter(ee=>ee!==null);return S.set(V,K),V}if(K.kind==="call"&&K.name==="child"&&K.args.length===2){let V=fn(K.args[0]),ee=de=>`${Te(de).replaceAll(".","_")}_${Te(K.args[1])}`;return V.kind==="list"?V.items.map(ee):ee(V)}return K.kind==="name"?K.value==="true"||K.value==="false"?K.value==="true":K.value:Wt(K)},zu=N=>{let[,K,V,ee,...de]=N.key.split(" ");if(de.length)return[ee,...de.filter(De=>De!=="or")].map(De=>zu({...N,key:`when ${K} ${V} ${De}`})).includes(!0);if(V==="is"&&(ee==="set"||ee==="unset")&&cr.has(K)&&!qn.has(K))return Kr(K)===(ee==="set");let re=Jt.get(K);if(re||U(N,`unknown branch tunable ${K}`,"name an enum, reference or optional tunable declared by this header","unknown_tunable"),V==="has"){let De=fn(re),[Re,...He]=Te(De).split("."),ke=o.get(Re),Ve=ke?h(ke.target)?.body:r.decls.filter(Ze=>Ze.kind==="instrument").find(Ze=>Ze.name===Re)?.body;for(let Ze of He){let Xt=Ve?Fe(a,Se(Fe(a,Ve).get("records"))).get(Ze):void 0;Ve=Xt?Se(Xt):void 0}return Ve||U(N,"field branch needs a declared object","bind a reference to a declared object"),Fe(a,Se(Fe(a,Ve).get("fields"))).has(ee)}return qn.get(K)?.includes(ee)||U(N,`unknown enum branch ${ee}`,"use a declared enum value, or set or unset"),Te(re)===ee},sg=N=>N.entries.flatMap(K=>K.key.startsWith("when ")?zu(K)?sg(Se(K.value)):[]:[K]),og=new Set,ku={texts:a,id:oe,decl:M,document:I,objects:s,environment:Jt,attachmentInfo:xe,economics:ag,fields:Ji,calculations:ig,actionTargets:og,boundaryReceipts:$u,boundaryOff:Vs,authored:S,splitMoves:F,resolve:fn,path:Iu,moneyPath:s$,val:o$,data:yn,isParty:on,reachedParty:qd,branchRows:sg,resolveFamily:A,resolveFamilyInstruments:Xn,checkTargetFamily:Pr,sharedParties:T};$.set(oe,new Map(hL(a,M).map(N=>[N,Te(fn({kind:"name",value:N,span:M.span}))]))),Ji.push(...wv(ku,Se(fr.get("fields"))));let dg=Se(fr.get("lifecycle")),la=yn(dg),Pd=Array.isArray(la.states)?la.states:[],Od=(N,K)=>{typeof K!="string"||!Pd.length||Pd.includes(K)||U(N,`\`${K}\` is not a state of \`${M.name}\`.${en(K,Pd)}`,`Use one of ${Pd.join(", ")}, or add \`${K}\` to \`lifecycle.states\`.`,"unknown_state")},pg=Fe(a,dg),cg=pg.get("initial");cg&&Od(cg,la.initial);let ug=pg.get("ends");ug?.kind==="list"&&Array.isArray(la.ends)&&ug.items.forEach((N,K)=>Od(N,la.ends[K])),la.transitions=Object.create(null);let Kt={id:oe,...xe?{subject:xe.subjectKindId}:{},...fr.has("summary")?{summary:String(yn(fr.get("summary")))}:{},fields:Ji,calculate:ig,lifecycle:la,actions:Object.create(null),actionOrder:[]};(y.get(M)??"program")==="program"&&C.set(Kt,M);let lg=N=>{for(let K of N.entries)if(K.key.startsWith("when "))lg(Se(K.value));else if(K.key==="calculate")for(let V of K.value.kind==="list"?K.value.items:[K.value]){let ee=V.kind==="block"?Fe(a,V).get("target"):void 0;ee&&og.add(String(yn(ee)))}};for(let N of M.body.entries)N.key.startsWith("action ")&&lg(Se(N.value));let mg=new Map,yg=new Map,qu=N=>({exposed:(xe?.exposed.has(N)??!1)||m.has(`${oe} ${N}`),invoked:c.has(N)}),p$=!Nt&&M.parameters.some(N=>{let K=N.value.kind==="default"?N.value.type:N.value;return K.kind==="name"&&K.value==="party"}),gg=new Map;for(let N of M.body.entries.filter(K=>K.key.startsWith("action "))){let K=N.key.slice(7),V=qe=>{let Be=qe.entries.flatMap(Je=>{if(!Je.key.startsWith("when "))return[Je];let Tt=zu(Je),ut=Se(Je.value);for(let Pt of ut.entries)!["requires","moves","invoke","calculate","set"].includes(Pt.key)&&!Pt.key.startsWith("when ")&&U(Pt,"when permits requirements, assignments, calculations, moves and invocations","keep lifecycle and actor clauses outside the branch");return Tt?V(ut).entries:[]}),Le=Be.filter(Je=>Je.key==="set");if(Le.length<2)return{...qe,entries:Be};let Ye={...Le[0],value:{kind:"block",entries:Le.flatMap(Je=>Se(Je.value).entries),span:Le[0].value.span}};return{...qe,entries:Be.flatMap(Je=>Je===Le[0]?[Ye]:Je.key==="set"?[]:[Je])}},ee=V(Se(N.value));gg.set(K,ee),k.push(...U9(a,K,Se(N.value),ee));let de=Fe(a,ee),re,De=de.get("subject"),Re=new Set,He=new Map,ke=de.get("moves");for(let qe of ke?.kind==="list"?ke.items:ke?[ke]:[]){let Be=Fe(a,Se(qe)),Le=Be.get("boundary");if(!Le||Vs(Le))continue;let Ye=Be.has("operation")?String(yn(Be.get("operation"))):"internal_transfer.create";(Ye==="internal_transfer.create"||Be.has("shares")||Be.has("fee"))&&U(qe,"boundary dispatch requires a reservation","reserve the exact amount before dispatch","boundary_invalid");let Je=Fe(a,Se(Le)),Tt=Je.get("adapter");Tt||U(Le,"boundary needs an adapter","name a bound ADL adapter","boundary_invalid");let ut=Te(fn(Tt)),Pt=w(ut);Pt||U(Le,`unknown boundary adapter ${ut}`,"bind the named ADL adapter before compilation","boundary_invalid");let tn=Je.has("operation")?Te(Je.get("operation")):Ye==="internal_transfer.reserve"?void 0:"",Cn=tn===void 0?Pt.operation:Object.entries(Pt.adapter.operationMap).find(([,br])=>br?.kind===tn)?.[0];Cn||U(Le,`${ut} declares no ${tn||"operation"} operation`,"name an operation the adapter declares");let Or=He.get(ut);Or!==void 0&&Or!==Cn&&U(Le,`this action asks ${ut} for both ${Or} and ${Cn}`,"give each provider operation its own action"),He.set(ut,Cn),Re.add(ut);let _r=Je.get("amount"),Za=tn==="capture"?Pt.adapter.operationMap[Cn]?.partial??"none":void 0;if(_r&&Za==="none"&&je(_r,"boundary_partial_capture",`${ut} captures an authorization whole, so this capture cannot name an amount`,"drop the amount to capture the whole hold"),_r&&Za==="once"){let br=Te(Be.get("transfer")),Ta=de.get("from"),En=de.get("to"),Sr=!!Ta&&!!En&&(Ta.kind==="list"?Ta.items:[Ta]).some(Sd=>String(yn(Sd))===String(yn(En))),Ws=yg.get(br);(Ws!==void 0||Sr)&&je(_r,"boundary_partial_capture",Ws!==void 0?`${ut} captures an authorization once, and ${Ws} already captures part of ${br}`:`${ut} captures an authorization once, and ${K} can run again on ${br}`,"capture part of the hold in one action that leaves its state"),yg.set(br,K)}}let Ve=de.get("send");if(Ve){let qe=Fe(a,Se(Ve)),Be=qe.get("adapter"),Le=qe.get("kind"),Ye=Te(Be),Je=w(Ye);Je||je(Be,"message_send_invalid",`unknown adapter ${Ye}`,"send through an adapter binding the toolchain declares, such as fixture_bank");let Tt=Object.entries(Je.adapter.operationMap).find(([,tn])=>tn?.kind==="message.send")?.[0];Tt||je(Be,"message_send_invalid",`${Ye} declares no message.send operation`,"send through an adapter with a message.send operation, such as fixture_bank");let ut=Te(Le);To.test(ut)||je(Le,"message_send_invalid",`${ut} is not a message kind`,'name the kind the adapter accepts, as mt700, or in quotes, as "pain.001.001.09": letters, digits, dots and dashes, up to 64');let Pt=He.get(Ye);Pt!==void 0&&Pt!==Tt&&je(Ve,"message_send_invalid",`this action asks ${Ye} for both ${Pt} and message.send`,"send the message from an action that asks the provider for nothing else"),He.set(Ye,Tt),Re.add(Ye)}let Ze=de.get("read");if(Ze){let qe=Fe(a,Se(Ze)),Be=qe.get("adapter"),Le=Te(Be),Ye=w(Le),Je=Ye?Object.entries(Ye.adapter.operationMap).find(([,Cn])=>Cn?.kind==="bill.enquire"):void 0;Je||je(Be,"read_invalid",Ye?`${Le} declares no bill.enquire operation`:`unknown adapter ${Le}`,"read through an adapter with a bill.enquire operation, such as fixture_bank");let[Tt,ut]=Je,Pt={money:["money"],text:["text","code","iban","currency"],integer:["integer"]};for(let Cn of Se(qe.get("sets")).entries){let Or=Te(Cn.value),_r=ut?.evidence?.[Or],Za=Ji.find(br=>br.name===Cn.key);(!_r||!Za||!Pt[Za.type]?.includes(_r))&&je(Cn.value,"read_invalid",_r?`${Cn.key} cannot hold ${Or}, which is ${_r}`:`${Le} answers no ${Or}`,`set a field of the evidence's type from one of ${Object.keys(ut?.evidence??{}).join(", ")}`)}let tn=He.get(Le);tn!==void 0&&tn!==Tt&&je(Ze,"read_invalid",`this action asks ${Le} for both ${tn} and bill.enquire`,"read the bill from an action that asks the provider for nothing else"),He.set(Le,Tt),Re.add(Le)}if(Re.size){let qe=Se(De),Be=new Set(qe.entries.filter(Le=>Le.key==="adapter").flatMap(Le=>Le.value.kind==="list"?Le.value.items.map(Te):[Te(Le.value)]));De={...qe,entries:[...qe.entries,...[...Re].filter(Le=>!Be.has(Le)).map(Le=>({key:"adapter",value:{kind:"name",value:Le,span:N.span},span:N.span}))]}}if(De){let qe=Se(De),Be=[],Le=[];for(let Ye of qe.entries)if(Ye.key==="adapter"){let Je=ut=>ut.kind==="name"&&M.parameters.some(Pt=>Pt.key===ut.value)?Te(fn(ut)):Te(ut),Tt=Ye.value.kind==="list"?Ye.value.items.map(Je):[Je(Ye.value)];for(let ut of Tt){let Pt=w(ut);if(Pt){let{adapter:tn}=Pt,Cn=He.get(ut)??Pt.operation,Or=tn.operationMap[Cn];if(Or&&Or.subjectRequirements!==void 0){let _r=[];for(let En of Or.subjectRequirements){let Sr=Ga.safeParse(En);(!Sr.success||Sr.data.optional)&&U(Ye,`adapter requirement ${En.name} is invalid or optional: ${Sr.success?"requirements cannot be optional":Sr.error.message}`,"ensure adapter subject requirements conform to UDL schema"),_r.push(Sr.data)}let Za=Kx({onboarding:tn.onboarding,provider:tn.provider,capability:tn.capability,operation:Cn,apiVersion:tn.apiVersion,requirements:_r}),br={...Za,declarationDigest:kr(Za)},Ta={};if(xe?.renames)for(let En of br.requirements)xe.renames.has(En.name)&&(Ta[En.name]=xe.renames.get(En.name));Le.push({binding:ut,snapshot:br,...Object.keys(Ta).length>0?{renames:Ta}:{}});for(let En of br.requirements){let Sr=xe?.renames.get(En.name),Ws=Sr??En.name,Sd=Be.find(_g=>(_g.objectField??_g.field.name)===Ws);Sd?Qa(Sd.field,En)||je(Ye,"subject_field_conflict",`conflicting requirement ${En.name} in action ${K}`,"rename or unify the requirement"):Be.push({field:{...En},...Sr?{objectField:Sr}:{}})}}else Le.push({binding:ut,snapshot:null})}else Le.push({binding:ut,snapshot:null})}}else{let Je=vv(a,Ye,fn);Je.optional&&U(Ye,`subject requirement ${Ye.key} cannot be optional`,"remove ? from requirement");let Tt=xe?.renames.get(Ye.key),ut=Tt??Ye.key,Pt=Be.find(tn=>(tn.objectField??tn.field.name)===ut);Pt?Qa(Pt.field,Je)||je(Ye,"subject_field_conflict",`conflicting requirement ${Ye.key} in action ${K}`,"rename or unify the requirement"):Be.push({field:Je,...Tt?{objectField:Tt}:{}})}(Be.length>0||Le.length>0)&&(re={requirements:Be,adapters:Le})}let Xt=de.get("from"),nt=(Xt?.kind==="list"?Xt.items:[Xt]).find(qe=>qe?.kind==="name"&&qe.value.includes("."));if(nt?.kind==="name"&&de.has("moves")){let[qe,Be]=nt.value.split("."),Le=Ln.get(qe);if(Le?.kind==="block"){let Ye=Fe(a,Le).get(Be),Je=M.parameters.find(Pt=>Pt.key===qe),Tt=Je?.value.kind==="default"?Je.value.value:void 0,ut=Tt?.kind==="block"?Fe(a,Tt).get(Be):void 0;if(Ye&&ut?.kind==="name"){let Pt=ae.get(oe)??[],{source:tn}=Ye;Pt.push({parameter:Be,span:Ye.span,...tn?{source:tn}:{},defaultState:ut.value,action:K}),ae.set(oe,Pt)}}}let We={...de.has("summary")?{summary:String(yn(de.get("summary")))}:{},event:`${oe}.${K}`,actor:"caller",input:wv(ku,Se(de.get("input"))),requires:[],moves:[],...re?{subject:re}:{}};S.set(We,N.value),C.set(We,N);let Vr=[];for(let qe of Re)We.subject?.adapters.find(Be=>Be.binding===qe)?.snapshot||U(N,`boundary adapter ${qe} has no declared requirements`,"declare the adapter subject requirements, including an explicit empty list","boundary_invalid");if(Ad=We,wu=K,K!=="create"){let qe=de.get("from"),Be=de.get("to");(!qe||!Be)&&U(N,`action ${K} needs from and to`,"declare its source and destination states","action_endpoints");let Le=qe.kind==="list"?qe.items:[qe],Ye=Le.map(Tt=>String(yn(Tt))),Je=String(yn(Be));Le.forEach((Tt,ut)=>Od(Tt,Ye[ut])),Je!=="preserve"&&Od(Be,Je),la.transitions[K]={from:Ye,to:Je}}for(let[qe,Be]of de)if(!["from","to","input","summary","subject"].includes(qe))if(qe==="moves"){let Le=Be.kind==="list"?Be.items:[Be];for(let[Ye,Je]of Le.entries())$L(ku,{name:K,action:We,calculations:Vr},Je,Ye)}else We[qe]=yn(qe==="send"?dL(Be):Be);xL(We),We.calculate&&(We.calculate=We.calculate.map(qe=>{let Be=qe.op==="sum"&&qe.values||[],[Le]=Be;if(qe.op!=="sum"||Be.length!==1||!Le||!("field"in Le||"literal"in Le)||Ji.find(Tt=>Tt.name===qe.target)?.type!=="date")return qe;let Ye={target:qe.target,op:"shift",date:Le,milliseconds:{literal:0},direction:"after"},Je=S.get(qe);return Je&&S.set(Ye,Je),Ye})),Vr.length&&(We.calculate=[...We.calculate??[],...Vr]),p$&&!de.has("actor")&&(mg.set(K,N),by(We,qu(K))&&(We.actor="clock")),xe?.exposed.has(K)&&($v(We.actor)&&U(N,`${K} runs on the clock or its parent, not a caller`,"expose only caller actions","caller_only"),We.publicAction=xe.exposed.get(K));let It=(qe,Be="")=>{if(typeof qe=="string"){if(["field","fields","reference","anchor","subject","at","instruction"].includes(Be)&&qe.startsWith("subject.")){let Le=qe.split(".")[1];We.subject?.requirements.find(Je=>Je.field.name===Le)||je(N,"subject_field_unknown",`subject.${Le} names no declared subject requirement in action ${K}`,`declare ${Le} in subject { ... }`)}}else if(Array.isArray(qe))for(let Le of qe)It(Le,Be);else if(qe!==null&&typeof qe=="object")for(let[Le,Ye]of Object.entries(qe))It(Ye,Le)};It(We.requires),It(We.set),It(We.invoke),Ad=void 0,wu=void 0;for(let qe of We.subject?.requirements??[]){let Be=Se(De).entries.find(Le=>Le.key===qe.field.name)??Se(De).entries.find(Le=>Le.key==="adapter");j.set(qe,{source:y.get(M)??"program",span:Be?.span??N.span,message:`${oe}.${K}.subject.${qe.field.name}`})}if(typeof We.actor=="object"&&"parent"in We.actor&&Array.isArray(We.actor.parent)&&(We.actor.parent=We.actor.parent.flat()),typeof We.actor=="object"&&"parent"in We.actor&&Array.isArray(We.actor.parent)&&!We.actor.parent.length){if((y.get(M)??"program")==="program"){let qe=Fe(a,Se(de.get("actor"))).get("parent");U(qe??N,`${qe?.kind==="call"?`${qe.name}(${Te(qe.args[0])})`:`the parent actor of ${K}`} matches no instrument`,"name an instrument this program declares or attaches")}delete la.transitions[K],g.add(oe);continue}Kt.actions[K]=We,Kt.actionOrder.push(K)}k.push(...F9(a,gg));for(let N of Object.values(Kt.actions))for(let K of N.moves)if("transfer"in K){let V=$u.get(K.transfer.replace(/^self\./,""));V&&(K.transfer=`self.${V}`)}else if(K.operation==="internal_transfer.reserve"&&K.boundary?.refundOf){let V=$u.get(K.boundary.refundOf.replace(/^self\./,""));V&&(K.boundary.refundOf=`self.${V}`)}let Lu=new Map;if(xe){let N=[];for(let K of xe.economics){let[V="",...ee]=K.key.slice(10).split(".");ee.length&&!Object.hasOwn(Kt.actions,V)&&jd.has(V)?Lu.set(V,[...Lu.get(V)??[],{...K,key:`economics ${ee.join(".")}`}]):N.push(K)}V9(I,Kt,xe.parties,N,yn,[...jd.keys()]),v.set(Kt.id,{prefix:xe.selectorPrefix??"",root:xe.rootInstrument??Kt.id})}for(let N of["invariants","reports","revisioned","scope"])fr.has(N)&&(Kt[N]=yn(fr.get(N)));for(let[N,K]of fr)if(N.startsWith("report ")){let V=G.get(K);if(V){V.hosts.push(Kt);continue}let ee=y.get(M),de={hosts:[Kt],name:N.slice(7),body:Se(K),span:K.span,...ee&&ee!=="program"?{source:ee}:{},...ee&&t.std.has(ee)?{standard:!0}:{}};G.set(K,de),W.push(de)}for(let N of Kt.reports??[])N?.scope&&typeof N.scope=="object"&&!("currency"in N.scope)&&(N.scope={...N.scope,currency:gr});if(pn.length&&(Kt.persons=pn),fr.has("once_per_record")){let N=Se(fr.get("once_per_record")),K=Fe(a,N);for(let de of K.keys())de!=="applies"&&de!=="reopen_on"&&U(N,`unknown once_per_record key ${de}`,"write once_per_record: { applies: true, reopen_on: [states] }");let V=K.has("applies")?fn(K.get("applies")):void 0;V&&(V.kind!=="name"||!["true","false"].includes(V.value))&&U(V,"applies needs true or false","write applies: true");let ee=K.has("reopen_on")?yn(K.get("reopen_on")):void 0;(!Array.isArray(ee)||!ee.length||ee.some(de=>typeof de!="string"))&&U(N,"once_per_record needs the states that reopen the record","write reopen_on: [cancelled, refunded]"),(!V||V.value==="true")&&(Kt.oncePerRecord={reopenOn:ee})}let hg=!1;for(let N of Object.values(Kt.actions))for(let K of N.moves)if("from"in K)for(let V of["from","to"])K[V]==="party.programTax"&&(K[V]="self.programTaxPayable",hg=!0);hg&&(Kt.fields.some(N=>N.name==="programTaxPayable")&&U(M,"programTaxPayable is reserved for the tax account","rename the authored field","name_reserved"),Kt.fields.push({name:"programTaxPayable",type:"account",owner:"programOperator",book:"cash",key:"programTax"}));for(let[N,K]of mg){let V=Kt.actions[N];if(!V)continue;let ee=xy(Kt,N,V,xe?.parties,qu(N));"spenders"in ee?D(K,N,ee.spenders):V.actor=ee.actor;let de=qu(N);de.invoked&&!de.exposed&&O.push({inst:Kt,name:N,row:K,parties:xe?.parties})}_.push({path:`$.instruments[${I.instruments.length}]`,span:{...ie,..._n(Z,ie.start)},...Nt?{standardBlock:Nt,terms:[...cr].map(([N,K])=>{let V=a.get(K.source);return{name:N,from:K.from,text:K.value?K.from==="party"?N:V.slice(K.span.start,K.span.end):"unset",source:K.source,..._n(V,K.span.start)}})}:{}}),(y.get(M)??"program")==="program"&&Kt.calculate.forEach((N,K)=>{let V=S.get(N);V?.kind==="call"&&V.round&&_.push({path:`$.instruments[${I.instruments.length}].calculate[${K}].rounding`,span:{...V.round.span,..._n(Z,V.round.span.start)}})});let fg=Qe&&pL(li??M,new Set([...Xs].filter(N=>!Kr(N))));Qe&&(Kt.family={...Qe,...fg||li?{digest:jy(fg??li)}:{}}),I.instruments.push(Kt),P.set(Kt,M);for(let[N,K]of jd){let V=xe?{...xe,attachmentName:`${xe.attachmentName}_${N}`,child:!0,exposed:new Map,economics:Lu.get(N)??[],selectorPrefix:`${xe.selectorPrefix??""}${N}.`,rootInstrument:xe.rootInstrument??oe}:void 0;V&&V.attachments.push({name:V.attachmentName,parent:xe.attachmentName,instrument:`${oe}_${N}`,parties:V.parties});let ee={kind:"instrument",name:N,parameters:[],body:Se(K),span:ie};y.set(ee,y.get(M)??"program");let de=Qe?A(`${Qe.module}.${Qe.exportPath}.${N}`,{span:ie},!1):void 0;se(ee,`${oe}_${N}`,qc,ie,{inherited:new Map([...Jt,["parent",{kind:"name",value:oe,span:ie}]]),inheritedEnums:qn,inheritedTerms:cr,inheritedEconomics:ag,inheritedOwnNames:Ld,attachmentInfo:V,familyDeclaration:de,standardOrigin:Nt&&{...Nt,recordPath:[Nt.recordPath,N].filter(Boolean).join(".")}})}},B=M=>{let oe=Kp.safeParse(M.name);if(!oe.success){U(M,`object ${M.name}: ${oe.error.issues[0].message}`,"rename the object with lowercase words joined by underscores, such as letter_of_credit","object_kind_shape");return}let ce=Fe(a,M.body);for(let _t of ce.keys())_t!=="fields"&&_t!=="columns"&&_t!=="entryActions"&&_t!=="belongs_to"&&!_t.startsWith("attach ")&&U(M,`unknown object clause ${_t}`,"use fields, columns, entryActions, belongs_to, or attach","unknown_clause");let ie=ce.get("belongs_to");ie&&!(ie.kind==="name"&&ie.value==="company")&&U(ie,"belongs_to takes company","write `belongs_to: company` when your company owns the thing this object records, such as a fleet car or shop stock, or leave it out when a customer owns it");let me=[],be=[],ze=Se(ce.get("fields"));for(let _t of ze.entries){sc.some(Pr=>Pr===_t.key)&&U(_t,`${_t.key} is a reserved object name`,"rename this field","name_reserved");let Fr=vv(a,_t);C.set(Fr,_t),me.push(Fr),be.push(_t.key)}let gt=p.get(M);if(!gt)return;let{placement:et}=gt,xe=[];for(let _t of M.body.entries)_t.key.startsWith("attach ")&&ot(k,()=>{let Fr=/^attach\s+([A-Za-z0-9_]+)\s*=\s*(.+)$/.exec(_t.key);Fr||U(_t,"invalid attach syntax","write attach name = template { ... }");let Pr=Fr[1],qn=Fr[2],sn=l.get(_t),pr=sn.template??b(qn,_t),Ln=`${M.name}_${Pr}`,Jt=Se(_t.value),cr=new Map,Kr=new Map,Xs=new Map,Vs=[];for(let tt of Jt.entries)if(tt.key.startsWith("economics "))Vs.push(tt);else if(tt.key==="rename")for(let Lt of Se(tt.value).entries){let jn=Kr.get(Lt.key);jn&&Bn(a,`rename ${Lt.key} is given twice`,jn,Lt,"rename each subject field once",{values:[jn.value,Lt.value]}),cr.set(Lt.key,Te(Lt.value)),Kr.set(Lt.key,Lt)}else if(tt.key==="expose"&&tt.value.kind==="call"){let Lt=tt.value.name,jn=Te(tt.value.args[0]),An=X.find(pn=>pn.instrument===Ln&&pn.action===Lt);An&&Bn(a,`${Lt} is exposed twice`,An.entry,tt,"expose each action once"),pr.body.entries.some(pn=>pn.key===`action ${Lt}`)||U(tt,`unknown action ${Lt}`,"expose one declared action","unknown_action"),Xs.set(Lt,jn),X.push({instrument:Ln,action:Lt,entry:tt})}let Xr={};xe.push({name:Pr,instrument:Ln,parties:Xr}),L.set(Ln,{entry:_t,name:Pr,template:pr});let li=I.instruments.length;se(pr,Ln,sn.arguments,_t.span,{attachmentInfo:{subjectKindId:M.name,attachmentName:Pr,renames:cr,exposed:Xs,parties:Xr,attachments:xe,economics:Vs,template:qn},familyDeclaration:sn.familyDeclaration,standardOrigin:sn.standardOrigin,tunables:sn.tunables});for(let tt of I.instruments.slice(li).flatMap(sL))I.parties[tt]?.kind==="business"&&tt!=="programOperator"&&tt!=="programTax"&&!Object.values(Xr).some(Lt=>"party"in Lt&&Lt.party===tt)&&(Xr[tt]??={party:tt});let ua=I.instruments.find(tt=>tt.id===Ln);ua&&!qn.includes(".")&&(ua.template=qn);for(let tt of I.instruments.slice(li).filter(Lt=>Lt.id===Ln||u.has(Lt.id))){if(!tt.actions.create)continue;let Lt=new Set(tt.calculate.map(rt=>rt.target));for(let rt of Object.values(tt.actions)){for(let on of rt.calculate??[])Lt.add(on.target);for(let on of rt.moves)"capture"in on&&on.capture&&Lt.add(on.capture);for(let on of Object.keys(rt.read?.sets??{}))Lt.add(on)}let jn=P.get(tt),An=jn?K9(jn.body):new Set(Object.values(tt.actions).flatMap(rt=>[...Object.keys(rt.set??{}),...(rt.calculate??[]).map(on=>on.target)])),pn=tt.actions.create;for(let rt of tt.fields){if(rt.type==="ref"&&rt.targetKind==="instrument"){pn.input.some(Sa=>Sa.name===rt.name)||pn.input.push({...rt,optional:!0});continue}if(rt.type==="account"||rt.type==="list"&&rt.item==="ref"&&rt.targetKind==="instrument"||rt.optional&&(An.has(rt.name)||cr.has(rt.name))||"value"in rt||Lt.has(rt.name)||pn.input.some(Sa=>Sa.name===rt.name))continue;let on=pn.subject?.requirements.find(Sa=>Sa.field.name===rt.name);if(on){Vt(on.field)!==Vt(rt)&&je(_t,"subject_field_conflict",`${tt.id}.create.subject.${rt.name} conflicts with its instrument field`,"use the instrument field's type and constraints");continue}let Yi=cr.get(rt.name);if(!Yi){pn.input.push({...rt});continue}rt.type==="digest"&&je(_t,"field_type_invalid",`${tt.id}.${rt.name} is a digest, which an object field cannot hold`,"keep the digest on the instrument and drop its rename");let qd={field:rt,objectField:Yi};pn.subject??={requirements:[],adapters:[]},pn.subject.requirements.push(qd),j.set(qd,{source:y.get(pr)??"program",span:_t.span,message:`${tt.id}.create.fields.${rt.name}`})}}for(let[tt]of cr)if(!(ua&&Object.values(ua.actions).some(jn=>jn.subject?.requirements.some(An=>An.field.name===tt)))){let jn=Kr.get(tt)??_t,An=I.instruments.slice(li).find(rt=>rt.id.startsWith(`${Ln}_`)&&rt.fields.some(on=>on.name===tt));An&&je(jn,"subject_field_unknown",`rename source '${tt}' belongs to the ${An.id.slice(Ln.length+1)} record of ${qn}; rename binds only fields of ${qn} itself`,`remove this rename; supply ${tt} as input when the record is created, or set it as a tunable where the header offers one`);let pn=ua?Object.values(ua.actions).flatMap(rt=>rt.subject?.requirements.map(on=>on.field.name)??[]):[];je(jn,"subject_field_unknown",`rename source '${tt}' is not a declared subject requirement of ${qn}`,pn.length?`rename one of: ${[...new Set(pn)].join(", ")}`:"rename a declared subject requirement")}});let Qe=ce.get("columns"),Nt=[];Qe&&(Qe.kind!=="list"&&U(Qe,"columns needs a list of field names","write columns: [name, ...]","columns_invalid"),Nt=Qe.items.map(Te),Nt.length>8&&U(Qe,`The object list selects ${Nt.length} columns; this release supports 8. The object may retain all its fields.`,`Remove ${Nt.length===9?"one name":`${Nt.length-8} names`} from \`columns\`, not from \`fields\`.`,"columns_invalid"));let Ft=ce.get("entryActions"),Xn;Ft&&((Ft.kind!=="list"||!Ft.items.length)&&U(Ft,"entryActions needs a nonempty list","name exposed create actions bound to actor","entry_action_invalid"),Xn=Ft.items.map(Te));let ui=et.entryActions.filter(_t=>!Xn?.includes(_t));ui.length&&(Xn=[...Xn??[],...ui]),I.objects.push({id:M.name,title:M.title,...Xn?{entryActions:Xn}:{},authoredFields:be,attachments:xe,fields:me,columns:Nt})};for(let M of r.decls)ot(k,()=>{if(M.kind==="instrument"&&!M.parameters.length&&se(M,M.name,qc,M.span),M.kind==="assignment"){let oe=l.get(M),ce=oe.template??b(M.target,M);se(ce,M.name,M.body,M.span,{familyDeclaration:oe.familyDeclaration,standardOrigin:oe.standardOrigin,tunables:oe.tunables})}M.kind==="object"&&B(M)});for(let M of W)ot(k,()=>{let[oe]=M.hosts,ce=H9(M,I);ce&&(oe.reports=[...oe.reports??[],ce])});f=k.length;let te=new Set,Q=new Set(I.instruments.map(M=>M.id));for(let M of I.instruments)for(let oe of Object.values(M.actions))for(let ce of oe.invoke??[]){let ie="reference"in ce?mt(I,M,ce.reference,oe.input,oe):void 0,me="instrument"in ce?[ce.instrument]:"selection"in ce?[ce.selection.instrument].flat():ie?.type==="ref"&&ie.targetKind==="instrument"?[ie.target??[]].flat():[],be=me.length>0&&me.every(ze=>Q.has(ze));for(let ze of be?me:["*"])te.add(`${ze} ${ce.action}`)}for(let{inst:M,name:oe,row:ce,parties:ie}of O){let me=M.actions[oe];if(!me||!Q.has(M.id)||te.has(`${M.id} ${oe}`)||te.has(`* ${oe}`))continue;let be=xy(M,oe,me,ie,{exposed:!1,invoked:!1});if(!("spenders"in be)){me.actor=be.actor;continue}try{D(ce,oe,be.spenders)}catch(ze){if(!ie||!(ze instanceof St))throw ze;k.push(ze.diagnostic)}}if(k.length)return z(k);let le=M=>{if(!M||typeof M!="object")return;let oe=M,ce=oe.selection;if(ce&&!ce.family){let ie=[ce.instrument].flat().map(be=>I.instruments.find(ze=>ze.id===be)?.family),me=ie[0];me&&ie.every(be=>be!==void 0&&Vt(be)===Vt(me))&&(ce.family=me)}for(let ie of Object.values(oe))le(ie)};le(I),IL(I,S,E),qL(I,j);for(let M of I.objects)ot(k,()=>{let oe=new Map(M.fields.map(ce=>[ce.name,`authored field ${M.id}.${ce.name}`]));for(let ce of I.instruments.filter(ie=>ie.subject===M.id))for(let ie of ce.actionOrder)for(let me of ce.actions[ie].subject?.requirements??[]){let be={...me.field,name:me.objectField??me.field.name},ze=M.fields.find(et=>et.name===be.name),gt=`${ce.id}.${ie}.subject.${me.field.name}`;ze&&!Qa(ze,be)&&je(s.get(M.id),"subject_field_conflict",`${gt} conflicts with ${oe.get(be.name)}: mismatched types or constraints`,"rename fields with different meanings"),ze||(M.fields.push(be),oe.set(be.name,gt))}for(let ce of M.columns)M.fields.some(ie=>ie.name===ce)||je(s.get(M.id),"subject_field_unknown",`column ${ce} is unknown on ${M.id}`,"name an authored field or attached requirement")});if(LL(a,I,S,P,h,k),mL(r,t,k),lL(I,S),yL(I,S,P,k),js.push(...gL(I,S)),js.push(...cL()),k.push(...lc(js)),k.length)return z(k);jL(I,g,q);let ue=M=>{let{decl:oe,party:ce,site:ie}=M,me=`${M.field}: ref<${ie.target}> of ${ce}`;M.targetKind==="object"&&U(ie,`\`${me}\` names an object, and an object binds no party`,"reference the instrument attached to the object, or remove of","shared_party_unknown");let be=$.get(M.instrument);for(let ze of M.targets){let gt=$.get(ze),et=[...be.has(ce)?[]:[oe.name],...gt?.has(ce)?[]:[ze]];if(et.length){let Nt=[...be].flatMap(([Ft,Xn])=>gt?.get(Ft)===Xn&&I.parties[Xn]?.kind!=="staff"?[Ft]:[]);U(ie,`\`${me}\` needs party ${ce} on both ${oe.name} and ${ze}, and ${et.join(" and ")} ${et.length===1?"declares":"declare"} none`,Nt.length?`name a party both declare: ${Nt.join(", ")}`:`declare ${ce} on ${et.join(" and ")}`,"shared_party_unknown")}let xe=be.get(ce),Qe=gt.get(ce);xe!==Qe&&U(ie,`\`${me}\`: ${ce} binds to ${xe} on ${oe.name} and to ${Qe} on ${ze}`,`bind ${ce} to the same party on both instruments`,"shared_party_unknown"),I.parties[xe]?.kind==="staff"&&U(ie,`\`${me}\`: ${ce} is the staff role ${xe}, which binds no account on a record`,"name a party each record binds, such as the applicant","shared_party_unknown")}},Pe=[];for(let M of T)ot(Pe,()=>ue(M));if(Pe.length)return z(Pe);let we=[];for(let M of X)I.instruments.find(oe=>oe.id===M.instrument)?.actions[M.action]||ot(we,()=>U(M.entry,`action ${M.action} is excluded by these bindings`,"expose an action available with these tunables","action_excluded"));let _e=new Map;for(let M of r.decls)M.kind==="expose"&&ot(we,()=>{let oe=M.target.split("."),ce=oe.pop(),ie=oe.join("_"),me=I.instruments.find(ze=>ze.id===ie)?.actions[ce??""],be=_e.get(M.target);be&&Bn(a,`${M.target} is exposed twice`,be,M,"expose each action once"),me||U(M,`unknown action ${M.target}`,"name one declared object.action","unknown_action"),_e.set(M.target,M),$v(me.actor)&&U(M,`${M.target} runs on the clock or its parent, not a caller`,"expose only caller actions","caller_only"),me.publicAction=M.name});let $e=new Set;for(let M of r.decls)M.kind==="accept"&&ot(we,()=>{let oe=I.instruments.find(ie=>ie.id===M.target.split(".").join("_"));oe||U(M,`${M.target} names no attached instrument`,"name the object and attachment, as in accept moves_balance on loan.plan","accept_invalid");let ce=bs.find(ie=>ie===M.property);ce||U(M,`${M.property} is not a certificate property`,`accept one of ${bs.join(", ")}`,"accept_invalid"),$e.has(`${M.target} ${ce}`)&&U(M,`${ce} on ${M.target} is accepted twice`,"accept each property once","accept_invalid"),$e.add(`${M.target} ${ce}`);for(let ie of I.instruments)(ie===oe||!M.target.includes(".")&&ie.template===oe.id)&&!ie.accepts?.includes(ce)&&(ie.accepts=[...ie.accepts??[],ce])});let Ie=new Map;for(let M of r.decls){if(M.kind!=="expose")continue;let oe=M.target.split(".").slice(0,-1).join("_"),ce=`${oe} ${M.name}`,ie=Ie.get(ce)??X.find(({instrument:me,action:be,entry:ze})=>me===oe&&`${M.target}`.split(".").pop()!==be&&ze.value.kind==="call"&&Te(ze.value.args[0])===M.name)?.entry;ie&&ot(we,()=>Bn(a,`public action ${M.name} is given twice on ${oe}`,ie,M,"give each exposed action a distinct public name")),Ie.set(ce,M)}let at=[];for(let M of I.objects){let oe=new Map;for(let ce of I.instruments){if(ce.subject!==M.id)continue;let ie=M.attachments.find(me=>me.instrument===ce.id)?.name??ce.id;for(let[me,be]of Object.entries(ce.actions)){if(!be.publicAction)continue;let ze=oe.get(be.publicAction);if(ze===void 0){oe.set(be.publicAction,ie);continue}let gt=r.decls.find(Qe=>Qe.kind==="expose"&&Qe.target.split(".").slice(0,-1).join("_")===ce.id&&Qe.target.endsWith(`.${me}`)),et=gt??X.find(Qe=>Qe.instrument===ce.id&&Qe.action===me)?.entry??s.get(M.id),xe=gt?.kind==="expose"?gt.target:me;at.push({code:"public_name_collision",message:`\`${ie}\` exposes \`${be.publicAction}\`, which \`${ze}\` already exposes on \`${M.id}\``,fix:`Give it its own public name, for example \`expose ${xe} as ${ie}_${me}\`.`,span:et.span})}}}we.push(...at);let dt=new Map(I.instruments.map(M=>[M.id,M]));for(let M of I.objects)for(let oe of M.attachments){if(oe.parent)continue;let ce=dt.get(oe.instrument),ie=ce.actions.create,me=ie?.input.filter(ze=>!ze.optional)??[],be=Object.values(ce.actions).find(ze=>ze.publicAction);!me.length||ie.publicAction||!be||ot(we,()=>U(s.get(M.id).body.entries.find(ze=>new RegExp(`^attach\\s+${oe.name}\\s*=`).test(ze.key))??s.get(M.id),`${oe.name} starts from ${be.publicAction}, but its create needs ${me.map(ze=>ze.name).join(", ")} and is not exposed`,`expose create on ${oe.name} so the caller supplies ${me.length===1?"it":"them"}, or rename { ${me[0].name}: ${me[0].name} } to read object metadata`,"create_input_hidden"))}for(let M of I.objects)for(let oe of M.entryActions??[])M.attachments.some(ie=>{let me=I.instruments.find(be=>be.id===ie.instrument)?.actions.create;return me?.publicAction===oe&&typeof me.actor=="object"&&"party"in me.actor&&me.actor.party==="actor"})||ot(we,()=>U(s.get(M.id),`entry action ${oe} must create an attachment as actor`,"expose its create action and bind its acting party to actor","entry_action_invalid"));if(we.length)return z(we);for(let M of I.instruments)for(let oe of Object.values(M.actions))oe.moves=oe.moves.filter(ce=>!F.has(ce)||!("amount"in ce)||!oc(I,M,ce.from,ce.to,oe.input,oe));let Ae=(M,oe)=>{oe.source!==void 0||oe.span.end<=oe.span.start||_.push({path:M,span:{...oe.span,..._n(Z,oe.span.start)}})};for(let M of r.decls)M.kind==="party"&&Ae(`$.parties.${M.name}`,M);I.instruments.forEach((M,oe)=>{let ce=`$.instruments[${oe}]`;M.fields.forEach((ie,me)=>{let be=S.get(ie);be&&Ae(`${ce}.fields[${me}]`,be)});for(let[ie,me]of Object.entries(M.actions)){let be=S.get(me);be&&Ae(`${ce}.actions.${ie}`,be),me.moves.forEach((ze,gt)=>{let et=S.get(ze);et?.kind!=="block"||!et.entries.length||Ae(`${ce}.actions.${ie}.moves[${gt}]`,{...et,span:{start:Math.min(...et.entries.map(xe=>xe.span.start)),end:Math.max(...et.entries.map(xe=>xe.span.end))}})})}});let Ht=[],wt=new Set,or=(M,oe,ce)=>{!M||M.source||wt.has(M.span.start)||(wt.add(M.span.start),Ht.push({code:"prose_missing",message:oe,fix:ce,span:M.span}))},pt=(M,oe)=>{for(let ce of oe)ce.description===void 0&&or(C.get(ce)??S.get(ce),`\`${M}.${ce.name}\` has no description`,`Write a quoted sentence after the type of \`${ce.name}\`: what the value is, and its unit when it has one.`)};for(let M of I.objects)pt(M.id,M.fields);for(let M of I.instruments){let oe=M.template??M.id;M.summary===void 0&&or(C.get(M),`\`${oe}\` has no summary`,'Write `summary: "One record is ..."` in the instrument.'),pt(oe,M.fields);for(let[ce,ie]of Object.entries(M.actions))ie.summary===void 0&&or(C.get(ie),`\`${oe}.${ce}\` has no summary`,'Write `summary: "..."` in the action: one sentence on what it does and who runs it.'),pt(`${oe}.${ce}`,ie.input)}let dr=Mo(I),ca=[...R(),...dr.ok?[]:dr.issues];return!dr.ok||ca.length?x(ca):{ok:!0,lowered:{document:I,read:{stored:dr.stored,document:dr.document},originMap:_,refundBindings:ae,attachedSelectors:v,attachEntries:L,proseMissing:Ht}}}catch(_){if(_ instanceof St)return z([...k,_.diagnostic]);let S=f===void 0?void 0:H();if(S)return S;throw _}}var $v,Cy,js,gr,Mi,Sy,_L,jv,vL,zL,Zy,kL,Pc=ve(()=>{"use strict";Er();In();N9();hy();X9();fy();Ls();ov();Ha();Py();$v=e=>e==="clock"||e==="observation"||e!==null&&typeof e=="object"&&"parent"in e;Cy=an(er);js=[],gr=Ka,Mi=new Map,Sy=e=>`${e.source??""}:${e.span.start}:${e.value}`;_L=["payee","fee","tax"];jv=new WeakMap;vL={"internal_transfer.reserve":["authorize","refund"],"internal_transfer.post":["capture","account.post"],"internal_transfer.void":["void"]};zL={"==":"!=","!=":"==","<":">=","<=":">",">":"<=",">=":"<"},Zy=128,kL=32});function Oc(e){return{costManifest:Fo(e.document),documentDigest:Qm(e.stored)}}function Sc(e){return{digest:e.digest,hsx:e.hsx,prover:e.prover}}function Zc(e,t,n){return E9(e,t,Wt,n)}var By=ve(()=>{"use strict";In();hc();Ko();Pc()});var Ui,Pv,Uy,Ov,Sv,Zv,Fy,Tc,Dc,AL,Tv,Ky,Xy,Vy,Dv,Rv,Wy,Cv,Ev,Hv=ve(()=>{"use strict";Ui=/^[a-z][a-z0-9_.-]{0,79}$/,Pv=["money","ref","date","duration","text","integer","percent","boolean","enum","list"],Uy=["acknowledged","unknown","authorized","requires_action","confirmed","rejected","duplicate"],Ov=["confirmed","rejected"],Sv=["confirmed","rejected","duplicate"],Zv=["release","hold"],Fy=["authorize","capture","adjust","void","refund","enquire","settlement.observe","payout","payout.batch","account.provision","account.lookup","account.post","account.balance","account.statement","account.intraday","message.send","message.observe","credit.observe","bill.enquire"],Tc=["capture","adjust","void"],Dc=[...Tc,"account.provision","account.lookup","account.post","account.balance","account.statement","account.intraday","message.send","message.observe","bill.enquire"],AL=[...Tc,"account.post"],Tv=["atomic","separate"],Ky=["none","once","multiple"],Xy=["GET","POST","DELETE"],Vy=["$instructionId","$callId","$externalReference","$amount","$currency","$refundOf","$masterReference","$legs","$date","$messageType","$messageReference","$document","$resubmitOf","$cursor","$debitReference","$payee","$items","$biller","$billNumber"],Dv=["$resubmitOf","$refundOf","$masterReference"],Rv=["code","money","currency","date","datetime","text","iban","integer"],Wy=["api_key","hmac_sha256","mtls","oauth_client"],Cv=["api_key","mtls","oauth_client"],Ev=["sandbox","live"]});function Yv(e){if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/.test(e))return!1;let t=(e.slice(4)+e.slice(0,4)).replace(/[A-Z]/g,r=>String(r.charCodeAt(0)-55)),n=0;for(let r of t)n=(n*10+Number(r))%97;return n===1}function CL(e){let t=new Set;for(let n of e){if(!Ui.test(n.provider))throw new Error(`invalid provider key ${n.provider}`);let r=`${n.provider}:${n.capability}`;if(t.has(r))throw new Error(`duplicate provider adapter ${r}`);if(t.add(r),n.onboarding&&(!n.onboarding.length||n.onboarding.some(a=>a!=="person"&&a!=="organization")||new Set(n.onboarding).size!==n.onboarding.length))throw new Error(`${n.provider} onboarding must declare person, organization or both`);JL(n),EL(n),ML(n),FL(n),YL(n)}return e}function EL(e){let t=(a,i)=>{throw new As(a,`${e.provider} ${i}`)},n=e.money?.feeAccount;n!==void 0&&(!Rc.test(n)||n.length>80)&&t("fee_account_invalid",`money.feeAccount ${n} must be an account key such as provider_fees`);let r=e.states??{};for(let[a,i]of Object.entries(r)){let s=`states.${a}`;Rc.test(a)||t("state_family_invalid",`${s} must be a lower camel or snake name`);for(let d of["from","holdExpiresAt","reasonCode","deadline","statusReports"]){let p=i[d];d!=="from"&&p===void 0||(typeof p!="string"||p.trim().length===0)&&t("state_family_invalid",`${s}.${d} must be a response path`)}let o=Object.entries(i.map??{});o.length===0&&t("state_family_invalid",`${s}.map must map at least one code`);for(let[d,p]of o)(d.length===0||d.length>80)&&t("state_family_invalid",`${s}.map code ${d} must be 1 to 80 characters`),Uy.includes(p)||t("state_family_invalid",`${s}.map.${d} names unknown outcome ${p}`);Array.isArray(i.terminal)||t("state_family_invalid",`${s}.terminal must list the final codes`);for(let d of i.terminal)Object.hasOwn(i.map,d)||t("state_code_unmapped",`${s}.terminal names ${d}, which map does not`);i.terminal.length===0&&t("state_map_no_terminal",`${s} declares no terminal code, so no observation could ever settle a hold`);for(let[d,p]of o){let u=i.terminal.includes(d);!u&&Nv.includes(p)&&t("state_nonterminal_settles",`${s}.map.${d} is ${p}, but ${d} is not a terminal code, so it would settle a hold the provider has not finished`),u&&!Nv.includes(p)&&t("state_terminal_holds",`${s}.map.${d} is terminal but maps to ${p}, which keeps the hold forever`)}}for(let[a,i]of Object.entries(e.operationMap))i.state!==void 0&&!Object.hasOwn(r,i.state)&&t("state_family_missing",`${a}.state names ${i.state}, which states does not declare`),i.remainder!==void 0&&!Zv.includes(i.remainder)&&t("remainder_rule_invalid",`${a}.remainder must be release or hold`)}function ML(e){let t=(r,a)=>{throw new As(r,`${e.provider} ${a}`)},n=new Map;for(let[r,a]of Object.entries(e.operationMap)){let{kind:i,request:s,evidence:o,partial:d}=a;if(i===void 0){(s??o??d??a.legs)&&t("operation_contract_incomplete",`${r} declares a request, evidence, partial or legs rule but no kind`);continue}Fy.includes(i)||t("operation_kind_invalid",`${r}.kind ${i} must be one of ${Fy.join(", ")}`);let p=n.get(i);p&&t("operation_kind_duplicate",`${r} and ${p} both declare kind ${i}, so a call could not name one`),n.set(i,r),(!s||a.state===void 0||!o)&&t("operation_contract_incomplete",`${r} is a ${i} and must declare request, state and evidence`);let u=(c,l)=>{Vy.includes(c)||t("operation_request_invalid",`${r}.request${l} names ${c}, which is not one of ${Vy.join(", ")}`)};Xy.includes(s.method)||t("operation_request_invalid",`${r}.request.method must be one of ${Xy.join(", ")}`),(typeof s.path!="string"||!s.path.startsWith("/")||s.path.length>240||/\s/.test(s.path))&&t("operation_request_invalid",`${r}.request.path must start with / and hold no spaces`);for(let[,c]of s.path.matchAll(Jy))u(c,".path"),Dc.includes(i)&&Dv.includes(c)&&t("operation_request_invalid",`${r}.request.path names ${c}, which a call may lack`);s.path.replace(Jy,"").includes("$")&&t("operation_request_invalid",`${r}.request.path writes a value outside {$value}`),s.method==="GET"&&s.body&&t("operation_request_invalid",`${r}.request is a GET and carries no body`);for(let[c,l]of Object.entries(s.body??{}))Mv.test(c)||t("operation_request_invalid",`${r}.request.body.${c} must be a provider field name`),(typeof l!="string"||!HL.test(l))&&t("operation_request_invalid",`${r}.request.body.${c} must be a $ value drawn from the instruction`),u(l,`.body.${c}`);if(i==="message.send"){a.subjectRequirements?.length&&t("message_send_format_fields",`${r} is a message.send and asks the program for subject fields; the document carries the message's fields and the adapter formats them`);for(let[,c]of[...s.path.matchAll(Jy),...Object.values(s.body??{}).map(l=>["",l])])Bv.includes(c)||t("message_send_format_fields",`${r}.request names ${c}, which a message.send never carries; it sends ${Bv.join(", ")}`)}let m=Object.entries(o);(m.length===0||m.length>32)&&t("operation_evidence_invalid",`${r}.evidence must name 1 to 32 fields`);for(let[c,l]of m)Mv.test(c)||t("operation_evidence_invalid",`${r}.evidence.${c} must be a lower camel or snake name`),Rv.includes(l)||t("operation_evidence_invalid",`${r}.evidence.${c} names unknown type ${l}`);d!==void 0&&!Ky.includes(d)&&t("operation_partial_invalid",`${r}.partial must be one of ${Ky.join(", ")}`),d!==void 0&&d!=="none"&&!NL.includes(i)&&t("operation_partial_invalid",`${r} is a ${i}, which moves no amount of its own and so cannot be partial`),d==="multiple"&&i==="capture"&&a.remainder!=="hold"&&t("operation_partial_invalid",`${r} captures more than once, so its remainder must be hold`),a.legs!==void 0&&(i!=="account.post"||!Tv.includes(a.legs))&&t("operation_legs_invalid",`${r}.legs must be atomic or separate, and only an account.post books legs`)}if(!n.has("authorize"))for(let r of Tc)n.has(r)&&t("operation_authorize_missing",`${n.get(r)} is a ${r} but the adapter declares no authorize to hold the money first`)}function Gy(e){if(typeof e!="string"||!BL.test(e))return;let t=e.at(-1);return Number(e.slice(0,-1))*Jv[t]}function FL(e){let t=(r,a)=>{throw new As(r,`${e.provider} ${a}`)},n=r=>{let a=Gy(r);return a!==void 0&&a<=UL};e.callDeadline!==void 0&&!n(e.callDeadline)&&t("call_deadline_invalid","callDeadline must be a whole number of s, m, h or d up to 30d, as 15m");for(let[r,a]of Object.entries(e.operationMap)){let i=a.kind!==void 0&&Dc.includes(a.kind);for(let s of["callDeadline","retryCeiling"])a[s]!==void 0&&!i&&t("call_deadline_invalid",`${r}.${s} is set, but only a call kind makes a call that can lapse`);if(a.retryCeiling!==void 0){let s=Gy(a.retryCeiling),o=Gy(a.callDeadline??e.callDeadline);s===void 0&&t("call_deadline_invalid",`${r}.retryCeiling must be a whole number of s, m, h or d, as 5m`),o!==void 0&&o<=s&&t("call_deadline_invalid",`${r}'s call deadline ${a.callDeadline??e.callDeadline} does not exceed its retryCeiling ${a.retryCeiling}, so a call could lapse while the provider still retries it`)}a.callDeadline!==void 0?n(a.callDeadline)||t("call_deadline_invalid",`${r}.callDeadline must be a whole number of s, m, h or d up to 30d, as 15m`):i&&e.callDeadline===void 0&&t("call_deadline_missing",`${r} is a ${a.kind} with no callDeadline and the adapter declares none, so a call the provider never answers would be asked forever`)}}function WL(e){return e==="localhost"||e==="[::1]"||/^127(\.(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])){3}$/.test(e)}function Fv(e,t){if(typeof e!="string"||e.length>240)return!1;try{let n=new URL(e),r=WL(n.hostname);return(n.protocol==="https:"||n.protocol==="http:"&&r&&t==="sandbox")&&!(r&&t==="live")&&n.hostname.length>0&&!n.username&&!n.password&&!n.search&&!n.hash}catch{return!1}}function YL(e){let t=(i,s)=>{throw new As(i,`${e.provider} ${s}`)},n=new Map,r=(i,s,o,d=!0)=>{(typeof i!="string"||!KL.test(i))&&t(o,`${s} must be an HTTP header name`);let p=i.toLowerCase();XL.includes(p)&&t(o,`${s} names ${i}, which Arc writes itself`);let u=n.get(p);u&&t(o,`${s} and ${u} both name header ${i}`),d&&n.set(p,s)};if(e.apiVersion!==void 0&&(r(e.apiVersion.header,"apiVersion.header","api_version_invalid"),(typeof e.apiVersion.value!="string"||!Uv.test(e.apiVersion.value))&&t("api_version_invalid","apiVersion.value must be 1 to 80 printable characters without spaces")),e.idempotency!==void 0){let{header:i,lifetime:s,mismatchCode:o}=e.idempotency;r(i,"idempotency.header","idempotency_invalid"),(typeof s!="string"||!VL.test(s))&&t("idempotency_invalid","idempotency.lifetime must be a whole number of s, m, h or d, as 24h"),(typeof o!="string"||o.length===0||o.length>80)&&t("idempotency_invalid","idempotency.mismatchCode must be the provider's error code")}let a=e.credentials??{};for(let[i,s]of Object.entries(a)){let o=`credentials.${i}`;switch((!Rc.test(i)||i.length>80)&&t("credential_invalid",`${o} must be a lower camel or snake name`),Wy.includes(s.kind)||t("credential_invalid",`${o}.kind must be one of ${Wy.join(", ")}`),s.kind){case"api_key":r(s.header,`${o}.header`,"credential_invalid",!1),s.scheme!==void 0&&!/^[A-Za-z][A-Za-z0-9._-]{0,31}$/.test(s.scheme)&&t("credential_invalid",`${o}.scheme must be one word, as Bearer`);break;case"hmac_sha256":r(s.header,`${o}.header`,"credential_invalid",!1),(!Number.isInteger(s.toleranceSeconds)||s.toleranceSeconds<1||s.toleranceSeconds>3600)&&t("credential_invalid",`${o}.toleranceSeconds must be a whole number from 1 to 3600`);break;case"mtls":(typeof s.certificate!="string"||!Rc.test(s.certificate)||s.certificate.length>80)&&t("credential_invalid",`${o}.certificate must name a certificate profile, as eidas_qwac`);break;case"oauth_client":Fv(s.tokenUrl)||t("credential_invalid",`${o}.tokenUrl must be an https URL`),(!Array.isArray(s.scopes)||s.scopes.length>32||s.scopes.some(d=>typeof d!="string"||!Uv.test(d)))&&t("credential_invalid",`${o}.scopes must list at most 32 scopes without spaces`);break}}for(let[i,s]of Object.entries(e.environments??{})){let o=`environments.${i}`;if(Ev.includes(i)||t("environment_invalid",`${o} must be sandbox or live`),(!s||!Fv(s.baseUrl,i))&&t("environment_invalid",`${o}.baseUrl must be an https URL with no user, query or fragment; sandbox may use http on a loopback host, live never names one`),s.credential===void 0)continue;let d=Object.hasOwn(a,s.credential)?a[s.credential]:void 0;d||t("environment_credential_missing",`${o}.credential names ${s.credential}, which credentials does not declare`),Cv.includes(d.kind)||t("environment_credential_missing",`${o}.credential names ${s.credential}, a ${d.kind} secret, which checks what the provider sends and cannot authenticate a call`)}}function Qy(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function r0(e,t){let n=Qy(t,e.from);if(typeof n!="string"||n.length===0)return;let r=d=>{let p=d===void 0?void 0:Qy(t,d);return typeof p=="string"&&p.length>0?p:void 0},a=r(e.reasonCode),i=r(e.holdExpiresAt),s=r(e.deadline),o=e.statusReports===void 0?void 0:Qy(t,e.statusReports);return{providerCode:n,outcome:Object.hasOwn(e.map,n)?e.map[n]:"unknown",...a?{reasonCode:a}:{},...i?{holdExpiresAt:i}:{},...s?{deadline:s}:{},...Number.isSafeInteger(o)&&o>=0?{statusReports:o}:{}}}function Cc(){return e=>CL(e)}function JL(e){for(let[t,n]of Object.entries(e.operationMap)){if(t!==n.operation)throw new Error(`${e.provider} operationMap key ${t} must match operation ${n.operation}`);if(GL(e.provider,`${t}.resourceIdPath`,n.resourceIdPath),n.subjectRequirements!==void 0){if(!Array.isArray(n.subjectRequirements)||n.subjectRequirements.length>128)throw new Error(`${e.provider} ${t}.subjectRequirements must be an array of at most 128 fields`);for(let[r,a]of n.subjectRequirements.entries()){let i=Ga.safeParse(a);if(!i.success||i.data.optional)throw new Error(`${e.provider} ${t}.subjectRequirements[${r}] does not match UDL object field schema: ${i.success?"action requirements cannot be optional":i.error.message}`);if(!Pv.includes(a.type))throw new Error(`${e.provider} ${t}.subjectRequirements[${r}] unknown subject field type ${a.type}`)}}}}function GL(e,t,n){if(n.trim().length===0)throw new Error(`${e} ${t} must not be blank`)}var kt,ia,Yy,e0,Kv,PL,OL,SL,Xv,t0,ZL,TL,DL,Vv,n0,RL,Wv,As,Rc,Nv,HL,Jy,Mv,NL,Bv,BL,Jv,UL,KL,XL,Uv,VL,a0=ve(()=>{"use strict";Fa();In();Hv();kt=Ce().min(1).max(240),ia=Ce().regex(/^[1-9][0-9]{0,17}$/),Yy=Ce().regex(/^(0|[1-9][0-9]{0,17})$/),e0=Ce().min(1).max(80),Kv=Ce().min(1).max(240),PL=Oe(Uy),OL=Y({reference:kt,payee:Kv,amount:ia}).readonly(),SL=Y({reference:kt,outcome:Oe(Ov),amount:ia,reasonCode:e0.optional(),reason:Ce().min(1).max(240).optional()}).readonly(),Xv=e=>e.every(t=>ia.safeParse(t.amount).success)?e.reduce((t,n)=>t+BigInt(n.amount),0n):void 0,t0=Y({id:kt,environment:Oe(["sandbox","live"]),tenantId:kt,productId:kt,productCoreId:kt,coreDigest:kt,target:Y({kind:kt,attachment:kt,instanceId:kt}).readonly(),sourceAccountId:kt,destinationAccountId:kt,amount:Ce().regex(/^[1-9][0-9]{0,17}$/),currency:Rn,adapter:Ce().regex(Ui),operation:Oe(["authorize","refund"]).optional(),refundOf:kt.optional(),items:ye(OL).min(1).max(Ao).optional(),debitReference:kt.optional(),payee:Kv.optional()}).superRefine((e,t)=>{e.operation!==void 0&&(e.debitReference!==void 0||e.payee!==void 0)&&t.addIssue({code:"custom",path:[e.payee!==void 0?"payee":"debitReference"],message:"only a payout names a debit account or a payee"}),e.items&&e.payee!==void 0&&t.addIssue({code:"custom",path:["payee"],message:"a batch names a payee on each line"}),(e.operation==="refund"?e.refundOf===void 0:e.refundOf!==void 0&&(e.operation!==void 0||e.items!==void 0))&&t.addIssue({code:"custom",path:["refundOf"],message:"a refund names the authorization it returns money from, and only a refund or a single payout names refundOf"});let{items:n}=e;if(!n)return;e.operation!==void 0&&t.addIssue({code:"custom",path:["items"],message:"only a payout carries items"}),new Set(n.map(a=>a.reference)).size!==n.length&&t.addIssue({code:"custom",path:["items"],message:"each item has its own reference"});let r=Xv(n);r!==void 0&&ia.safeParse(e.amount).success&&r!==BigInt(e.amount)&&t.addIssue({code:"custom",path:["amount"],message:"a batch instruction's amount is the total of its items"})}).readonly(),ZL={capture:[["amount","currency"]],adjust:[["amount","currency"]],void:[["currency"]],"account.provision":[["currency"],["masterReference"]],"account.lookup":[[]],"account.post":[["amount","currency","legs"],["resubmitOf"]],"account.balance":[[]],"account.statement":[["date"]],"account.intraday":[["cursor"]],"message.send":[["messageType","document"],["resubmitOf"]],"message.observe":[["messageReference"]],"bill.enquire":[["biller","billNumber"]]},TL=Y({instructionId:kt,amount:ia,debitReference:kt,creditReference:kt}).readonly(),DL=1e4,Vv=Y({id:kt,operation:Oe(Dc),instructionId:kt,adapter:Ce().regex(Ui),amount:ia.optional(),currency:Rn.optional(),masterReference:kt.optional(),legs:ye(TL).min(1).max(256).optional(),date:Qn.date().optional(),cursor:Ce().regex(/^(0|[1-9][0-9]{0,15})$/).optional(),messageType:Ce().regex(To).optional(),messageReference:kt.optional(),document:Ce().min(1).max(DL).optional(),resubmitOf:kt.optional(),biller:kt.optional(),billNumber:kt.optional()}).superRefine((e,t)=>{let[n,r=[]]=ZL[e.operation];for(let i of Object.keys(e))i==="id"||i==="operation"||i==="instructionId"||i==="adapter"||!n.includes(i)&&!r.includes(i)&&t.addIssue({code:"custom",path:[i],message:`a ${e.operation} call carries no ${i}`});for(let i of n)e[i]===void 0&&t.addIssue({code:"custom",path:[i],message:`a ${e.operation} call names its ${i}`});if(!e.legs)return;e.legs[0]?.instructionId!==e.instructionId&&t.addIssue({code:"custom",path:["instructionId"],message:"a post names its first leg's hold as its instruction"}),new Set(e.legs.map(i=>i.instructionId)).size!==e.legs.length&&t.addIssue({code:"custom",path:["legs"],message:"a post books each hold once"}),e.legs.every(i=>ia.safeParse(i.amount).success)&&e.amount!==void 0&&ia.safeParse(e.amount).success&&e.legs.reduce((i,s)=>i+BigInt(s.amount),0n)!==BigInt(e.amount)&&t.addIssue({code:"custom",path:["amount"],message:"a post's amount is the total of its legs"})}).readonly(),n0=Y({adapter:Ce().regex(Ui),externalReference:kt,instructionId:kt,outcome:PL,observedAt:Qn.datetime(),reason:Ce().min(1).max(240).optional(),amount:ia.optional(),currency:Rn.optional(),providerFee:Yy.optional(),netAmount:Yy.optional(),valueDate:Qn.date().optional(),holdExpiresAt:Qn.datetime().optional(),providerCode:e0.optional(),reasonCode:e0.optional(),callId:kt.optional(),statusReports:Gn().int().min(0).max(1e6).optional(),evidence:gn(Ce().regex(/^[a-z][a-zA-Z0-9_]{0,79}$/),Ce().min(1).max(1e4)).optional(),items:ye(SL).min(1).max(Ao).optional()}).superRefine((e,t)=>{let n=(d,p)=>t.addIssue({code:"custom",path:[d],message:p}),{items:r}=e;if(r){let d=r.filter(p=>p.outcome==="confirmed");if(e.outcome!=="confirmed"&&e.outcome!=="rejected")n("items","only a confirmation or a rejection carries items");else if(e.outcome==="rejected"&&d.length)n("items","a rejection confirms no item");else if(e.outcome==="confirmed"){let p=Xv(d);d.length?(e.amount===void 0||p!==void 0&&ia.safeParse(e.amount).success&&p!==BigInt(e.amount))&&n("amount","a confirmation's amount is the total of its confirmed items"):n("items","a confirmation confirms at least one item")}new Set(r.map(p=>p.reference)).size!==r.length&&n("items","each item is answered once"),r.some(p=>p.outcome==="confirmed"&&(p.reasonCode!==void 0||p.reason!==void 0))&&n("items","only a rejected item carries a reason")}e.amount===void 0!=(e.currency===void 0)&&n("currency","amount and currency must be reported together");let a=e.outcome==="confirmed";e.amount!==void 0&&!a&&e.outcome!=="authorized"&&n("amount","only a confirmation or an authorization carries an amount");for(let d of["providerFee","netAmount","valueDate"])e[d]!==void 0&&!a&&n(d,`only a confirmation carries ${d}`);(e.providerFee!==void 0||e.netAmount!==void 0)&&e.amount===void 0&&n("amount","a fee or net amount needs the amount it came from"),e.holdExpiresAt!==void 0&&e.outcome!=="authorized"&&n("holdExpiresAt","only an authorization carries holdExpiresAt");let i=d=>d===void 0||Yy.safeParse(d).success;if(e.amount===void 0||![e.amount,e.providerFee,e.netAmount].every(i))return;let s=BigInt(e.amount),o=BigInt(e.providerFee??"0");o>s?n("providerFee","the provider fee cannot exceed the amount"):e.netAmount!==void 0&&BigInt(e.netAmount)!==s-o&&n("netAmount","netAmount must equal amount less providerFee")}).readonly(),RL=Y({adapter:Ce().regex(Ui),externalReference:kt,accountId:kt,amount:Ce().regex(/^[1-9][0-9]{0,17}$/),currency:Rn,observedAt:Qn.datetime()}).readonly(),Wv=Y({adapter:Ce().regex(Ui),reference:kt,accountReference:kt,amount:Ce().regex(/^-?[1-9][0-9]{0,17}$/),currency:Rn,valueDate:Qn.date(),observedAt:Qn.datetime(),originalReference:kt.optional()}).readonly();As=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.name="AdapterDeclarationError",this.code=t}},Rc=/^[a-z][a-zA-Z0-9_]*$/,Nv=Sv;HL=/^\$[A-Za-z]+$/,Jy=/\{(\$[A-Za-z]+)\}/g,Mv=/^[a-z][a-zA-Z0-9_]{0,79}$/,NL=["capture","adjust","refund"],Bv=["$instructionId","$callId","$messageType","$document","$resubmitOf"];BL=/^[1-9][0-9]{0,4}[smhd]$/,Jv={s:1e3,m:6e4,h:36e5,d:864e5},UL=30*Jv.d;KL=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,XL=["host","content-type","content-length"],Uv=/^[\x21-\x7e]{1,80}$/,VL=/^[1-9][0-9]{0,4}[smhd]$/});function ej(e){return QL.includes(e)?qa.provider:e}function hr(e,t,n,r,a,i={}){if(ej(e.adapter)!==qa.provider)throw new Error("instruction adapter mismatch");return n0.parse({adapter:e.adapter,instructionId:e.id,outcome:t,externalReference:n,observedAt:r,...a?{reason:a}:{},...i})}function e2(e){return e.items?.map(t=>{let n=Yv(t.payee)?BigInt(t.amount)>Hc?{code:"AM02",text:"the line is over the fixture bank's per-payout limit of 100,000.00"}:void 0:{code:"AC03",text:"the payee is not a valid IBAN"};return{reference:t.reference,outcome:n?"rejected":"confirmed",amount:t.amount,...n?{reasonCode:n.code,reason:n.text}:{}}})}function nj(e,t){let n=e2(e);return n?.every(r=>r.outcome==="rejected")?{status:"RJCT",statusReason:{code:n[0].reasonCode,text:"the bank refused every line of the batch"}}:n?{status:t==="submit"?"ACSP":"ACSC"}:BigInt(e.amount)>Hc?{status:"RJCT",statusReason:{code:"AM02",text:"the amount is over the fixture bank's per-payout limit of 100,000.00"}}:{status:t==="submit"?"ACSP":"ACSC"}}function rj(e,t,n){let r=nj(e,t),a=r0(qa.states.payout,r),s=a.outcome==="confirmed"||a.outcome==="rejected"?e2(e):void 0,o=s?s.filter(p=>p.outcome==="confirmed").reduce((p,u)=>p+BigInt(u.amount),0n).toString():e.amount,d=a.outcome==="rejected"?`reject:${e.id}`:a.outcome==="confirmed"?`settle:${e.id}`:`ack:${e.id}`;return hr(e,a.outcome,d,n,r.statusReason?.text,{providerCode:a.providerCode,...a.reasonCode?{reasonCode:a.reasonCode}:{},...a.outcome==="confirmed"?{amount:o,currency:e.currency,providerFee:"0",netAmount:o,valueDate:n.slice(0,10)}:{},...s?{items:s}:{}})}function Gv(e){let t=e.amountDue-e.paid,n=(r,a)=>r<a?r:a;return e.minimum===void 0&&e.maximum===void 0?{low:t,high:t}:{low:n(e.minimum??1n,t),high:n(e.maximum??t,t)}}function oj(e,t){let n;try{n=JSON.parse(t)}catch{return t}if(!e.startsWith("MT")||typeof n!="object"||!n)return t;let r=d=>{let p=String(d).replace(/\r?\n|-\}/g," "),u=/^[0-9]{2}([0-9]{2})-([0-9]{2})-([0-9]{2})$/.exec(p);if(u)return`${u[1]}${u[2]}${u[3]}`;let m=/^([A-Z]{3}) (-?[0-9]+)(?:\.([0-9]+))?$/.exec(p);return m?`${m[1]}${m[2]},${m[3]??""}`:p},a=sj[e]??[],i=new Set(a.map(([,d])=>d)),s=a.filter(([,d])=>Object.hasOwn(n,d)).map(([d,p])=>`:${d}:${r(n[p])}`),o=Object.keys(n).filter(d=>!i.has(d)).sort().map(d=>`/${d}/${r(n[d])}`);return o.length&&s.push(`:72Z:${o.join(`
|
|
68
68
|
`)}`),`{2:I${e.slice(2)}}{4:
|
|
69
69
|
${s.join(`
|