fig-tree-evaluator 3.0.0-preview.8 → 3.0.0-preview.9

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.
@@ -1 +1 @@
1
- import{a as e,i as t,k as r,f as a,d as n,D as o,E as s,g as i,c as l,n as c,o as u,h as d,S as p,q as f,e as m,p as h,s as v,u as y,j as g,v as b,w,r as k,t as $,l as x,R as j,F as O,x as P,b as A,y as D,z as S,W as C,A as N,B as z,G as T}from"./shared.js";const E={ok:!0},q=e=>null===e?"null":Array.isArray(e)?"array":typeof e,M=(e,t)=>({ok:!1,expected:e,actual:q(t)}),F=(t,r)=>{switch(r){case"any":return!0;case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"array":return Array.isArray(t);case"object":return e(t);case"null":return null===t;default:return!1}},R=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),I=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),V=t=>{if("string"==typeof t)return I.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&I.has(e));if(e(t)&&"literal"in t){const e=t.literal;return Array.isArray(e)&&e.length>0&&e.every(e=>["string","number","boolean"].includes(typeof e))}return!1},L=(e,r)=>{if(t(r)){if(-1!==r.literal.indexOf(e))return E;const t=r.literal.map(e=>JSON.stringify(e)).join(", ");return M(`one of ${t}`,e)}return"string"==typeof r?F(e,r)?E:M(r,e):r.some(t=>F(e,t))?E:M(r.join(" | "),e)},W=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return M("array",e);if(e.length!==t.length)return{ok:!1,expected:`array of length ${t.length}`,actual:`array of length ${e.length}`}}if(t.homogeneous){if(!Array.isArray(e))return M("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>F(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:J(e)}}}if(t.elementShape){if(!Array.isArray(e))return M("array",e);for(let r=0;r<e.length;r++){const a=K(e[r],t.elementShape);if(!a.ok)return a}}return E},J=e=>{const t=q(e[0]),r=e.find(e=>q(e)!==t);return void 0===r?`array of ${t}`:`${q(r)} beside ${t}`},B=["length","homogeneous","elementShape"],U=t=>{if(!e(t))return M("a constraints object",t);for(const e of Object.keys(t))if(!B.includes(e))return{ok:!1,expected:`one of ${B.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return M("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&V(a)))return M("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return M("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return M(`a declaration for "${t}"`,r);if(void 0!==r.type&&!V(r.type))return M(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return M(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=U(r.constraints);if(!e.ok)return e}}}return E},K=(t,r)=>{if(!e(t))return M("object",t);const a=Object.keys(r);for(let e=0;e<a.length;e++){const n=a[e],o=r[n],s=Object.prototype.hasOwnProperty.call(t,n),i=!1!==o.required;if(s){if(void 0!==o.type){const e=L(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=W(t[n],o.constraints);if(!e.ok)return e}}else if(i)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return E},G=(e,t,r)=>{if(!r||!Array.isArray(e))return W(e,t);const{length:a,...n}=t;if(void 0!==a){const t=W(e,{length:a});if(!t.ok)return t}return W(e.filter(e=>null!==e),n)},_=["logic","comparison","math","string","array","data","io","other"],H=Symbol("fig-tree:EvaluationData"),Q=Symbol("fig-tree:validated-operator"),X=e=>"object"==typeof e&&null!==e&&!0===e[Q],Y="<array>",Z="<object>",ee=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?Y:Z,te=e=>null!==e&&"object"==typeof e,re="a composite element renders as a placeholder, never as text — drill in, or join it explicitly",ae=[!1,null,0,""],ne=e=>-1===ae.indexOf(e),oe=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:se(String(e),String(t)),se=(e,t)=>{const r=Array.from(e),a=Array.from(t),n=Math.min(r.length,a.length);for(let e=0;e<n;e++){const t=r[e].codePointAt(0),n=a[e].codePointAt(0);if(t!==n)return t<n?-1:1}return r.length===a.length?0:r.length<a.length?-1:1},ie=e=>e.trim(),le=/\s+$/,ce=/^\s+/,ue=e=>e.replace(le,""),de=e=>e.replace(ce,""),pe=e=>Array.from(e),fe=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},me=Object.prototype.hasOwnProperty,he=(e,t)=>{for(const r of e.keys())if(ve(r,t))return r},ve=(e,t)=>{let r,a,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((a=e.length)===t.length)for(;a--&&ve(e[a],t[a]););return-1===a}if(r===Set){if(e.size!==t.size)return!1;for(a of e){if(n=a,n&&"object"==typeof n&&(n=he(t,n),!n))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(a of e){if(n=a[0],n&&"object"==typeof n&&(n=he(t,n),!n))return!1;if(!ve(a[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((a=e.byteLength)===t.byteLength)for(;a--&&e.getInt8(a)===t.getInt8(a););return-1===a}if(ArrayBuffer.isView(e)){if((a=e.byteLength)===t.byteLength)for(;a--&&e[a]===t[a];);return-1===a}if(!r||"object"==typeof e){for(r in a=0,e){if(me.call(e,r)&&++a&&!me.call(t,r))return!1;if(!(r in t)||!ve(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},ye=e=>!e.includes("{")&&!e.includes("}")&&(e.startsWith("$")?e.length>1:r(e).ok),ge=e=>{const t=[];let r="";const a=()=>{""!==r&&(t.push({kind:"text",text:r}),r="")};let n=0;for(;n<e.length;){const o=e[n];if("%"===o){let s=n+1;for(;s<e.length&&e[s]>="0"&&e[s]<="9";)s++;if(s>n+1){const r=e.slice(n,s);a(),t.push({kind:"positional",raw:r,index:Number(r.slice(1))}),n=s;continue}r+=o,n++;continue}if("{"===o&&"{"===e[n+1]){const o=e.indexOf("}}",n+2);if(-1!==o){const r=e.slice(n+2,o);if(ye(r)){a(),t.push({kind:"named",raw:e.slice(n,o+2),body:r}),n=o+2;continue}}r+="{{",n+=2;continue}r+=o,n++}return a(),t},be=e=>{const t={maxDepth:0};return{constant:we(t,e,0),depth:t.maxDepth}},we=(e,t,r)=>{if(r>o)return!1;if(r>e.maxDepth&&(e.maxDepth=r),void 0===t)return!1;if("string"==typeof t){const e=a(t).kind;return"plain"===e||"unrecognized"===e}if(Array.isArray(t)){for(let a=0;a<t.length;a++)if(!we(e,t[a],r+1))return!1;return!0}if(n(t)){for(const e in t){if("operator"===e||"fragment"===e||"vars"===e||"//"===e)return!1;if(e.startsWith("$"))return!1}for(const a in t)if(!we(e,t[a],r+1))return!1;return!0}return!0},ke=(e,t)=>({parent:e,key:t}),$e=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},xe=e=>{e.sort((e,t)=>e.order-t.order)},je=e=>e.some(({issue:e})=>"error"===e.severity),Oe=e=>{const t=e.entry.definition.parameters.as;if("structural"!==t?.evaluation)return null;const r=e.params.as;return"constant"===r?.kind&&"string"==typeof r.value?r.value:null},Pe=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,Ae=(e,t,r)=>{"__proto__"===t?Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}):e[t]=r},De=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=Se(n,e.at,r[t],a)}),n},Se=(e,t,r,a)=>{const n=Ce(e,a),[o,...s]=t;return Ae(n,o,0===s.length?r:Se(n[o],s,r,a)),n},Ce=(e,t)=>{if(t.has(e))return e;const r=Array.isArray(e)?[...e]:{...e};return t.add(r),r},Ne=/*#__PURE__*/new Set(["data","vars","params","element","index","d","v","p","e","i"]),ze=(e,t,r={})=>{const a={registry:t,recognizes:e=>((e,t)=>"literal"===t||void 0!==Cr(e,t)||e.fragments.has(t))(t,e),issues:[],order:0,nodeCount:0,maxDepth:0,dataPaths:new Map,dynamic:!1,operators:new Set,fragmentNames:new Set,fragmentCalls:[],dataReads:[],identityOnly:!1,scope:{bindings:[]},asNames:new Set,unrecognized:[],hasNoCache:!1},n=(r.basePath??[]).reduce(ke,null),o=Me(a,e,n,0);Ee(a);const s=xt(o);xe(a.issues);const i=je(a.issues),l={nodeCount:a.nodeCount,maxDepth:a.maxDepth,dependencies:{dataPaths:a.dataPaths,dynamic:a.dynamic,operators:[...a.operators],fragments:[...a.fragmentNames]},identityOnly:a.identityOnly};return{root:o,holes:s,issues:a.issues,hasErrors:i,timeoutShielded:s.every(e=>void 0!==e.timeoutFallback),own:l,...Te(l,a.fragmentCalls,t.fragments),fragmentCalls:a.fragmentCalls,dataReads:a.dataReads,hasNoCache:a.hasNoCache}},Te=(e,t,r)=>{if(0===t.length)return e;const a=new Map(e.dependencies.dataPaths),n=new Set(e.dependencies.operators),o=new Set(e.dependencies.fragments);let{nodeCount:s,maxDepth:i,identityOnly:l}=e,c=e.dependencies.dynamic;for(const e of t){const t=r.get(e.name);if(void 0!==t){s+=t.nodeCount,i=Math.max(i,e.depth+t.maxDepth),l||=t.identityOnly,c||=t.dependencies.dynamic;for(const[e,r]of t.dependencies.dataPaths)a.set(e,r);for(const e of t.dependencies.operators)n.add(e);for(const e of t.dependencies.fragments)o.add(e)}}return{nodeCount:s,maxDepth:i,identityOnly:l,dependencies:{dataPaths:a,dynamic:c,operators:[...n],fragments:[...o]}}},Ee=e=>{if(0!==e.asNames.size)for(const{token:t,issue:r,raw:a}of e.unrecognized)e.asNames.has(t)&&(r.issue={...r.issue,severity:"error",code:s.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},qe=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:$e(n)};void 0!==s.operator&&(i.operator=s.operator),void 0!==s.parameter&&(i.parameter=s.parameter),void 0!==s.suggestion&&(i.suggestion=s.suggestion);const l={issue:i,order:o};return e.issues.push(l),l},Me=(e,t,r,a)=>{const n=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>o)return qe(e,"error",s.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Ie(t,r,n);const i=Fe(e,t,r,a,n);return"operator"!==i.kind&&"fragmentCall"!==i.kind&&"reference"!==i.kind&&"invalid"!==i.kind||e.nodeCount++,i},Fe=(e,t,r,a,o)=>null==t?Re(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Re(t,r,o):"string"==typeof t?Ve(e,t,r,o):Array.isArray(t)?Le(e,t,r,a,o):n(t)?We(e,t,r,a,o):(e.identityOnly=!0,Re(t,r,o)),Re=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Ie=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),Ve=(e,t,r,n)=>{const o=a(t,e.scope);switch(o.kind){case"plain":return Re(t,r,n);case"unrecognized":{const a=qe(e,"warning",s.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,r,n),o=i(t);return null!==o&&e.unrecognized.push({token:o.token,issue:a,raw:t}),Re(t,r,n)}case"invalid":return qe(e,"error",o.code??s.invalidReference,`'${t}': ${o.reason}`,r,n),Ie(t,r,n);case"reference":{const{namespace:a,segments:s,drill:i,binding:l}=o;return void 0!==l?{kind:"reference",namespace:a,segments:s,raw:t,binding:l,path:r,order:n}:("data"===a&&(0===s.length?e.dynamic=!0:Ze(e,s,i.startsWith(".")?i.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:s,raw:t,path:r,order:n})}}},Le=(e,t,r,a,n)=>{const o=Array.from(t,(t,n)=>({key:n,rawChild:t,node:Me(e,t,ke(r,n),a+1)}));return $t(e,t,o,!0,!1,void 0,r,n)},We=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return qe(e,"error",s.malformedNode,o.message,r,n),Ie(t,r,n);case"operator":return Je(e,t,r,a,n);case"fragment":return ht(e,t,r,a,n);case"shorthand":return lt(e,t,o.key,r,a,n);case"plain":return wt(e,t,r,a,n)}},Je=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return qe(e,"error",s.malformedNode,"the 'operator' value must be a literal string",r,n),Ie(t,r,n);if("literal"===o)return mt(e,t,t.value,"value"in t,r,n);const i=Cr(e.registry,o);if(void 0===i){const a=f(o,Pt(e));return qe(e,"error",s.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Ie(t,r,n)}const l=Be(e,i,r,n),c=[];for(const o in t){const i=t[o];"operator"!==o&&"//"!==o&&void 0!==i&&(Ue(e,l,o,i,r,a,n)||("parameters"!==o?Ge(e,l,c,o,i,ke(r,o),n):qe(e,"error",s.malformedNode,"'parameters' is reserved and unused on operator nodes",ke(r,o),n,{operator:l.name})))}return _e(e,l,c,a,n),l},Be=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),Ue=(e,t,r,a,n,o,s)=>"fallback"===r?(t.fallback=Me(e,a,ke(n,"fallback"),o+1),!0):"noCache"===r?(Ke(e,t,a,n,s),!0):"vars"===r&&(t.vars=bt(e,a,n,o,s),!0),Ke=(e,t,r,a,n)=>{!0===r?(t.noCache=!0,e.hasNoCache=!0):qe(e,"error",s.malformedNode,"'noCache' takes only the literal true — it is settled before the subtree runs",ke(a,"noCache"),n,"operator"===t.kind?{operator:t.name}:{})},Ge=(e,t,r,a,n,o,i)=>{if(void 0===t.entry.definition.parameters[a]){const r=f(a,Object.keys(t.entry.definition.parameters));return void qe(e,"error",s.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,o,i,{operator:t.name,parameter:a,suggestion:r})}r.push({name:a,kind:"value",value:n,path:o})},_e=(e,t,r,a,n)=>{const o=t.entry.definition,s=o.resolution.perElement.length>0;let i;if(s){const a=r.find(e=>"as"===e.name&&"structural"===o.parameters.as?.evaluation&&"value"===e.kind);void 0!==a&&"value"===a.kind&&(i=it(e,t,a.value,a.path,n))}for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"!==r&&(t.params[n.name]=tt(e,n,r,a))}if(s){void 0!==i&&e.scope.bindings.push(i);for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"===r&&(t.params[n.name]=tt(e,n,r,a))}void 0!==i&&e.scope.bindings.pop()}et(e,t),He(e,t)},He=(e,t)=>{if("buildString"!==t.name)return;((e,t)=>{const r=t.params.substitutions;if(void 0===r)return;const a="constant"===r.kind?r.value:"skeleton"===r.kind?r.skeleton:void 0;(Array.isArray(a)||n(a))&&Object.values(a).some(te)&&qe(e,"error",s.operatorValidate,re,r.path,r.order,{operator:t.name,parameter:"substitutions"})})(e,t);const r=t.params.template;if("constant"!==r?.kind||"string"!=typeof r.value)return;const a=ge(r.value).filter(e=>"text"!==e.kind);if(0===a.length)return;const o=t.params.substitutions,i=(e=>{if(void 0===e)return{mode:"absent"};if("constant"===e.kind)return Array.isArray(e.value)?{mode:"array",length:e.value.length}:n(e.value)?{mode:"object",keys:new Set(Object.keys(e.value))}:{mode:"dynamic"};if("skeleton"===e.kind){const{skeleton:t,holes:r}=e;if(Array.isArray(t))return{mode:"array",length:t.length};if(n(t)){const e=new Set(Object.keys(t));for(const t of r)e.add(String(t.at[0]));return{mode:"object",keys:e}}}return{mode:"dynamic"}})(o);if(Xe(e,t,r,a,i),"absent"!==i.mode&&"object"!==i.mode)return;const l=[],c=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(c.has(t.body))continue;const a=Ve(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,c.add(t.body),l.push({path:r.path,at:[t.body],node:a}))}0!==l.length&&(t.params.substitutions=Qe(e,t,o,l))},Qe=(e,t,r,a)=>{const n="skeleton"===r?.kind?{...r,skeleton:{...r.skeleton},holes:[...r.holes]}:{kind:"skeleton",skeleton:"constant"===r?.kind?{...r.value}:{},holes:[],path:r?.path??ke(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},Xe=(e,t,r,a,n)=>{const o=(a,n)=>qe(e,"warning",a,n,r.path,r.order,{operator:t.name}),i=(e,t)=>o(s.unboundToken,`'${e}' binds to nothing and renders as its own text${t}`),l=e=>{for(const t of e)o(s.unusedSubstitution,`substitution ${t} is never named by the template`)};if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&o(s.inertReferenceToken,`a reference token needs the named face — beside ${"array"===n.mode?"positional substitutions":"a dynamically supplied map"} it is not recognized and renders as its own text`),"array"===n.mode){const e=new Set,t=[];for(const r of a)"positional"===r.kind&&(r.index>=1&&r.index<=n.length?e.add(r.index):t.push(r));const r=[];for(let t=1;t<=n.length;t++)e.has(t)||r.push(String(t));if(0===t.length)return void l(r);const o=0===n.length?"there are no substitutions":1===n.length?"there is only 1 substitution":`there are only ${n.length} substitutions`;for(const e of t)i(e.raw,` — ${e.index<1?"numbering starts at %1":o}${Ye(r)}`);return}if("object"===n.mode){const e=new Set,t=[];for(const r of a)"named"===r.kind&&(n.keys.has(r.body)?e.add(r.body):r.body.startsWith("$")||t.push(r.raw));const r=[...n.keys].filter(t=>!e.has(t)).map(e=>`'${e}'`);0===t.length&&l(r);for(const e of t)i(e,Ye(r))}},Ye=e=>{if(0===e.length)return"";if(1===e.length)return`, and substitution ${e[0]} is unused`;const t=e[e.length-1];return`, and substitutions ${e.slice(0,-1).join(", ")} and ${t} are unused`},Ze=(e,t,r,a)=>{let n,o;void 0!==r&&c(r)?(n=r,o=t):(o=u(t),n=d(o)),e.dataPaths.set(n,o),e.dataReads.push({kind:"path",key:n,segments:o,path:a})},et=(e,t)=>{if("get"!==t.name||void 0!==t.params.from)return;const r=t.params.path;if(void 0!==r)if("constant"===r.kind)try{const a="string"==typeof r.value?g(r.value):r.value;if(!Array.isArray(a)||!a.every(b))return void(e.dynamic=!0);if(0===a.length)return void(e.dynamic=!0);Ze(e,a,"string"==typeof r.value?r.value:void 0,t.path)}catch{e.dynamic=!0}else e.dynamic=!0},tt=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=ot(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=st(e,t,a);if(null!==r)return r}return"value"===t.kind?Me(e,t.value,t.path,a+1):rt(e,t,a)},rt=(e,t,r)=>{const{order:a,containerDepth:n}=at(e,r),o=nt(e,t.elements,t.basePath,t.offset,n);return $t(e,t.elements,o,!0,!1,void 0,t.basePath,a)},at=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},nt=(e,t,r,a,n)=>Array.from(t,(t,o)=>({key:o,rawChild:t,node:Me(e,t,ke(r,a+o),n+1)})),ot=(e,t,r)=>{const a="slice"===t.kind?t.elements:t.value;if(!Array.isArray(a))return null;const n="slice"===t.kind?t.basePath:t.path,o="slice"===t.kind?t.offset:0,{order:s,containerDepth:i}=at(e,r),l=nt(e,a,n,o,i);if(l.every(e=>"constant"===e.node.kind))return $t(e,a,l,!0,!1,void 0,n,s);return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:s}},st=(e,t,r)=>{if("value"!==t.kind)return null;const a=t.value;if(!n(a)||m(a,e.recognizes))return null;const{order:o,containerDepth:s}=at(e,r),{entries:i,vars:l,changed:c}=kt(e,a,t.path,s,o,!0);if(i.every(e=>"constant"===e.node.kind))return $t(e,a,i,!1,c,l,t.path,o);const u={};for(const{key:e,node:t}of i)u[String(e)]=t;const d={kind:"entries",entries:u,path:t.path,order:o};return void 0!==l&&(d.vars=l),d},it=(e,t,n,o,i)=>{const l=r=>{qe(e,"error",s.invalidAs,r,o,i,{operator:t.name})};if("string"!=typeof n||"plain"!==a(n).kind)return l("'as' must be a literal name — a dynamic value cannot be statically resolved");const c=r(n);if(!c.ok)return l(`'${n}' is not a legal binding name — ${c.reason}`);const u=[n,w(n)];for(const t of u){if(Ne.has(t))return l(`'${n}' collides with the reserved namespace word '${t}'`);if(null!==y(t,e.scope.bindings))return l(`'${n}' collides with an enclosing 'as' binding ('${t}')`)}for(const t of u)e.asNames.add(t);return n},lt=(e,t,r,a,n,o)=>{const i=r.slice(1),l="literal"===i,c=!l&&e.registry.fragments.has(i);for(const n in t)if(n!==r&&!p.has(n))return qe(e,"error",s.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,ke(a,n),o),Ie(t,a,o);const u=t[r],d=ke(a,r);if(l){for(const r of["fallback","vars","noCache"])r in t&&qe(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(a,r),o);return mt(e,t,u,!0,a,o)}if(c)return vt(e,t,i,u,a,n,o);const f=Cr(e.registry,i),m=Be(e,f,a,o);for(const s in t){const i=t[s];s!==r&&"//"!==s&&void 0!==i&&Ue(e,m,s,i,a,n,o)}const h=[];return ct(e,m,h,u,d,o),_e(e,m,h,n,o),m},ct=(e,t,r,a,o,s)=>{if(Array.isArray(a))dt(e,t,r,a,o,s);else if(!n(a)||m(a,e.recognizes))ut(e,t,r,a,o,s);else for(const n in a){const i=a[n];"//"!==n&&void 0!==i&&Ge(e,t,r,n,i,ke(o,n),s)}},ut=(e,t,r,a,n,o)=>{const s=v(t.entry.definition);null!==s?r.push({name:s,kind:"value",value:a,path:n}):pt(e,t,n,o)},dt=(e,t,r,a,n,o)=>{const s=t.entry.definition,i=h(s,a.length);if(null===i)return void ft(e,t,a,n,o);const l=s.positionalParams;for(let e=0;e<i.bound;e++)r.push({name:l[e],kind:"value",value:a[e],path:ke(n,e)});const{restAt:c}=i;null!==c&&r.push({name:s.restParam,kind:"slice",elements:0===c?a:a.slice(c),basePath:n,offset:c})},pt=(e,t,r,a)=>qe(e,"error",s.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),ft=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void pt(e,t,a,n);const i=o.length;qe(e,"error",s.positionalArity,`'${t.name}' takes at most ${i} positional argument${1===i?"":"s"} (${o.join(", ")}), got ${r.length}`,a,n,{operator:t.name})},mt=(e,t,r,a,n,o)=>{if("operator"in t){for(const r in t)"operator"!==r&&"value"!==r&&"//"!==r&&("fallback"!==r&&"vars"!==r&&"noCache"!==r?qe(e,"error",s.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,ke(n,r),o,{operator:"literal"}):qe(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(n,r),o));if(!a)return qe(e,"error",s.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Ie(t,n,o)}return Re(r,n,o)},ht=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return qe(e,"error",s.malformedNode,"the 'fragment' value must be a literal string",r,n),Ie(t,r,n);const i={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};yt(e,i,a);for(const o in t){const l=t[o];"fragment"!==o&&"//"!==o&&void 0!==l&&("parameters"!==o?"fallback"!==o?"vars"!==o?"noCache"!==o?qe(e,"error",s.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,ke(r,o),n):Ke(e,i,l,r,n):i.vars=bt(e,l,r,a,n):i.fallback=Me(e,l,ke(r,"fallback"),a+1):gt(e,i,l,ke(r,"parameters"),a,n))}return i},vt=(e,t,r,a,o,i,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};yt(e,c,i);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=Me(e,n,ke(o,"fallback"),i+1)),"noCache"===a&&Ke(e,c,n,o,l),"vars"===a&&(c.vars=bt(e,n,o,i,l)))}return n(a)?gt(e,c,a,ke(o,`$${r}`),i,l):qe(e,"error",s.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,ke(o,`$${r}`),l),c},yt=(e,t,r)=>{const{name:a,path:n,order:o}=t;e.fragmentNames.add(a);const i=e.registry.fragments.get(a);if(void 0===i){const t=f(a,e.registry.fragments.keys());return void qe(e,"error",s.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,o,{suggestion:t})}t.entry=i,e.fragmentCalls.push({name:a,depth:r}),e.dataReads.push({kind:"call",fragment:i,path:n})},gt=(e,t,r,o,i,l)=>{if(void 0!==r){if(m(r,e.recognizes)||"string"==typeof r&&"reference"===a(r).kind)return t.argumentsMode="dynamic",t.parameters=Me(e,r,o,i+1),void(e.dynamic=!0);if(n(r)){const a={};for(const t in r){const n=r[t];"//"!==t&&void 0!==n&&(a[t]=Me(e,n,ke(o,t),i+1))}return void(t.parameters=a)}qe(e,"error",s.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},bt=(e,t,a,o,i)=>{const l=ke(a,"vars");if(!n(t))return void qe(e,"error",s.invalidVars,"a 'vars' block must be an object of name → expression entries",l,i);const c={};for(const a in t){const n=t[a];if("//"===a||void 0===n)continue;const u=ke(l,a),d=r(a);d.ok?c[a]=Me(e,n,u,o+1):qe(e,"error",s.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,i)}return c},wt=(e,t,r,a,n)=>{const{entries:o,vars:s,changed:i}=kt(e,t,r,a,n);return $t(e,t,o,!1,i,s,r,n)},kt=(e,t,r,a,n,o=!1)=>{let i,l=!1;const c=[];for(const u in t){const d=t[u];if("//"!==u)if("vars"!==u)if(void 0!==d){if(u.startsWith("$")){const t=f(u.slice(1),Pt(e)),a=void 0!==t?` — did you mean '$${t}'?`:o?"":" — data with a '$' key goes inside 'literal'";qe(e,o?"warning":"error",s.unrecognizedIdentifier,`'${u}' is not a registered operator or fragment${o?", so it is a plain key":""}${a}`,ke(r,u),n,{suggestion:void 0===t?void 0:`$${t}`})}c.push({key:u,rawChild:d,node:Me(e,d,ke(r,u),a+1)})}else l=!0;else i=bt(e,d,r,a,n),l=!0;else l=!0}return{entries:c,vars:i,changed:l}},$t=(e,t,r,a,n,o,i,l)=>{const c=[],u=a?new Array(r.length):{};let d=n;for(const{key:e,rawChild:t,node:a}of r)"constant"!==a.kind?(d=!0,"skeleton"!==a.kind||void 0!==a.vars?c.push({path:a.path,at:[e],node:a}):(Ae(u,e,a.skeleton),c.push(...a.holes.map(t=>({...t,at:[e,...t.at]}))))):(Ae(u,e,a.value),a.value!==t&&(d=!0));if(0===c.length)return void 0!==o&&Object.keys(o).length>0&&qe(e,"warning",s.unreferencedVar,"this vars block declares names nothing in its scope references",ke(i,"vars"),l),Re(d||void 0!==o?u:t,i,l);const p={kind:"skeleton",skeleton:u,holes:c,path:i,order:l};return void 0!==o&&(p.vars=o),p},xt=(e,t=[])=>{if("skeleton"===e.kind)for(const r of e.holes)xt(r.node,t);else if("constant"!==e.kind){const r=jt(e);t.push(void 0===r?{node:e}:{node:e,timeoutFallback:r})}return t},jt=e=>{if("operator"===e.kind||"fragmentCall"===e.kind){if(void 0!==e.fallback)return"constant"===e.fallback.kind?{value:e.fallback.value}:void 0;if("operator"===e.kind){const t=e.entry.hostDefaults;return void 0!==t&&Object.hasOwn(t,"fallback")?{value:t.fallback}:void 0}return e.entry?.timeoutFallback}},Ot=new WeakMap,Pt=e=>{const t=Ot.get(e.registry);if(void 0!==t)return t;const r=[...e.registry.operators.keys(),...e.registry.aliases.keys(),...e.registry.fragments.keys()];return Ot.set(e.registry,r),r},At=e=>{switch(e.kind){case"operator":return e.entry.definition.returns;case"fragmentCall":return e.entry?.returns??"any";case"skeleton":return Array.isArray(e.skeleton)?"array":"object";case"constant":return Dt(e.value);default:return"any"}},Dt=t=>{if(null===t)return"null";if(Array.isArray(t))return"array";if(e(t))return"object";switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"any"}},St=/*#__PURE__*/Object.freeze({parsePath:g,resolvePath:k,checkType:L,checkConstraints:W,describeType:q,renderText:ee,isTruthy:ne}),Ct=(e,t={})=>{zt({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),xe(e.issues),e.hasErrors=je(e.issues)},Nt=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:$e(n)};void 0!==s.operator&&(i.operator=s.operator),void 0!==s.fragment&&(i.fragment=s.fragment),void 0!==s.parameter&&(i.parameter=s.parameter),void 0!==s.suggestion&&(i.suggestion=s.suggestion),e.artifact.issues.push({issue:i,order:o})},zt=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Jt(e,t);case"skeleton":{const r=Gt(e,t.vars,t.path);for(const r of t.holes)zt(e,r.node);return void _t(e,r)}case"fragmentCall":return void Lt(e,t);case"elements":for(const r of t.nodes)zt(e,r);return;case"entries":{const r=Gt(e,t.vars,t.path);for(const r in t.entries)zt(e,t.entries[r]);return void _t(e,r)}case"operator":return void Et(e,t)}return t},Tt=e=>"kind"in e&&"string"==typeof e.kind,Et=(e,t)=>{const r=Gt(e,t.vars,t.path);void 0!==t.fallback&&zt(e,t.fallback);const a=t.entry.definition,n=Vt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?Mt(e,n,r,o,a,qt(t,r)):o.required&&Nt(e,"error",s.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}Wt(e,t);const o=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?o.push([r,n]):zt(e,n)}if(o.length>0){const r={as:Oe(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)zt(e,t);e.iteratorFrames.pop(),r.referenced||Nt(e,"warning",s.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}_t(e,r)},qt=(e,t)=>{const{definition:r,hostDefaults:a}=e.entry;if(void 0!==r.parameters[t]?.elementNullPolicy)return!1;for(const[n,o]of r.resolution.entries){if(!o.replacesNullAt?.includes(t))continue;const r=e.params[n];if(void 0===r){if(void 0!==a&&Object.hasOwn(a,n)&&null!==a[n])return!0}else if("constant"!==r.kind||null!==r.value)return!0}return!1},Mt=(e,t,r,a,n,o=!1)=>{if("elements"===n.kind){const o=a.constraints?.length;return void(void 0!==o&&n.nodes.length!==o&&Nt(e,"error",s.typeCheck,`'${t.label}.${r}': expected ${o} element${1===o?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("constant"!==n.kind&&"structural"===a.evaluation&&"as"!==r)return void Nt(e,"error",s.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r});const i=`'${t.label}.${r}'`,l=Rt(a,n,o);void 0!==l&&Nt(e,"error",l.code,l.code===s.returnsMismatch?`${l.reason} — it can never satisfy ${i}`:`${i}: ${l.reason}`,n.path,n.order,{...t.extra,parameter:r});let c=n;for(;"operator"===c.kind||"fragmentCall"===c.kind;){const n=c.fallback;if(void 0===n)return void("operator"===c.kind&&Ft(e,t,r,a,c,o));const l=Rt(a,n,o);void 0!==l&&Nt(e,"warning",s.fallbackMismatch,`this fallback can never satisfy ${i}: ${l.reason}`,n.path,n.order,{...t.extra,parameter:r}),c=n}},Ft=(e,t,r,a,n,o)=>{const i=n.entry.hostDefaults;if(void 0===i||!Object.hasOwn(i,"fallback"))return;const l=It(a,i.fallback,o);void 0!==l&&Nt(e,"warning",s.fallbackMismatch,`'${n.name}' falls back to its operatorDefaults fallback, which can never satisfy '${t.label}.${r}': ${l.reason}`,n.path,n.order,{...t.extra,parameter:r})},Rt=(e,t,r)=>{switch(t.kind){case"constant":return It(e,t.value,r);case"operator":case"fragmentCall":{if("fragmentCall"===t.kind&&void 0===t.entry)return;const r=At(t);if($(r,e.type))return;const a="operator"===t.kind?`'${t.name}'`:`fragment '${t.name}'`;return{code:s.returnsMismatch,reason:`${a} returns ${JSON.stringify(r)}`}}case"skeleton":{const r=L(Array.isArray(t.skeleton)?[]:{},e.type);return r.ok?void 0:{code:s.typeCheck,reason:`expected ${r.expected}, received ${r.actual}`}}default:return}},It=(e,t,r)=>{if(null===t&&(r||!e.required&&!R(e.type)))return;const a=L(t,e.type);if(!a.ok)return{code:s.typeCheck,reason:`expected ${a.expected}, received ${a.actual}`};if(void 0===e.constraints)return;const n=G(t,e.constraints,void 0!==e.elementNullPolicy);return n.ok?void 0:{code:s.typeCheck,reason:`expected ${n.expected}, received ${n.actual}`}},Vt=e=>({label:e.name,extra:{operator:e.name}}),Lt=(e,t)=>{const r=Gt(e,t.vars,t.path);void 0!==t.fallback&&zt(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||Tt(t.parameters)?void 0:t.parameters;if(void 0!==a&&"static"===t.argumentsMode){const r={label:t.name,extra:{fragment:t.name}};for(const o in a){const i=a[o],l=n?.[o];void 0!==l?Mt(e,r,o,i,l):i.required&&Nt(e,"error",s.missingRequired,`fragment '${t.name}' – requires '${o}'`,t.path,t.order,{fragment:t.name,parameter:o})}if(void 0!==n)for(const r in n){const o=n[r];if(void 0===a[r]){const n=f(r,Object.keys(a));Nt(e,"error",s.unknownNodeKey,`fragment '${t.name}' declares no parameter '${r}'${n?` — did you mean '${n}'?`:""}`,o.path,o.order,{parameter:r,suggestion:n})}}}if(void 0!==t.parameters)if(Tt(t.parameters))zt(e,t.parameters);else for(const r in t.parameters)zt(e,t.parameters[r]);_t(e,r)},Wt=(e,t)=>{const r=t.entry.definition.validate;if(void 0===r)return;const a={};for(const e in t.params){const r=t.params[e];"constant"===r.kind&&(a[e]=r.value)}let n;try{n=r(a,St)}catch(r){return void Nt(e,"error",s.operatorValidate,`'${t.name}' validate hook threw: ${r.message}`,t.path,t.order,{operator:t.name})}for(const r of n){const a=void 0!==r.parameter?t.params[r.parameter]:void 0;Nt(e,r.severity,s.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Jt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Bt(e,t);case"params":return void Ut(e,t);case"element":case"index":return void Kt(e,t,t.namespace)}},Bt=(e,t)=>{const r=t.segments[0],a="string"==typeof r?r:void 0;if(void 0!==a)for(let t=e.varsFrames.length-1;t>=0;t--){const r=e.varsFrames[t],n=r.names.get(a);if(void 0!==n){if(n.referenced=!0,null!==r.currentVar){const e=r.edges.get(r.currentVar)??new Set;e.add(a),r.edges.set(r.currentVar,e)}return}}Nt(e,"error",s.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},Ut=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void Nt(e,"error",s.unresolvedParam,`'${t.raw}': $params is only available inside a fragment body`,t.path,t.order);if(0===t.segments.length)return;const a=t.segments[0];"string"==typeof a&&r.has(a)||Nt(e,"error",s.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Kt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Pe(n.as,r,t.binding))return void(n.referenced=!0)}Nt(e,"error",s.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Gt=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=ke(r,"vars");for(const r in t){const o=t[r],i=ke(n,r);for(const t of e.varsFrames)if(t.names.has(r)){Nt(e,"warning",s.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,i,o.order);break}a.names.set(r,{node:o,declaredAt:i,order:o.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,zt(e,r.node),a.currentVar=null;return a},_t=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||Nt(e,"warning",s.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Ht(e,t)}},Ht=(e,t)=>{const r=new Map([...t.names.keys()].map((e,t)=>[e,t])),a=[],n=new Set,o=new Set,i=new Set,l=c=>{if(!o.has(c))if(n.has(c))(a=>{const n=[...a].sort((e,t)=>r.get(e)-r.get(t)),o=n.join("\0");if(i.has(o))return;i.add(o);const l=n.map(e=>`'${e}'`),c=1===l.length?`${l[0]} depends on itself`:`${l.slice(0,-1).join(", ")} and ${l[l.length-1]} form a vars cycle — a var may not depend on itself`,u=t.names.get(n[0]);Nt(e,"error",s.varCycle,c,u.declaredAt,u.order)})(a.slice(a.indexOf(c)));else{n.add(c),a.push(c);for(const e of t.edges.get(c)??[])l(e);a.pop(),n.delete(c),o.add(c)}};for(const e of t.names.keys())l(e)},Qt={capable:!1,effective:!1,disabled:[]},Xt={capable:!0,effective:!0,disabled:[]},Yt=e=>{const{effective:t}=Zt(e,e.root,!1);return xe(e.issues),t},Zt=(e,t,r)=>{switch(t.kind){case"constant":case"reference":return Qt;case"invalid":return Xt;case"skeleton":return nr(e,[...t.holes.map(e=>e.node),...or(t.vars)],r);case"elements":return nr(e,t.nodes,r);case"entries":return nr(e,[...Object.values(t.entries),...or(t.vars)],r);case"operator":return er(e,t,Pr(t.entry),r);case"fragmentCall":return er(e,t,t.entry?.caches??!0,r)}return t},er=(e,t,r,a)=>{const n=!0===t.noCache,o=nr(e,ar(t),a||n),s=r||o.capable,i=tr(t),l=void 0===i?o.disabled:[i,...o.disabled];return n&&a?sr(e,t,"'noCache' is redundant — an enclosing node already sets it"):n&&!s&&sr(e,t,l.length>0?`'noCache' is redundant — caching is already disabled for ${rr(l)}`:"'noCache' is dead — nothing beneath this node caches"),{capable:s,effective:!n&&(r||o.effective),disabled:l}},tr=e=>"operator"===e.kind&&e.entry.definition.cache&&!Pr(e.entry)?e.entry.definition.name:void 0,rr=e=>{const t=[...new Set(e)].map(e=>`'${e}'`);return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`},ar=e=>{const t=[];return"operator"===e.kind?t.push(...Object.values(e.params)):void 0!==e.parameters&&("dynamic"===e.argumentsMode?t.push(e.parameters):t.push(...Object.values(e.parameters))),void 0!==e.fallback&&t.push(e.fallback),t.push(...or(e.vars)),t},nr=(e,t,r)=>{const a={capable:!1,effective:!1,disabled:[]};for(const n of t){const{capable:t,effective:o,disabled:s}=Zt(e,n,r);a.capable||=t,a.effective||=o,a.disabled.push(...s)}return a},or=e=>void 0===e?[]:Object.values(e),sr=(e,t,r)=>{const a={severity:"warning",code:s.uselessModifier,message:r,path:$e(ke(t.path,"noCache"))};"operator"===t.kind?a.operator=t.name:a.fragment=t.name,e.issues.push({issue:a,order:t.order})};class ir{max;entries=new Map;constructor(e){this.max=e,lr(e)}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.max&&this.evictOldest()}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}resize(e){for(lr(e),this.max=e;this.entries.size>this.max;)this.evictOldest()}evictOldest(){const e=this.entries.keys().next();!0!==e.done&&this.entries.delete(e.value)}}const lr=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},cr=Symbol("fig-tree:lazy-handle"),ur="~",dr=(e,t)=>{if(t>o)return"refused";switch(typeof e){case"boolean":return"json";case"string":return e.length>4096?"serializer":"json";case"number":return Number.isFinite(e)&&!Object.is(e,-0)?"json":"serializer";case"undefined":return"serializer";case"object":break;default:return"refused"}if(null===e)return"json";if(Array.isArray(e)){for(let r=0;r<e.length;r++){const a=dr(e[r],t+1);if("json"!==a)return a}return"json"}if(!n(e))return"refused";for(const r in e){if(r.length>4096)return"serializer";const a=dr(e[r],t+1);if("json"!==a)return a}return"json"},pr=(e,t)=>fr(e,0,t)?t.join(""):void 0,fr=(e,t,r)=>{if(t>o)return!1;if(null===e)return hr(r,"n");if(void 0===e)return hr(r,"u");switch(typeof e){case"boolean":return hr(r,e?"t":"f");case"number":return mr(e,r);case"string":return hr(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!fr(a,t+1,r))return!1;return hr(r,"]")}if(!n(e)||cr in e)return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!fr(e[a],t+1,r))return!1;return hr(r,"}")},mr=(e,t)=>Number.isNaN(e)?hr(t,"N"):e===1/0?hr(t,"I"):e===-1/0?hr(t,"J"):Object.is(e,-0)?hr(t,"#-0"):hr(t,`#${String(e)}`),hr=(e,t)=>(e.push(t),!0);class vr{deps;identity=new WeakMap;content=new ir(200);constructor(e){this.deps=e}resolve(e){const t="object"==typeof e&&null!==e?e:void 0;if(void 0!==t){const e=this.identity.get(t);if(void 0!==e)return e}const r=this.deps.probe(e);if(r.constant){const e={kind:"inert",depth:r.depth};return void 0!==t&&this.identity.set(t,e),e}const a=void 0===t?void 0:(e=>{const t=dr(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?pr(e,[ur]):void 0})(e),n=void 0===a?void 0:this.content.get(a),o=n??this.deps.compile(e),s={kind:"artifact",artifact:o};return void 0!==t&&this.identity.set(t,s),void 0!==a&&void 0===n&&!o.identityOnly&&o.holes.length>0&&this.content.set(a,o),s}}const yr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),gr=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),br=(t,a,n)=>{const o=(...e)=>["fragments",t,...e],i=r(t);if(!i.ok)return void n(s.invalidName,`'${t}' is not a legal fragment name: ${i.reason}`,o());if(x.has(t))return void n(s.reservedName,`'${t}' is a reserved name and may not name a fragment`,o());if(!e(a))return void n(s.invalidDefinition,`fragment '${t}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,o());if(!("expression"in a))return void n(s.invalidDefinition,`fragment '${t}' has no 'expression'`,o());for(const e of Object.keys(a))gr.has(e)||n(s.invalidDefinition,`'${e}' is not a key of a fragment definition`,o(e));const l={name:t,parameters:{},body:{kind:"constant",value:null,path:null,order:0},returns:"any",warnings:[],nodeCount:0,maxDepth:0,dependencies:{dataPaths:new Map,dynamic:!1,operators:[],fragments:[]},identityOnly:!1,caches:!1};if(void 0!==a.description&&("string"!=typeof a.description?n(s.invalidDefinition,"'description' must be a string",o("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(s.invalidDefinition,"'metadata' must be a plain object",o("metadata"))),void 0!==a.parameters)if(e(a.parameters))for(const[e,t]of Object.entries(a.parameters)){const r=wr(e,t,o,n);void 0!==r&&(l.parameters[e]=r)}else n(s.invalidDefinition,"'parameters' must be a plain object",o("parameters"));return l},wr=(t,a,n,o)=>{const i=n("parameters",t),l=r(t);if(!l.ok)return void o(s.invalidName,`'${t}' is not a legal parameter name: ${l.reason}`,i);if(j.has(t))return void o(s.reservedName,`'${t}' is a reserved node key and may not name a parameter`,i);if(!e(a))return void o(s.invalidDefinition,`the declaration of '${t}' must be an object`,i);for(const e of Object.keys(a))yr.has(e)||o(s.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...i,e]);const c=a.type??"any";if(!V(c))return void o(s.invalidDefinition,`'${t}' declares an unknown type`,[...i,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void o(s.invalidDefinition,"'required' must be a boolean",[...i,"required"]);let u;if(void 0!==a.constraints){const e=U(a.constraints);if(!e.ok)return void o(s.invalidDefinition,`'${t}' declares invalid constraints: expected ${e.expected}, got ${e.actual}`,[...i,"constraints"]);u=a.constraints}const d="default"in a;if(d&&!0===a.required)return void o(s.invalidDefinition,`'${t}' is declared required and also declares a default — the default could never apply`,[...i,"default"]);if(d){const e=L(a.default,c);if(!e.ok)return void o(s.typeCheck,`the default for '${t}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...i,"default"]);if(void 0!==u){const e=W(a.default,u);if(!e.ok)return void o(s.typeCheck,`the default for '${t}' violates its declared constraints: expected ${e.expected}, got ${e.actual}`,[...i,"default"])}}const p={type:c,required:a.required??!d};return d&&(p.default=a.default),"string"==typeof a.description&&(p.description=a.description),e(a.metadata)&&(p.metadata=a.metadata),void 0!==u&&(p.constraints=u),p},kr=e=>{const t=new Set,r=new Set,a=e=>{if(r.has(e.name)||t.has(e.name))return;t.add(e.name);const n=e.body;"fragmentCall"===n.kind&&void 0!==n.entry&&a(n.entry),e.returns=At(n),t.delete(e.name),r.add(e.name)};for(const t of e.fragments.values())a(t)},$r=(e,t)=>{const r=[],a=new Set,n=new Set,o=i=>{const l=r.indexOf(i);if(-1!==l){const e=[...r.slice(l),i],a=[...e].sort().join("\0");return n.has(a)||t(s.fragmentCycle,`fragment '${i}' reaches itself: ${e.join(" → ")} — recursion is not supported`,["fragments",i]),void n.add(a)}if(!a.has(i)){r.push(i);for(const t of e.get(i)?.fragmentCalls??[])o(t.name);r.pop(),a.add(i)}};for(const t of e.keys())o(t);return 0===n.size},xr=(e,t)=>{const r=new Set,a=n=>{if(r.has(n))return;r.add(n);const o=e.fragments.get(n),s=t.get(n);if(void 0===o||void 0===s)return;for(const e of s.fragmentCalls)a(e.name);const i=Te(s.own,s.fragmentCalls,e.fragments);o.nodeCount=i.nodeCount,o.maxDepth=i.maxDepth,o.dependencies=i.dependencies,o.identityOnly=i.identityOnly,o.caches=Yt(s),o.timeoutFallback=jr(s,e.fragments)};for(const e of t.keys())a(e)},jr=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=Or(e,t);if(void 0===r)return;n.push(r.value)}let o=0;const s=e=>"skeleton"===e.kind?De(e.skeleton,e.holes,e.holes.map(e=>s(e.node))):n[o++];return{value:s(r)}},Or=(e,t)=>{if(void 0!==e.timeoutFallback)return e.timeoutFallback;const{node:r}=e;return"fragmentCall"===r.kind&&void 0===r.fallback?t.get(r.name)?.timeoutFallback:void 0},Pr=e=>e.definition.cache&&!0!==e.hostDefaults?.noCache,Ar=["fallback","noCache"],Dr=t=>{const r=[],a=(e,t,a,n)=>{r.push({severity:"error",code:e,message:t,path:a,...void 0!==n?{operator:n}:{}})},n={operators:new Map,aliases:new Map,fragments:new Map},{operators:o,aliases:i}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(s.duplicateOperator,`'${e}' is already registered (by '${n}') — one namespace, no silent precedence`,t,r),!1):(l.set(e,r),!0)},u=(e,t)=>{if("function"==typeof e)return void a(s.invalidOptions,`operators[${t[1]}]${t.length>2?`[${t[2]}]`:""} is a function — factories must be called: httpOperators(client)`,t);if(!X(e))return void a(s.invalidOptions,"every operators entry must be built with defineOperator() — a plain definition object is not accepted",t);const{name:r,alias:n}=e,l=c(r,t,r),u=void 0===n||c(n,t,r);l&&u&&(o.set(r,{definition:e}),void 0!==n&&i.set(n,r))};return Array.isArray(t.operators)?t.operators.forEach((e,t)=>{Array.isArray(e)?e.forEach((e,r)=>{Array.isArray(e)?a(s.invalidOptions,"'operators' is flattened one level only — arrays may not nest deeper",["operators",t,r]):u(e,["operators",t,r])}):u(e,["operators",t])}):a(s.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&Sr(t.operatorDefaults,o,i,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(s.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=br(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const o=new Map;for(const[e,a]of r.fragments){const n=t[e],s=ze(n.expression,r,{basePath:["expression"]});a.body=s.root,o.set(e,s)}kr(r);for(const[e,t]of r.fragments){const r=o.get(e);Ct(r,{fragmentParams:new Set(Object.keys(t.parameters))});for(const{issue:t}of r.issues)"error"===t.severity&&n(t.code,`fragment '${e}': ${t.message}`,["fragments",e,...t.path])}$r(o,n)&&xr(r,o);for(const[e,t]of r.fragments)for(const{issue:r}of o.get(e).issues)if("error"!==r.severity){const e={...r,path:[...r.path]};Object.freeze(e.path),t.warnings.push(Object.freeze(e))}})(t.fragments,n,(e,t)=>c(e,t,e),a),r.length>0&&(e=>{const[t]=e,r=e.length-1,a=r>0?`${t.message} (+ ${r} more issue${1===r?"":"s"})`:t.message;throw new O({code:s.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},Sr=(t,r,a,n)=>{if(e(t))for(const[o,i]of Object.entries(t)){const t=["operatorDefaults",o],l=r.get(o);if(void 0===l){const e=a.get(o);void 0!==e?n(s.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${o}'`,t,e):n(s.unknownOperator,`'${o}' names no registered operator`,t);continue}if(!e(i)){n(s.invalidOptions,`the defaults for '${o}' must be a plain object`,t,o);continue}let c=!0;for(const[e,r]of Object.entries(i)){const a=[...t,e];if(Ar.includes(e)){"fallback"!==e||be(r).constant||(n(s.invalidOptions,`the default fallback for '${o}' must be a constant value — it is returned as written, never evaluated`,a,o),c=!1),"noCache"===e&&(!0!==r?(n(s.invalidOptions,"the 'noCache' modifier takes only the literal true",a,o),c=!1):l.definition.cache||(n(s.invalidOptions,`'noCache' on '${o}', which never caches — its definition does not declare 'cache: true'`,a,o),c=!1));continue}const i=l.definition.parameters[e];if(void 0===i){n(s.invalidOptions,`'${e}' names no declared parameter of '${o}' (nor 'fallback'/'noCache')`,a,o),c=!1;continue}if(i.required){n(s.invalidOptions,`'${e}' is a required parameter of '${o}' — operatorDefaults may only target optional parameters`,a,o),c=!1;continue}const u=L(r,i.type);if(u.ok){if(void 0!==i.constraints){const t=W(r,i.constraints);t.ok||(n(s.typeCheck,`the default for '${o}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,o),c=!1)}}else n(s.typeCheck,`the default for '${o}.${e}' does not satisfy its declared type: expected ${u.expected}, got ${u.actual}`,a,o),c=!1}c&&(l.hostDefaults=Object.freeze({...i}))}else n(s.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},Cr=(e,t)=>{const r=e.operators.get(t);if(void 0!==r)return r;const a=e.aliases.get(t);return void 0!==a?e.operators.get(a):void 0},Nr="fig-tree:scope-settled",zr="fig-tree:request-expired",Tr="fig-tree:evaluation-timeout";class Er{parent;controller;upstream;forward;settled=!1;verified=-1;clock;constructor(e){this.parent=e,this.clock=void 0===e?{epoch:0}:e.clock}get aborted(){return void 0!==this.controller?this.controller.signal.aborted:!!this.settled||this.verified!==this.clock.epoch&&(!(void 0===this.parent||!this.parent.aborted)||(this.verified=this.clock.epoch,!1))}get reason(){return void 0!==this.controller?this.controller.signal.reason:this.settled?Nr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(Nr);else if(void 0!==this.parent){const t=this.parent.signal;t.aborted?e.abort(t.reason):(this.upstream=t,this.forward=()=>e.abort(t.reason),t.addEventListener("abort",this.forward,{once:!0}))}}return this.controller.signal}settle(){this.settled||(this.settled=!0,this.clock.epoch+=1,void 0!==this.controller&&(void 0!==this.upstream&&void 0!==this.forward&&this.upstream.removeEventListener("abort",this.forward),this.controller.abort(Nr)))}}const qr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:P}),Mr=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(Nr)}})():(e=>{const t=new AbortController;e.aborted&&t.abort(e.reason);const r=()=>t.abort(e.reason);return e.addEventListener("abort",r,{once:!0}),{signal:t.signal,abort:e=>t.abort(e),settle:()=>{e.removeEventListener("abort",r),t.abort(Nr)}}})(e),{signal:n}=a;let o;const s=new Promise((e,t)=>{o=t});s.catch(P);const i=()=>o(n.reason);n.aborted?i():n.addEventListener("abort",i,{once:!0});const l=void 0===t?void 0:setTimeout(()=>a.abort(r),Math.min(t,2147483647));return{signal:n,expiry:s,settle:()=>{void 0!==l&&clearTimeout(l),n.removeEventListener("abort",i),a.settle()}}},Fr=(e,t)=>Mr(e,t,zr),Rr=(e,t)=>(r,a)=>{const n=(o=[e.operator,e.fingerprint,r],pr(o,[]));var o;return void 0===n?a():(async(e,t,r,a)=>{const n=e.generation,o=await e.lookup(t);if(a?.({type:"cache",hit:o.hit}),o.hit)return o.value;const s=await r();return await e.write(t,s,n),s})(t,n,a,e.note)},Ir=/*#__PURE__*/Object.freeze({}),Vr=(e,t)=>!0!==t||!0===e.noCache?e:{...e,noCache:t};class Lr{options;cache;trace;#e;constructor(e,t,r,a){this.options=t,this.cache=r,this.trace=a,this.#e=e}get signal(){return this.#e.signal}}const Wr={memo:(e,t)=>t()},Jr={note:P},Br=Symbol("fig-tree:internal-error"),Ur=e=>ea(`[fig-tree internal] ${e}`,Br),Kr=e=>ra(e,Br),Gr=Symbol("fig-tree:cancelled"),_r=()=>ea("[fig-tree] evaluation cancelled",Gr),Hr=e=>ra(e,Gr),Qr=(e,t,r)=>e.rootScope.aborted?Xr(e.rootScope.reason,t,r):e.abortScope.aborted?_r():void 0,Xr=(e,t,r)=>e===Nr?_r():Yr(e,$e(t),{operator:r}),Yr=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===Tr,i=void 0===n?"":`${n}ms `;return new O({code:o?s.timeout:s.aborted,message:o?`evaluation exceeded its ${i}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},Zr=e=>A(e)&&(e.code===s.aborted||e.code===s.timeout),ea=(e,t)=>{const r=new Error(e);return ta(r,t),r},ta=(e,t)=>{e[t]=!0},ra=(e,t)=>e instanceof Error&&!0===e[t],aa=()=>performance.now(),na=e=>{const t=new Map,r=new WeakMap,a=new WeakSet;let n;const o=(e,r,n)=>{const o=t.get(e);if(void 0===o)return;t.delete(e),a.has(e)||("fallback"!==e.status&&(e.status=r),void 0!==n.error&&void 0===e.error&&(e.error=n.error),"failed"!==r&&"cancelled"!==r&&(e.value=n.value),void 0!==n.elapsed&&(e.elapsed=n.elapsed));const s=[...o.children,...oa(o)];s.length>0&&(e.children=s.sort((e,t)=>e.order-t.order||e.index-t.index).map(e=>e.entry))},s=(e,t)=>{(e.events??=[]).push(t)},i=(e,a,o,s)=>{const i=pa(e),l=fa(e),c={path:$e(e.path),kind:ua(e),status:"value",...void 0!==o?{source:o}:{},...void 0!==i?{operator:i}:{},...void 0!==l?{ref:l}:{},...void 0!==s?.var?{var:s.var}:{}};return t.set(c,{node:e,children:[],seen:new Set,started:aa()}),r.set(e,c),((e,r,a)=>{if(void 0===e)return void(n=r.entry);const o=t.get(e);void 0!==o&&(o.children.push(r),o.seen.add(a))})(a,{entry:c,order:e.order,index:s?.index??0},e),c};return{enter:(e,t,r,a)=>i(e,t,void 0!==r?{fragment:r.fragment}:void 0,a),settle:o,markFallback:(e,t)=>{e.status="fallback",e.error=t},note:s,markShielded:(e,n,l)=>{const c=r.get(e),u=void 0===c?void 0:t.get(c);if(void 0===c||void 0===u)return;a.add(c),c.status="fallback",c.error=n,c.value=l,c.elapsed=aa()-u.started,s(c,{type:"shielded-fallback"});const d=da(e);void 0!==d&&o(i(d,c,c.source,void 0),"value",{value:l})},finish:()=>{for(const e of[...t.keys()].reverse())o(e,"cancelled",{});return void 0!==n&&e.length>0&&(n.warnings=e),n}}},oa=e=>sa(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:$e(e.path),kind:ua(e),status:"skipped"},order:e.order,index:0})),sa=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(ia),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...la(e.parameters),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{}),...void 0!==e.entry?[e.entry.body]:[]];case"skeleton":return[...e.holes.map(e=>e.node),...Object.values(e.vars??{})];case"elements":return e.nodes;case"entries":return Object.values(e.entries);default:return[]}},ia=e=>"elements"===e.kind||"entries"===e.kind?sa(e):[e],la=e=>void 0===e?[]:ca(e)?[e]:Object.values(e),ca=e=>"string"==typeof e.kind,ua=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},da=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.fallback:void 0,pa=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,fa=e=>"reference"===e.kind?e.raw:void 0,ma=(e,t)=>{if(void 0===t)return e;const r={parent:e.scope,vars:new Map},a={...e,scope:r};for(const[e,n]of Object.entries(t))r.vars.set(e,D(()=>tn(n,a,{var:e})));return a},ha=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await ya(e,t,a):va(e,t,a),frame:n};delete o.scope,delete o.bindings;const s=await tn(t.body,o);return void 0===s?null:s},va=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,s]of Object.entries(t.parameters)){const t=a[o],i=D(async()=>{if(void 0===t)return ga(e,o,s,r);let a;try{a=await tn(t,r)}catch(e){throw xa(e,r.frame)}return ba(e,o,s,a,t.path,r)});n.set(o,()=>{const e=i();return e.catch(P),e})}return n},ya=async(t,r,a)=>{const n=t.parameters;let o;try{o=await tn(n,a)}catch(e){throw xa(e,a.frame)}if(!e(o))throw xa(wa(t,s.typeCheck,`'parameters' must evaluate to an object, received ${ka(o)}`,n.path),a.frame);const i=new Map;for(const[e,s]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?ba(t,e,s,o[e],n.path,a):ga(t,e,s,a,n.path);i.set(e,()=>Promise.resolve(r))}return i},ga=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw xa(wa(e,s.missingRequired,`requires '${t}'`,n),a.frame)},ba=(e,t,r,a,n,o)=>{const i=void 0===a?null:a;if(null===i&&!r.required&&!R(r.type))return r.default??null;const l=L(i,r.type);if(!l.ok)throw xa(wa(e,s.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=W(i,r.constraints);if(!a.ok)throw xa(wa(e,s.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return i},wa=(e,t,r,a)=>new O({code:t,message:`fragment '${e.name}' – ${r}`,path:$e(a)}),ka=e=>null===e?"null":Array.isArray(e)?"array":typeof e,$a=Symbol("fig-tree:anchored"),xa=(e,t)=>!A(e)||ra(e,$a)?e:(ta(e,$a),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=$e(t.callPath)),e);class ja extends Error{code;errorData;constructor(e,t={}){super(e),this.name="OperatorFailure",void 0!==t.code&&(this.code=t.code),void 0!==t.errorData&&(this.errorData=t.errorData)}}const Oa=e=>e instanceof ja,Pa=(e,t,r)=>Da(Array.from({length:e},(e,a)=>Aa(a,()=>t(a),r)),e),Aa=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},Da=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[cr]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},Sa=e=>({[cr]:!0,evaluate:D(e)}),Ca=e=>({[cr]:!0,evaluate:()=>Promise.resolve(e)}),Na=(e,t,r,a,n)=>Sa(async()=>za(await tn(e,n),t,r,a)),za=(e,t,r,a)=>{const n=L(e,a.type);if(!n.ok)throw Fa(t,r,n);if(null!==e&&void 0!==a.constraints){const n=G(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw Fa(t,r,n)}return a.truthiness?La(e,a.type):e},Ta=(e,t,r,a,n,o)=>{const s=Array.isArray(t)?t:[],i=Oe(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>za(await tn(e,((e,t,r,a)=>({...e,bindings:{parent:e.bindings,as:t,element:r,index:a}}))(o,i,s[t],t),{index:t}),r,a,n))();return u.catch(P),l.set(t,u),u};return{[cr]:!0,evaluate:c,settle:()=>Pa(s.length,c,e=>e)}},Ea=(e,t)=>t.truthiness?ne(e):e,qa=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>Sa(async()=>Ea(await tn(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>Pa(e.length,r=>tn(e[r],t,{index:r}),r))(e.nodes,r,e=>Ea(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=ma(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=Sa(async()=>Ea(await tn(o,a),t));return n}},Ma=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>Ca(Ea(e,t)));case"race":return((e,t)=>Pa(e.length,t=>Promise.resolve(e[t]),t))(e,e=>Ea(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=Ca(Ea(n,t));return r}case"lazy":return Ca(e);default:return e}},Fa=(e,t,r)=>new O({code:s.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:$e(e.path),operator:e.name}),Ra=(e,t,r)=>{if("string"==typeof t.nullPolicy)return t.nullPolicy;const a=t.nullPolicy,n=e.entry.definition.parameters[a.selector],o=r[a.selector],s=L(o,n.type);if(!s.ok)throw Fa(e,a.selector,s);const i=a.table.find(e=>e.value===o);if(void 0===i)throw Ur(`no null-policy row for ${e.name}.${a.selector}`);return i.policy},Ia=async(t,r,a)=>{if(void 0!==r.elementNullPolicy){if(Array.isArray(t)&&t.includes(null)){const e=await a();return t.map(t=>null===t?e:t)}if(e(t)&&Object.values(t).includes(null)){const e=await a(),r={};for(const[a,n]of Object.entries(t))r[a]=null===n?e:n;return r}return t}return null===t?a():t},Va=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),La=(t,r)=>{if((e=>!("object"==typeof e&&!Array.isArray(e))&&(Array.isArray(e)?e:[e]).every(e=>"array"===e||"object"===e))(r)){if(Array.isArray(t))return t.map(ne);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=ne(a);return e}}return ne(t)},Wa=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,hostDefaults:a}=e.entry,{entries:n,whole:o,perElement:s}=r.resolution,i=[],l=[],c={};let u;const d={};for(const[r,o]of n){const n=e.params[r];switch(o.evaluation){case"eager":void 0!==n&&(i.push(r),l.push(tn(n,t)));break;case"structural":"constant"===n?.kind&&(c[r]=n.value);break;case"lazy":if(void 0!==o.replacesNullAt){const e=void 0!==n?D(()=>tn(n,t)):void 0!==a&&Object.hasOwn(a,r)?D(()=>a[r]):void 0;if(void 0!==e)for(const t of o.replacesNullAt)(u??={})[t]=e;break}void 0!==n&&(d[r]=Na(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=qa(n,o,t);if(void 0!==e){d[r]=e;break}i.push(r),l.push(tn(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[i[0]]=S(e)?await e:e}else{const e=await Promise.all(l);i.forEach((t,r)=>{c[t]=e[r]})}for(const[e,r]of o){if(Object.hasOwn(d,e))continue;const n=c[e];(void 0===n||null===n&&!r.required&&!R(r.type))&&(void 0!==a&&Object.hasOwn(a,e)?c[e]=a[e]:"default"in r?c[e]=r.default===H?t.data:r.default:delete c[e])}for(const[t,r]of o){if(Object.hasOwn(d,t))continue;let a=c[t];if(void 0===a)continue;const n=u?.[t];void 0!==n&&(a=await Ia(a,r,n));const o="eager"!==r.evaluation&&"structural"!==r.evaluation;if(null===a&&R(r.type)&&!o&&"propagate"===Ra(e,r,c))return{params:d,propagate:!0};if("propagate"===r.elementNullPolicy&&Va(a))return{params:d,propagate:!0};a=za(a,e,t,r),d[t]=Ma(a,r)}for(const[r,a]of s){if(void 0===a.over)throw Ur(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=Ta(n,d[a.over],e,r,a,t))}return{params:d,propagate:!1}})(e,t);if(a)return null;const{definition:n}=e.entry,o=!0!==t.noCache&&Pr(e.entry),s=Ba(n,r),i=void 0===s?void 0:Fr(t.abortScope.signal,s),l=void 0===i?t:{...t,abortScope:qr(i.signal,t.abortScope)},c=(e=>{const{trace:t,traceParent:r}=e;if(void 0!==t&&void 0!==r)return e=>{t.note(r,e)}})(t),u=((e,t,r,a)=>new Lr(e.abortScope,e.options,r?{memo:Rr({operator:t.name,fingerprint:t.fingerprint,note:a},e.cache)}:Wr,void 0===a?Jr:{note:a}))(l,n,o,c);try{return await Ja(e,t,r,u,i)}catch(r){throw Ua(r,e,t,i,s)}finally{i?.settle()}},Ja=async(e,t,r,a,n)=>{const o=Qr(t,e.path,e.name);if(void 0!==o)throw o;const s=Promise.resolve(e.entry.definition.evaluate(r,a));return void 0===n?Ga(await s,e):(s.catch(P),Ga(await Promise.race([s,n.expiry]),e))},Ba=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},Ua=(e,t,r,a,n)=>{if(Kr(e)||Hr(e))return e;const o=Qr(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===zr?new ja(`request exceeded its ${String(n)}ms timeout`,{code:s.requestTimeout}):e},Ka=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>tn(r,t);const a=e.entry.hostDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Ga=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new O({code:s.nonFiniteResult,message:`${t.name} – produced a non-finite number (${String(e)})`,path:$e(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[cr])throw new O({code:s.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:$e(t.path),operator:t.name});var r;return e},_a=(e,t)=>{if(A(e))return e;if(Oa(e))return new O({code:e.code??s.operatorFailure,message:`${t.name} – ${e.message}`,path:$e(t.path),operator:t.name,...void 0!==e.errorData?{errorData:e.errorData}:{}});const r=e instanceof Error?e.message:String(e);return new O({code:s.operatorFailure,message:`${t.name} – ${r}`,path:$e(t.path),operator:t.name})},Ha=(e,t)=>0===e.segments.length?t.data:Za(t.data,e.segments,e,t,"is absent from the evaluation data"),Qa=async(e,t)=>{const[r,...a]=e.segments,n="string"==typeof r?((e,t)=>{for(let r=e;void 0!==r;r=r.parent){const e=r.vars.get(t);if(void 0!==e)return e}})(t.scope,r):void 0;if("string"!=typeof r||void 0===n)throw Ur(`'${e.raw}': no var named '${String(r)}' is in scope — the static gate should have refused it`);const o=await n();return 0===a.length?en(o):Za(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Xa=async(e,t)=>{const r=t.params;if(void 0===r)throw Ur(`'${e.raw}': $params outside a fragment body — the static gate should have refused it`);const[a,...n]=e.segments;if(void 0===a){const e={};return await Promise.all([...r].map(async([t,r])=>{e[t]=en(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Ur(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const s=await o();return 0===n.length?en(s):Za(s,n,e,t,`is absent from the value of '$params.${String(a)}'`)},Ya=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Pe(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Ur(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?en(a.element):Za(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Za=(e,t,r,a,n)=>{const o=k(e,t);if(o.found)return en(o.value);if(!a.strictDataPaths)return null;throw new O({code:s.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:$e(r.path)})},en=e=>void 0===e?null:e,tn=(e,t,r)=>void 0!==t.trace?rn(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(Qr(t,e.path)):an(e,t),rn=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=aa();try{if(t.abortScope.aborted)throw Qr(t,e.path);const a=await an(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:aa()-o}),a}catch(e){throw r.settle(n,Hr(e)?"cancelled":"failed",{...A(e)?{error:e}:{},elapsed:aa()-o}),e}},an=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Ha(e,t);case"vars":return Qa(e,t);case"params":return Xa(e,t);case"element":case"index":return Ya(e,t)}})(e,t);case"skeleton":return nn(e,t);case"operator":return(async(e,t)=>{const r=ma(Vr(t,e.noCache),e.vars),a=e.entry.definition.deliversLazily?new Er(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await Wa(e,n)}finally{a?.settle()}}catch(a){if(Kr(a)||Hr(a)||Zr(a))throw a;const n=_a(a,e),o=Ka(e,r);if(void 0===o)throw n;try{const e=await o();return void 0!==t.trace&&void 0!==t.traceParent&&t.trace.markFallback(t.traceParent,n),e}catch(t){if(Kr(t)||Hr(t)||Zr(t))throw t;const r=_a(t,e);throw void 0===r.cause&&(r.cause=n),r}}})(e,t);case"fragmentCall":return(async(e,t)=>{const{entry:r}=e;if(void 0===r)throw Ur(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=ma(Vr(t,e.noCache),e.vars),n=new Er(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},s={...a,abortScope:n};try{try{return await ha(e,r,s,a,o)}finally{n.settle()}}catch(r){if(Kr(r)||Hr(r)||Zr(r))throw r;const n=xa(r,o),{fallback:s}=e;if(void 0===s)throw n;try{const e=await tn(s,a);return void 0!==t.trace&&void 0!==t.traceParent&&A(n)&&t.trace.markFallback(t.traceParent,n),e}catch(e){if(Kr(e)||Hr(e)||Zr(e))throw e;const r=xa(e,t.frame);throw A(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Ur(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Ur("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},nn=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=ma(a,e.vars),o=e.holes.map(({node:e})=>void 0===r?tn(e,n):"skeleton"===e.kind?tn(e,{...n,rootBoundary:r}):r(()=>tn(e,n),e)),s=o.some(S)?await Promise.all(o):o;return De(e.skeleton,e.holes,s)},on=async(e,t,r)=>{const{timeout:a,signal:n}=t,o=e.holes.length>0,s=void 0!==a||void 0!==n?Mr(n,a,Tr):void 0,i=void 0!==s?((e,t)=>{const r={epoch:0};return e.addEventListener("abort",()=>{r.epoch+=1},{once:!0}),{get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:r,settle:t}})(s.signal,s.settle):new Er(void 0),l=void 0!==s&&void 0!==a&&e.timeoutShielded&&o,c=!0===t.trace?na(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,u=((e,t,r,a)=>({options:e,data:e.data??Ir,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,...void 0!==a?{trace:a}:{}}))(t,r,i,c),d=l?ln(e,s.expiry,a,c):void 0,p=void 0!==d&&"skeleton"!==e.root.kind,f=void 0===d||p?u:{...u,rootBoundary:d};try{if(i.aborted)throw Yr(i.reason,[]);const t=()=>p&&void 0!==d?d(()=>tn(e.root,f),e.root):tn(e.root,f),r=await(l||void 0===s?t():sn(t,s,a));return void 0!==c?{result:r,trace:c.finish()}:{result:r}}catch(e){throw void 0!==c&&A(e)&&void 0===e.trace&&(e.trace=c.finish()),e}finally{i.settle()}},sn=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Yr(e,[],{ms:r})})]),ln=(e,t,r,a)=>{const n=new Map(e.holes.map(e=>[e.node,e]));return(e,o)=>{const s=n.get(o);if(void 0===s)throw Ur(`the hole boundary was handed the node at ${JSON.stringify($e(o.path))}, which is not one of the artifact's holes`);let i=!1;const l=Promise.resolve(e()).then(e=>(i=!0,e));return Promise.race([l,t.catch(e=>{if(e!==Tr)throw Yr(e,[]);if(i)return;const t=un(s);return a?.markShielded(s.node,cn(s,e,r),t),t})])}},cn=(e,t,r)=>{const{node:a}=e,n="operator"===a.kind?a.name:void 0;return Yr(t,$e(a.path),{operator:n,ms:r})},un=e=>{if(void 0===e.timeoutFallback)throw Ur("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},dn={hit:!1},pn=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw mn("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!fn(t))throw mn("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw mn("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw mn("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},fn=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),mn=e=>new O({code:s.invalidOptions,message:e,path:[]});class hn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new ir(e.maxSize),this.store=this.own):this.store=e.store,this.maxTime=e.maxTime}get generation(){return this.current}async lookup(e){let t;try{t=await this.store.get(e)}catch{return dn}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||vn(t)?(this.drop(e),dn):{hit:!0,value:t.value}:dn;var r}async write(e,t,r){if(r!==this.current)return;const a={fig:"ft3",value:t,generation:r,...Number.isFinite(this.maxTime)?{expiresAt:Date.now()+1e3*this.maxTime}:{}};try{await this.store.set(e,a)}catch{}}clear(){this.current+=1;try{Promise.resolve(this.store.clear()).catch(P)}catch{}}configure(e){void 0!==e.store&&e.store!==this.store&&(this.store=e.store,this.own=void 0),this.maxTime=e.maxTime,this.own?.resize(e.maxSize)}drop(e){try{Promise.resolve(this.store.delete(e)).catch(P)}catch{}}}const vn=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),yn=e=>e===C?0:"number"==typeof e?1:2,gn=e=>({data:{paths:[...e.dataPaths].sort(([,e],[,t])=>((e,t)=>{const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a],n=t[a];if(r===n)continue;const o=yn(r)-yn(n);return 0!==o?o:"number"==typeof r&&"number"==typeof n?r-n:r<n?-1:1}return e.length-t.length})(e,t)).map(([e])=>e),dynamic:e.dynamic},operators:[...e.operators],fragments:[...e.fragments]}),bn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e)){const e={...n};void 0!==t&&Object.hasOwn(t,a)&&(e.hostDefault=t[a]),r[a]=e}return r},wn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push($n(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:s.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},kn=(e,t)=>e.hasErrors||void 0!==t.maxDepth||void 0!==t.maxNodes?[...wn(e,t),...e.issues.map(e=>e.issue)]:[],$n=(e,t)=>({severity:"error",code:s.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),xn=(e,t,r)=>{const a=[...wn(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...jn(e.dataReads,t.data)),a},jn=(e,t)=>{const r=new Map,a=new Map,n=[],o=(e,o,i,l)=>{let c=r.get(e);if(void 0===c&&(c=k(t,o).found,r.set(e,c)),c)return;let u=a.get(i.path);if(void 0===u&&a.set(i.path,u=new Set),u.has(e))return;u.add(e);const d=void 0===l?"":` (read by fragment '${l}')`;n.push({severity:"warning",code:s.missingDataPath,message:`'${N(o)}' is absent from the supplied sample data${d}`,path:$e(i.path)})};for(const t of e)if("path"===t.kind)o(t.key,t.segments,t,void 0);else for(const[e,r]of t.fragment.dependencies.dataPaths)o(e,r,t,t.fragment.name);return n},On="...",Pn=/*#__PURE__*/new Set(["propagate","value"]),An=e=>e,Dn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=Sn(e.parameters,t,(t,r,a)=>{throw new O({code:t,message:r,path:a,operator:e.name})});return Cn(e,r)},Sn=(e,r,a)=>{const n=Object.entries(r).filter(([,e])=>t(e)).map(([e])=>e),o=new Map;for(const[i,l]of Object.entries(e)){if("function"!=typeof l.nullPolicy)continue;const e=["parameters",i,"nullPolicy"];if(1!==n.length){a(s.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${n.length}`,e,i);continue}const c=n[0],u=r[c];if(!t(u))continue;const d=[];let p=!0;for(const t of u.literal){let r;try{r=l.nullPolicy(t)}catch(r){a(s.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(r)}`,e,i),p=!1;break}if("string"!=typeof r||!Pn.has(r)){a(s.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(r)} for ${JSON.stringify(t)}`,e,i),p=!1;break}d.push({value:t,policy:r})}p&&o.set(i,{selector:c,table:d})}return o},Cn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e.parameters)){const e=t.get(a),o="string"==typeof n.nullPolicy?n.nullPolicy:void 0,s=n.type??"any",i=!0===n.truthiness&&R(s)?"value":"propagate",l={type:zn(s),required:n.required??!("default"in n),evaluation:n.evaluation??"eager",truthiness:n.truthiness??!1,nullPolicy:e??o??i};"default"in n&&(l.default=n.default),void 0!==n.description&&(l.description=n.description),void 0!==n.metadata&&(l.metadata=n.metadata),void 0!==n.elementNullPolicy&&(l.elementNullPolicy=n.elementNullPolicy),void 0!==n.constraints&&(l.constraints=Tn(n.constraints)),void 0!==n.over&&(l.over=n.over),void 0!==n.replacesNullAt&&(l.replacesNullAt=[...n.replacesNullAt]),r[a]=l}const a=e.positionalParams?.at(-1),n=a?.startsWith(On)?a.slice(3):null,o={[Q]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:En(r),restParam:n,deliversLazily:Object.values(r).some(e=>"eager"!==e.evaluation&&"structural"!==e.evaluation),timeoutParam:e.timeoutParam??null,cache:!0===e.cache,fingerprint:"",evaluate:e.evaluate,returns:void 0!==e.returns?zn(e.returns):"any"};return void 0!==e.alias&&(o.alias=e.alias),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.positionalParams&&(o.positionalParams=[...e.positionalParams]),void 0!==e.validate&&(o.validate=e.validate),void 0!==e.analysis&&(o.analysis=Tn(e.analysis)),o.fingerprint=Nn(o),qn(o)},Nn=e=>z(JSON.stringify([e.name,e.parameters,e.positionalParams,e.restParam,e.returns,e.cache,e.timeoutParam,e.evaluate,e.validate],(e,t)=>"function"==typeof t||"symbol"==typeof t||t instanceof RegExp?String(t):t)),zn=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],Tn=t=>{if(Array.isArray(t))return t.map(Tn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=Tn(a);return e}return t},En=e=>{const t=Object.entries(e);return{entries:t,whole:t.filter(([,e])=>void 0===e.replacesNullAt&&"perElement"!==e.evaluation),perElement:t.filter(([,e])=>"perElement"===e.evaluation)}},qn=e=>{for(const t of Object.values(e.parameters))"string"!=typeof t.type&&Object.freeze(t.type),"object"==typeof t.type&&"literal"in t.type&&Object.freeze(t.type.literal),"object"==typeof t.nullPolicy&&(t.nullPolicy.table.forEach(e=>Object.freeze(e)),Object.freeze(t.nullPolicy.table),Object.freeze(t.nullPolicy)),void 0!==t.constraints&&Mn(t.constraints),void 0!==t.replacesNullAt&&Object.freeze(t.replacesNullAt),Object.freeze(t);Object.freeze(e.parameters);for(const t of Object.values(e.resolution))t.forEach(e=>Object.freeze(e)),Object.freeze(t);return Object.freeze(e.resolution),"string"!=typeof e.returns&&Object.freeze(e.returns),void 0!==e.positionalParams&&Object.freeze(e.positionalParams),Object.freeze(e)},Mn=t=>{Array.isArray(t)?(t.forEach(Mn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(Mn),Object.freeze(t))},Fn=e=>{if(Array.isArray(e))return e;try{return g(e)}catch(e){throw new ja(e.message)}},Rn=(e,t)=>{if("string"!=typeof e)return[];try{return g(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},In=e=>Array.isArray(e.values)&&0===e.values.length?[{severity:"error",parameter:"values",message:"an empty values array has no result — supply at least one value"}]:[],Vn=e=>t=>{const r=t[e];return Array.isArray(r)&&0===r.length?[{severity:"warning",parameter:e,message:`an empty ${e} array is a dead expression — the result is always the identity`}]:[]},Ln=/*#__PURE__*/Vn("values"),Wn=/*#__PURE__*/Vn("input"),Jn=/*#__PURE__*/Vn("entries"),Bn=e=>Array.isArray(e.values)&&e.values.length<2?[{severity:"warning",parameter:"values",message:"fewer than two values is a dead comparison — the result never varies"}]:[],Un=(e,t)=>new ja(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:s.emptyAggregate}),Kn=async(e,t)=>{const r=[];for await(const a of e){if(a.ok&&a.value===t)return t;a.ok||r.push(a)}if(r.length>0)throw r.sort((e,t)=>e.index-t.index),Gn(r);return!t},Gn=e=>{const[t,...r]=e,a=r.map(e=>e.error).filter(A);return a.length>0&&A(t.error)&&void 0===t.error.related&&(t.error.related=a),t.error},_n=async e=>{const t=new Array(e.length);let r=0;for await(const a of e){t[a.index]=a;for(let e=t[r];void 0!==e;e=t[r]){if(!e.ok)throw e.error;r+=1}}return t.map(e=>e?.value)},Hn=(e,t)=>{const r=e=>t&&"string"==typeof e?e.toLowerCase():e;if(e.length<2)return!0;const a=r(e[0]);return e.every(e=>ve(r(e),a))},Qn={values:{type:"array",elementNullPolicy:"value",description:"The values compared; null is comparable (null equals null)"},caseInsensitive:{type:"boolean",default:!1,description:"Fold string operands to one case before comparing (shallow)"}},Xn={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:Qn,positionalParams:["...values"],returns:"boolean",validate:Bn,evaluate:({values:e,caseInsensitive:t})=>Hn(e,t)},Yn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:Qn,positionalParams:["...values"],returns:"boolean",validate:Bn,evaluate:({values:e,caseInsensitive:t})=>!Hn(e,t)},Zn=(e,t,r,a)=>({name:e,alias:t,category:"comparison",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{length:2,homogeneous:["number","string"]},description:"Exactly two operands: both numbers, or both strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces a null operand before comparing"}},positionalParams:["...values"],returns:"boolean",evaluate:({values:e})=>{const[t,r]=e;return a(oe(t,r))}}),eo=/*#__PURE__*/Zn("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),to=/*#__PURE__*/Zn("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),ro=/*#__PURE__*/Zn("lessThan","<","Is the first value strictly less than the second?",e=>e<0),ao=/*#__PURE__*/Zn("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),no={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},oo=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,so={name:"plus",alias:"+",category:"math",description:"Add numbers, concatenate strings or arrays, or shallow-merge objects — all operands must share one type",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string","array","object"]},description:"The operands; homogeneous: all numbers, strings, arrays or objects"},expect:{type:{literal:["number","string","array","object"]},required:!1,description:"Pin the mode: every operand must be this type, and an empty input yields its identity"},nullValueDefault:{type:["number","string","array","object"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null operand before the addition"}},positionalParams:["...values"],returns:["number","string","array","object"],validate:({values:e,expect:t})=>void 0!==t?Ln({values:e}):In({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw Un("the sum","pin the mode with 'expect' to get its identity");return no[t]()}const r=t??oo(e[0]),a=e.find(e=>oo(e)!==r);if(void 0!==a)throw n=`all operands must be ${r}s — received ${q(a)}`,new ja(n,{code:s.typeCheck});var n;switch(r){case"number":return e.reduce((e,t)=>e+t,0);case"string":return e.join("");case"array":return e.flat(1);case"object":return Object.assign({},...e)}}},io={name:"subtract",alias:"-",category:"math",description:"Subtract one number from another",parameters:{value:{type:["number","null"],description:"The main operand"},minus:{type:["number","null"],description:"The amount subtracted from value"}},positionalParams:["value","minus"],returns:"number",evaluate:({value:e,minus:t})=>e-t},lo={name:"divide",alias:"/",category:"math",description:"Divide one number by another — true division; zero divisors fail",parameters:{value:{type:["number","null"],description:"The main operand"},by:{type:["number","null"],description:"The divisor"}},positionalParams:["value","by"],returns:"number",evaluate:({value:e,by:t})=>e/t},co={name:"modulo",category:"math",description:"The floored remainder: the result takes the sign of mod, so modulo(-7, 3) is 2",parameters:{value:{type:["number","null"],description:"The main operand"},mod:{type:["number","null"],description:"The modulus"}},positionalParams:["value","mod"],returns:"number",evaluate:({value:e,mod:t})=>(e%t+t)%t},uo={name:"multiply",alias:"*",category:"math",description:"Multiply numbers together — an empty input is 1, the empty product",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number"]},description:"The factors"},nullValueDefault:{type:"number",required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null factor before multiplying"}},positionalParams:["...values"],returns:"number",validate:Ln,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},po={name:"power",alias:"^",category:"math",description:"Raise a base to an exponent — overflow and complex results fail",parameters:{base:{type:["number","null"],description:"The number to raise"},exponent:{type:["number","null"],description:"The power to raise it to"}},positionalParams:["base","exponent"],returns:"number",evaluate:({base:e,exponent:t})=>e**t},fo={name:"round",category:"math",description:"Round to a number of decimal places — ties go half away from zero; negative decimals round to tens, hundreds, …",parameters:{value:{type:["number","null"],description:"The number to round"},decimals:{type:"integer",default:0,description:"Decimal places to keep; negative values round to powers of ten"}},positionalParams:["value","decimals"],returns:"number",evaluate:({value:e,decimals:t})=>((e,t=0)=>{if(!Number.isFinite(e))return e;const r=e<0?-1:1,a=Math.round(fe(Math.abs(e),t));return r*fe(a,-t)})(e,t)},mo=(e,t,r,a,n="number")=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"],description:r}},positionalParams:["value"],returns:n,evaluate:({value:e})=>a(e)}),ho=/*#__PURE__*/mo("floor","Round down toward negative infinity","The number to round down",Math.floor,"integer"),vo=/*#__PURE__*/mo("ceil","Round up toward positive infinity","The number to round up",Math.ceil,"integer"),yo=/*#__PURE__*/mo("abs","The absolute value","The number",Math.abs),go=(e,t,r,a)=>({name:e,category:"math",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string"]},description:"The candidates: all numbers, or all strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null candidate before comparing"}},positionalParams:["...values"],returns:["number","string"],validate:In,evaluate:({values:e})=>{const r=e;if(0===r.length)throw Un(t);return r.reduce((e,t)=>a(oe(t,e))?t:e)}}),bo=(e,t,r,a)=>({name:e,category:"string",description:t,parameters:{value:{type:["string","null"],description:r}},positionalParams:["value"],returns:"string",evaluate:({value:e})=>a(e)}),wo={name:"split",category:"string",description:"Divide a string on a delimiter into an array of pieces — empty pieces are kept; an empty delimiter splits into code points",parameters:{value:{type:["string","null"],description:"The string to divide"},delimiter:{type:"string",default:" ",description:'Split on each occurrence; "" splits into code points'},trim:{type:"boolean",default:!0,description:"Trim whitespace from each piece"}},positionalParams:["value","delimiter"],returns:"array",evaluate:({value:e,delimiter:t,trim:r})=>{const a=""===t?pe(e):e.split(t);return r?a.map(ie):a}},ko=e=>Array.isArray(e.values)&&e.values.some(te)?[{severity:"error",parameter:"values",message:re}]:[],$o={name:"join",category:"string",description:"Render array elements to text and concatenate them with a delimiter",parameters:{values:{type:"array",elementNullPolicy:"value",description:'Elements of any type, rendered by the stringification table; a null renders "" and still occupies its slot'},delimiter:{type:"string",default:" ",description:"Placed between each adjacent pair — shares its contract with split"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:'Rendered in place of a null element, instead of ""'}},positionalParams:["...values"],returns:"string",validate:e=>[...Ln(e),...ko(e)],evaluate:({values:e,delimiter:t},r)=>e.map((e,t)=>{const a=`[${t}]`;return null===e?r.trace.note({type:"render",token:a,rendered:"empty"}):te(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),ee(e)}).join(t)},xo=e=>{const t=new Set,r=[];for(const a of e)if("imsu".includes(a)){if(t.has(a))return`duplicate regex flag '${a}'`;t.add(a)}else r.includes(a)||r.push(a);if(0===r.length)return;const a=r.includes("g")||r.includes("y")?" — all matches is mode: 'match'":"";return`unknown regex flag${1===r.length?"":"s"}: ${r.join(", ")}${a}`},jo={type:"array",description:"The collection iterated over; a null input is a type error"},Oo={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},Po={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},Ao={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},Do={name:"get",category:"data",description:"Read a path out of the evaluation data, or out of a supplied object — the dynamic face of a $data reference",parameters:{path:{type:["string","array","null"],description:"Dot and bracket segments, quoted keys and the [*] projection — or an array of segments, taken verbatim"},from:{type:"any",nullPolicy:"value",default:H,description:"The object searched instead of the evaluation data — replace, never merge; a null source is one where every path is missing"},default:{type:"any",required:!1,evaluation:"lazy",description:"The answer when the path is missing — a stored null passes through unchanged (firstOf replaces one); supplying it also opts out of strictDataPaths"}},positionalParams:T,returns:"any",validate:({path:e})=>Rn(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=k(t,Fn(e));if(n.found)return void 0===n.value?null:n.value;if(void 0!==r)return r.evaluate();if(a.options.strictDataPaths)throw new ja(`'${So(e)}' is missing (strictDataPaths)`,{code:s.missingDataPath});return null}},So=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),Co={name:"buildObject",category:"data",description:"Assemble an object from computed key/value entries — for keys known only at runtime",parameters:{entries:{type:"array",constraints:{elementShape:{key:{type:["string","number","boolean"]},value:{type:"any"}}},description:'Objects with a "key" and a "value"; a null value keeps its key'}},positionalParams:["...entries"],returns:"object",validate:e=>[...Jn(e),...No(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=ee(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},No=e=>{const t=e.entries;if(!Array.isArray(t))return[];const r=new Set,a=new Set,n=[];for(const e of t){const t=e?.key;if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)continue;const o=ee(t);r.has(o)&&!a.has(o)&&(a.add(o),n.push({severity:"warning",parameter:"entries",message:`duplicate key '${o}' — the last entry wins and the earlier one is dead`})),r.add(o)}return n},zo=(e,t)=>new ja(`cannot convert ${q(e)} to ${t}`),To=/*#__PURE__*/[{name:"and",category:"logic",description:"True when every value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Ln,evaluate:({values:e})=>Kn(e,!1)},{name:"or",category:"logic",description:"True when any value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Ln,evaluate:({values:e})=>Kn(e,!0)},{name:"not",alias:"!",category:"logic",description:"Negate the truthiness of a value",parameters:{value:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy, so not(null) is true"}},positionalParams:["value"],returns:"boolean",evaluate:({value:e})=>!e},{name:"if",alias:"?",category:"logic",description:"Choose between two branches — only the chosen branch evaluates",parameters:{condition:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy"},then:{type:"any",evaluation:"lazy",description:"The value when the condition holds"},else:{type:"any",evaluation:"lazy",default:null,description:"The value when it does not; omitted means null"}},positionalParams:["condition","then","else"],evaluate:({condition:e,then:t,else:r})=>e?t.evaluate():r.evaluate()},{name:"match",category:"logic",description:"Dispatch on a value — only the matching branch evaluates",parameters:{value:{type:["string","number","boolean","null"],nullPolicy:"value",description:"Matched against branch keys by its canonical string form"},branches:{type:"object",evaluation:"lazyEntries",description:"A literal map of branches, or an expression computing one"},default:{type:"any",required:!1,evaluation:"lazy",description:"The branch taken when none matches; absent means failure"}},positionalParams:["value","branches","default"],evaluate:({value:e,branches:t,default:r})=>{const a=null===e?null:ee(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new ja(`no branch matches ${null===a?"null":`'${a}'`}, and no default was supplied`)}},{name:"firstOf",category:"logic",description:"The first candidate that is not null (SQL COALESCE) — later candidates never evaluate",parameters:{values:{type:"array",evaluation:"lazyElements",description:"Candidates, tried in order; only null is skipped"}},positionalParams:["...values"],validate:Ln,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Xn,Yn,eo,to,ro,ao,so,io,uo,lo,co,po,fo,ho,vo,yo,/*#__PURE__*/go("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/go("max","the maximum","The largest of the values — numbers numerically, strings in codepoint order",e=>e>0),{name:"buildString",category:"string",description:"Render a template, filling its tokens — the result is always a string",parameters:{template:{type:["string","null"],description:"The text, with %N or {{name}} tokens; in a literal template, {{$data.x}} is that reference"},substitutions:{type:["array","object"],default:[],elementNullPolicy:"value",description:"An array pairs with %N tokens, an object with {{name}} tokens; the mode dispatches on which arrives"},trim:{type:"boolean",default:!1,description:"Trim whitespace from each rendered value, never from the template text"},closeGaps:{type:"boolean",default:!1,description:"A value that renders empty also takes one run of adjacent template whitespace"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["substitutions"],description:'Rendered in place of a null value, instead of ""'}},positionalParams:["template","...substitutions"],returns:"string",evaluate:({template:e,substitutions:t,trim:r,closeGaps:a},n)=>{const o=Array.isArray(t)?t:void 0,s=void 0===o?t:void 0,i=[];for(const t of ge(e)){if("text"===t.kind){i.push({text:t.text,site:!1});continue}if(!("positional"===t.kind?void 0!==o&&t.index>=1&&t.index<=o.length:void 0!==s&&Object.hasOwn(s,t.body))){n.trace.note({type:"render",token:t.raw,rendered:"literal"}),i.push({text:t.raw,site:!1});continue}const e="positional"===t.kind?o[t.index-1]:s[t.body],a=ee(e);te(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?ie(a):a;""===l&&n.trace.note({type:"render",token:t.raw,rendered:"empty"}),i.push({text:l,site:!0,token:t.raw})}if(a)for(const e of(e=>{const t=[];for(let r=0;r<e.length;r++){const a=e[r];if(!a.site||""!==a.text)continue;const n=e[r-1];if(void 0!==n&&!n.site){const e=ue(n.text);if(e!==n.text){n.text=e,t.push(a.token);continue}}const o=e[r+1];if(void 0!==o&&!o.site){const e=de(o.text);e!==o.text&&t.push(a.token),o.text=e}}return t})(i))n.trace.note({type:"render",token:e,rendered:"gap-closed"});return i.map(e=>e.text).join("")}},wo,$o,/*#__PURE__*/bo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/bo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/bo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",ie),{name:"regex",category:"string",description:"Test, extract or match a string against a regular expression",parameters:{value:{type:["string","null"],description:"The subject string"},pattern:{type:["string","null"],description:"The regular expression source"},flags:{type:"string",default:"",description:"The admitted subset: i, m, s, u"},mode:{type:{literal:["test","extract","match"]},default:"test",description:"test gives a boolean, extract the first matching substring, match every one of them"},noMatchDefault:{type:["string","null"],required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The extract answer when nothing matches — a matched empty string still passes through"}},positionalParams:["value","pattern"],returns:["boolean","string","array","null"],validate:({pattern:e,flags:t})=>{const r=[],a="string"==typeof t?xo(t):void 0;if(void 0!==a&&r.push({severity:"error",parameter:"flags",message:a}),"string"==typeof e)try{new RegExp(e,"string"==typeof t&&void 0===a?t:"")}catch(e){r.push({severity:"error",parameter:"pattern",message:`pattern does not compile: ${e.message}`})}return r},evaluate:({value:e,pattern:t,flags:r,mode:a,noMatchDefault:n})=>{const o=xo(r);if(void 0!==o)throw new ja(o);const s=e=>{try{return new RegExp(t,r+e)}catch(e){throw new ja(`pattern does not compile: ${e.message}`)}};switch(a){case"test":return s("").test(e);case"extract":{const t=s("").exec(e);return null===t?n.evaluate():t[0]}case"match":return[...e.matchAll(s("g"))].map(e=>e[0])}}},{name:"length",category:"array",description:"An array's element count, or a string's Unicode code-point count",parameters:{value:{type:["string","array","null"],description:"The array or string measured"}},positionalParams:["...value"],returns:"integer",evaluate:({value:e})=>"string"==typeof e?pe(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:jo,as:Oo,nullInputDefault:Po,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Wn,evaluate:({each:e})=>_n(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:jo,as:Oo,nullInputDefault:Po,each:Ao},positionalParams:["input","each"],returns:"array",validate:Wn,evaluate:async({input:e,each:t})=>{const r=await _n(t.settle());return e.filter((e,t)=>r[t])}},{name:"find",category:"array",description:"The first element of an array whose predicate is truthy",parameters:{input:jo,as:Oo,nullInputDefault:Po,each:Ao,noMatchDefault:{type:"any",required:!1,default:null,evaluation:"lazy",description:"The answer when nothing matches; a found null passes through unchanged"}},positionalParams:["input","each"],validate:Wn,evaluate:async({input:e,each:t,noMatchDefault:r})=>{const a=new Array(e.length);let n=0;for await(const r of t.settle()){a[r.index]=r;for(let t=a[n];void 0!==t;t=a[n]){if(!t.ok)throw t.error;if(!0===t.value)return e[n];n+=1}}return r.evaluate()}},{name:"some",category:"array",description:"True when any element satisfies the predicate",parameters:{input:jo,as:Oo,nullInputDefault:Po,each:Ao},positionalParams:["input","each"],returns:"boolean",validate:Wn,evaluate:({each:e})=>Kn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:jo,as:Oo,nullInputDefault:Po,each:Ao},positionalParams:["input","each"],returns:"boolean",validate:Wn,evaluate:({each:e})=>Kn(e.settle(),!1)},Do,Co,{name:"convert",category:"other",description:"Convert a value to a number, string, boolean or array — strict: a failed conversion is an error, never a guess",parameters:{value:{type:"any",nullPolicy:e=>"boolean"===e?"value":"propagate",description:"The value to convert; null propagates except for boolean, where it is false"},to:{type:{literal:["number","string","boolean","array"]},description:"The target type"}},positionalParams:["value","to"],returns:["number","string","boolean","array"],evaluate:({value:t,to:r})=>{switch(r){case"number":if("number"==typeof t)return t;if("boolean"==typeof t)return t?1:0;if("string"==typeof t){const e=t.trim(),r=""===e?NaN:Number(e);if(Number.isNaN(r))throw new ja(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw zo(t,"number");case"string":if(Array.isArray(t)||e(t))throw new ja(`cannot convert ${q(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw zo(t,"string");return ee(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return ne(t);case"array":return Array.isArray(t)?t:[t]}}}].map(Dn),Eo="3.0.0-preview.8",qo=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,a]of Object.entries(t)){if(void 0===a)continue;if(null===a){delete r[e];continue}if("data"===e||!n(a)){r[e]=a;continue}const t=r[e],o=n(t)?{...t}:{};for(const[e,t]of Object.entries(a))void 0!==t&&(null===t?delete o[e]:o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);Go(r);const a=Mo(r);if(null!==e&&!(e=>void 0!==e.operators||void 0!==e.fragments||void 0!==e.operatorDefaults)(t))return{options:r,evaluation:a,registry:e.registry,compileCache:e.compileCache};const o=Dr({operators:r.operators??[To],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:a,registry:o,compileCache:new vr({compile:e=>Fo(e,o),probe:be})}},Mo=e=>{const t={...e};return delete t.operators,delete t.fragments,t},Fo=(e,t)=>{const r=ze(e,t);return Ct(r),r.hasNoCache&&Yt(r),r};class Ro{state;results;version=Eo;constructor(e={}){this.state=qo(null,e),this.results=new hn(pn(this.state.options.cache))}updateOptions(e={}){const t=qo(this.state,e),r=pn(t.options.cache);this.state=t,this.results.configure(r)}clearCache(){this.results.clear()}getOptions(){return(e=>{const t={};for(const[r,a]of Object.entries(e))t[r]=n(a)?{...a}:a;return t})(this.state.evaluation)}getOperators(){return[...this.state.registry.operators.values()].map(e=>{const{definition:t,hostDefaults:r}=e,a={name:t.name,category:t.category,description:t.description,parameters:bn(t.parameters,r),restParam:t.restParam,timeoutParam:t.timeoutParam,cache:t.cache,returns:t.returns,hasValidate:void 0!==t.validate};return void 0!==t.alias&&(a.alias=t.alias),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.positionalParams&&(a.positionalParams=t.positionalParams),void 0!==r&&(!0===r.noCache&&(a.hostNoCache=!0),Object.hasOwn(r,"fallback")&&(a.hostFallback=r.fallback)),a})}getFragments(){return[...this.state.registry.fragments.values()].map(e=>{const t={name:e.name,parameters:Object.fromEntries(Object.entries(e.parameters).map(([e,t])=>[e,{...t}])),returns:e.returns,warnings:[...e.warnings],dependencies:gn(e.dependencies),caches:e.caches};return void 0!==e.description&&(t.description=e.description),void 0!==e.metadata&&(t.metadata=e.metadata),t})}validate(e,t){const r=void 0===t?this.state.evaluation:Uo(this.state.evaluation,t),a=Fo(e,this.state.registry),n=xn(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n}}getDependencies(e){return gn(ze(e,this.state.registry).dependencies)}isEvaluable(e){const t=ze(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return Io(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>Fo(e,r.registry))}compile(e){const{state:t}=this;return Jo(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const Io=async(e,t,r,a,n,o)=>{const s=void 0===a?e:Uo(e,a),i=n(),l="inert"===i.kind&&!0===s.trace?{kind:"artifact",artifact:o()}:i;if("inert"===l.kind){if(void 0!==s.maxDepth&&l.depth>s.maxDepth){const e=$n(l.depth,s.maxDepth);throw Ho(e,[e])}return r}const{artifact:c}=l,u=kn(c,s),d=u.find(e=>"error"===e.severity);if(void 0!==d)throw Ho(d,u);const p=await on(c,s,t);return!0===s.trace?p:p.result};let Vo;const Lo=(e,t)=>Vo?.(e,t);class Wo{#t;#r;#a;#n;#o;#s;#i;constructor(e,t,r,a,n){this.#t=e,this.#r=t,this.#a=r,this.#n=a,this.#o=n,Vo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Uo(e.#a,t);return{expression:e.#t,artifact:e.#l(),options:r}}}get expression(){return this.#t}get issues(){return this.#i??=this.#l().issues.map(e=>e.issue)}get hasErrors(){return this.#l().hasErrors}evaluate(e){return Io(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return gn(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#s??=Fo(this.#t,this.#n)}}const Jo=(e,t,r,a,n)=>new Wo(e,t,r,a,n),Bo=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,trace:0})),Uo=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Bo.has(a))throw Ko(a);r??={...e},r[a]=n}}return void 0===r?e:(Go(t),r)},Ko=e=>new O({code:s.invalidOptions,message:`'${e}' is not a per-call option — a call may supply data, signal, timeout and trace; configure the rest at construction or via updateOptions()`,path:[]}),Go=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new O({code:s.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!_o(r))throw new O({code:s.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},_o=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Ho=(e,t)=>new O({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},issues:t});export{Eo as A,xn as B,Y as C,Z as D,H as E,Ro as F,oe as G,ve as H,Pn as N,_ as O,On as R,G as a,R as b,L as c,To as d,Oa as e,Pe as f,Lo as g,kn as h,ne as i,V as j,X as k,U as l,W as m,Sn as n,Cn as o,ja as p,Fn as q,Oe as r,De as s,$e as t,ee as u,St as v,q as w,Dn as x,An as y,Rn as z};
1
+ import{a as e,i as t,l as r,f as a,d as n,D as o,E as s,g as i,c as l,o as c,q as u,h as d,S as p,u as f,e as m,p as h,s as v,j as y,n as g,v as b,k as w,w as k,x as $,r as x,t as j,m as O,R as P,F as A,y as C,b as D,z as S,A as N,W as z,B as T,C as E,G as q}from"./shared.js";const M={ok:!0},F=e=>null===e?"null":Array.isArray(e)?"array":typeof e,R=(e,t)=>({ok:!1,expected:e,actual:F(t)}),I=(t,r)=>{switch(r){case"any":return!0;case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"array":return Array.isArray(t);case"object":return e(t);case"null":return null===t;default:return!1}},V=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),L=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),W=t=>{if("string"==typeof t)return L.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&L.has(e));if(e(t)&&"literal"in t){const e=t.literal;return Array.isArray(e)&&e.length>0&&e.every(e=>["string","number","boolean"].includes(typeof e))}return!1},J=(e,r)=>{if(t(r)){if(-1!==r.literal.indexOf(e))return M;const t=r.literal.map(e=>JSON.stringify(e)).join(", ");return R(`one of ${t}`,e)}return"string"==typeof r?I(e,r)?M:R(r,e):r.some(t=>I(e,t))?M:R(r.join(" | "),e)},B=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return R("array",e);if(e.length!==t.length)return{ok:!1,expected:`array of length ${t.length}`,actual:`array of length ${e.length}`}}if(t.homogeneous){if(!Array.isArray(e))return R("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>I(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:U(e)}}}if(t.elementShape){if(!Array.isArray(e))return R("array",e);for(let r=0;r<e.length;r++){const a=_(e[r],t.elementShape);if(!a.ok)return a}}return M},U=e=>{const t=F(e[0]),r=e.find(e=>F(e)!==t);return void 0===r?`array of ${t}`:`${F(r)} beside ${t}`},K=["length","homogeneous","elementShape"],G=t=>{if(!e(t))return R("a constraints object",t);for(const e of Object.keys(t))if(!K.includes(e))return{ok:!1,expected:`one of ${K.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return R("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&W(a)))return R("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return R("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return R(`a declaration for "${t}"`,r);if(void 0!==r.type&&!W(r.type))return R(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return R(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=G(r.constraints);if(!e.ok)return e}}}return M},_=(t,r)=>{if(!e(t))return R("object",t);const a=Object.keys(r);for(let e=0;e<a.length;e++){const n=a[e],o=r[n],s=Object.prototype.hasOwnProperty.call(t,n),i=!1!==o.required;if(s){if(void 0!==o.type){const e=J(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=B(t[n],o.constraints);if(!e.ok)return e}}else if(i)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return M},H=(e,t,r)=>{if(!r||!Array.isArray(e))return B(e,t);const{length:a,...n}=t;if(void 0!==a){const t=B(e,{length:a});if(!t.ok)return t}return B(e.filter(e=>null!==e),n)},Q=["logic","comparison","math","string","array","data","io","other"],X=Symbol("fig-tree:EvaluationData"),Y=Symbol("fig-tree:validated-operator"),Z=e=>"object"==typeof e&&null!==e&&!0===e[Y],ee="<array>",te="<object>",re=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?ee:te,ae=e=>null!==e&&"object"==typeof e,ne="a composite element renders as a placeholder, never as text — drill in, or join it explicitly",oe=[!1,null,0,""],se=e=>-1===oe.indexOf(e),ie=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:le(String(e),String(t)),le=(e,t)=>{const r=Array.from(e),a=Array.from(t),n=Math.min(r.length,a.length);for(let e=0;e<n;e++){const t=r[e].codePointAt(0),n=a[e].codePointAt(0);if(t!==n)return t<n?-1:1}return r.length===a.length?0:r.length<a.length?-1:1},ce=e=>e.trim(),ue=/\s+$/,de=/^\s+/,pe=e=>e.replace(ue,""),fe=e=>e.replace(de,""),me=e=>Array.from(e),he=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},ve=Object.prototype.hasOwnProperty,ye=(e,t)=>{for(const r of e.keys())if(ge(r,t))return r},ge=(e,t)=>{let r,a,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((a=e.length)===t.length)for(;a--&&ge(e[a],t[a]););return-1===a}if(r===Set){if(e.size!==t.size)return!1;for(a of e){if(n=a,n&&"object"==typeof n&&(n=ye(t,n),!n))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(a of e){if(n=a[0],n&&"object"==typeof n&&(n=ye(t,n),!n))return!1;if(!ge(a[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((a=e.byteLength)===t.byteLength)for(;a--&&e.getInt8(a)===t.getInt8(a););return-1===a}if(ArrayBuffer.isView(e)){if((a=e.byteLength)===t.byteLength)for(;a--&&e[a]===t[a];);return-1===a}if(!r||"object"==typeof e){for(r in a=0,e){if(ve.call(e,r)&&++a&&!ve.call(t,r))return!1;if(!(r in t)||!ge(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},be=e=>!e.includes("{")&&!e.includes("}")&&(e.startsWith("$")?e.length>1:r(e).ok),we=e=>{const t=[];let r="";const a=()=>{""!==r&&(t.push({kind:"text",text:r}),r="")};let n=0;for(;n<e.length;){const o=e[n];if("%"===o){let s=n+1;for(;s<e.length&&e[s]>="0"&&e[s]<="9";)s++;if(s>n+1){const r=e.slice(n,s);a(),t.push({kind:"positional",raw:r,index:Number(r.slice(1))}),n=s;continue}r+=o,n++;continue}if("{"===o&&"{"===e[n+1]){const o=e.indexOf("}}",n+2);if(-1!==o){const r=e.slice(n+2,o);if(be(r)){a(),t.push({kind:"named",raw:e.slice(n,o+2),body:r}),n=o+2;continue}}r+="{{",n+=2;continue}r+=o,n++}return a(),t},ke=e=>{const t={maxDepth:0};return{constant:$e(t,e,0),depth:t.maxDepth}},$e=(e,t,r)=>{if(r>o)return!1;if(r>e.maxDepth&&(e.maxDepth=r),void 0===t)return!1;if("string"==typeof t){const e=a(t).kind;return"plain"===e||"unrecognized"===e}if(Array.isArray(t)){for(let a=0;a<t.length;a++)if(!$e(e,t[a],r+1))return!1;return!0}if(n(t)){for(const e in t){if("operator"===e||"fragment"===e||"vars"===e||"//"===e)return!1;if(e.startsWith("$"))return!1}for(const a in t)if(!$e(e,t[a],r+1))return!1;return!0}return!0},xe=(e,t)=>({parent:e,key:t}),je=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},Oe=e=>{e.sort((e,t)=>e.order-t.order)},Pe=e=>e.some(({issue:e})=>"error"===e.severity),Ae=e=>{const t=e.entry.definition.parameters.as;if("structural"!==t?.evaluation)return null;const r=e.params.as;return"constant"===r?.kind&&"string"==typeof r.value?r.value:null},Ce=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,De=(e,t,r)=>{"__proto__"===t?Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}):e[t]=r},Se=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=Ne(n,e.at,r[t],a)}),n},Ne=(e,t,r,a)=>{const n=ze(e,a),[o,...s]=t;return De(n,o,0===s.length?r:Ne(n[o],s,r,a)),n},ze=(e,t)=>{if(t.has(e))return e;const r=Array.isArray(e)?[...e]:{...e};return t.add(r),r},Te=/*#__PURE__*/new Set(["data","vars","params","element","index","d","v","p","e","i"]),Ee=(e,t,r={})=>{const a={registry:t,recognizes:e=>((e,t)=>"literal"===t||void 0!==Er(e,t)||e.fragments.has(t))(t,e),issues:[],order:0,nodeCount:0,maxDepth:0,dataPaths:new Map,dynamic:!1,operators:new Set,fragmentNames:new Set,fragmentCalls:[],dataReads:[],identityOnly:!1,scope:{bindings:[]},asNames:new Set,unrecognized:[],hasNoCache:!1},n=(r.basePath??[]).reduce(xe,null),o=Re(a,e,n,0);Me(a);const s=At(o);Oe(a.issues);const i=Pe(a.issues),l={nodeCount:a.nodeCount,maxDepth:a.maxDepth,dependencies:{dataPaths:a.dataPaths,dynamic:a.dynamic,operators:[...a.operators],fragments:[...a.fragmentNames]},identityOnly:a.identityOnly};return{root:o,holes:s,issues:a.issues,hasErrors:i,timeoutShielded:s.every(e=>void 0!==e.timeoutFallback),own:l,...qe(l,a.fragmentCalls,t.fragments),fragmentCalls:a.fragmentCalls,dataReads:a.dataReads,hasNoCache:a.hasNoCache}},qe=(e,t,r)=>{if(0===t.length)return e;const a=new Map(e.dependencies.dataPaths),n=new Set(e.dependencies.operators),o=new Set(e.dependencies.fragments);let{nodeCount:s,maxDepth:i,identityOnly:l}=e,c=e.dependencies.dynamic;for(const e of t){const t=r.get(e.name);if(void 0!==t){s+=t.nodeCount,i=Math.max(i,e.depth+t.maxDepth),l||=t.identityOnly,c||=t.dependencies.dynamic;for(const[e,r]of t.dependencies.dataPaths)a.set(e,r);for(const e of t.dependencies.operators)n.add(e);for(const e of t.dependencies.fragments)o.add(e)}}return{nodeCount:s,maxDepth:i,identityOnly:l,dependencies:{dataPaths:a,dynamic:c,operators:[...n],fragments:[...o]}}},Me=e=>{if(0!==e.asNames.size)for(const{token:t,issue:r,raw:a}of e.unrecognized)e.asNames.has(t)&&(r.issue={...r.issue,severity:"error",code:s.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},Fe=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:je(n)};void 0!==s.operator&&(i.operator=s.operator),void 0!==s.parameter&&(i.parameter=s.parameter),void 0!==s.suggestion&&(i.suggestion=s.suggestion);const l={issue:i,order:o};return e.issues.push(l),l},Re=(e,t,r,a)=>{const n=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>o)return Fe(e,"error",s.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Le(t,r,n);const i=Ie(e,t,r,a,n);return"operator"!==i.kind&&"fragmentCall"!==i.kind&&"reference"!==i.kind&&"invalid"!==i.kind||e.nodeCount++,i},Ie=(e,t,r,a,o)=>null==t?Ve(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Ve(t,r,o):"string"==typeof t?We(e,t,r,o):Array.isArray(t)?Je(e,t,r,a,o):n(t)?Be(e,t,r,a,o):(e.identityOnly=!0,Ve(t,r,o)),Ve=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Le=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),We=(e,t,r,n)=>{const o=a(t,e.scope);switch(o.kind){case"plain":return Ve(t,r,n);case"unrecognized":{const a=Fe(e,"warning",s.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,r,n),o=i(t);return null!==o&&e.unrecognized.push({token:o.token,issue:a,raw:t}),Ve(t,r,n)}case"invalid":return Fe(e,"error",o.code??s.invalidReference,`'${t}': ${o.reason}`,r,n),Le(t,r,n);case"reference":{const{namespace:a,segments:s,drill:i,binding:l}=o;return void 0!==l?{kind:"reference",namespace:a,segments:s,raw:t,binding:l,path:r,order:n}:("data"===a&&(0===s.length?e.dynamic=!0:at(e,s,i.startsWith(".")?i.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:s,raw:t,path:r,order:n})}}},Je=(e,t,r,a,n)=>{const o=Array.from(t,(t,n)=>({key:n,rawChild:t,node:Re(e,t,xe(r,n),a+1)}));return Pt(e,t,o,!0,!1,void 0,r,n)},Be=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return Fe(e,"error",s.malformedNode,o.message,r,n),Le(t,r,n);case"operator":return Ue(e,t,r,a,n);case"fragment":return bt(e,t,r,a,n);case"shorthand":return pt(e,t,o.key,r,a,n);case"plain":return jt(e,t,r,a,n)}},Ue=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return Fe(e,"error",s.malformedNode,"the 'operator' value must be a literal string",r,n),Le(t,r,n);if("literal"===o)return gt(e,t,t.value,"value"in t,r,n);const i=Er(e.registry,o);if(void 0===i){const a=f(o,St(e));return Fe(e,"error",s.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Le(t,r,n)}const l=Ke(e,i,r,n),c=[];for(const o in t){const i=t[o];"operator"!==o&&"//"!==o&&void 0!==i&&(Ge(e,l,o,i,r,a,n)||("parameters"!==o?He(e,l,c,o,i,xe(r,o),n):Fe(e,"error",s.malformedNode,"'parameters' is reserved and unused on operator nodes",xe(r,o),n,{operator:l.name})))}return Qe(e,l,c,a,n),l},Ke=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),Ge=(e,t,r,a,n,o,s)=>"fallback"===r?(t.fallback=Re(e,a,xe(n,"fallback"),o+1),!0):"noCache"===r?(_e(e,t,a,n,s),!0):"vars"===r&&(t.vars=xt(e,a,n,o,s),!0),_e=(e,t,r,a,n)=>{!0===r?(t.noCache=!0,e.hasNoCache=!0):Fe(e,"error",s.malformedNode,"'noCache' takes only the literal true — it is settled before the subtree runs",xe(a,"noCache"),n,"operator"===t.kind?{operator:t.name}:{})},He=(e,t,r,a,n,o,i)=>{if(void 0===t.entry.definition.parameters[a]){const r=f(a,Object.keys(t.entry.definition.parameters));return void Fe(e,"error",s.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,o,i,{operator:t.name,parameter:a,suggestion:r})}r.push({name:a,kind:"value",value:n,path:o})},Qe=(e,t,r,a,n)=>{const o=t.entry.definition,s=o.resolution.perElement.length>0;let i;if("get"===t.name&&Xe(e,t,r),s){const a=r.find(e=>"as"===e.name&&"structural"===o.parameters.as?.evaluation&&"value"===e.kind);void 0!==a&&"value"===a.kind&&(i=dt(e,t,a.value,a.path,n))}for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"!==r&&(t.params[n.name]=ot(e,n,r,a))}if(s){void 0!==i&&e.scope.bindings.push(i);for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"===r&&(t.params[n.name]=ot(e,n,r,a))}void 0!==i&&e.scope.bindings.pop()}nt(e,t),Ze(e,t)},Xe=(e,t,r)=>{const a=r.findIndex(e=>"from"===e.name),n=r[a];if("value"!==n?.kind||"string"!=typeof n.value)return;const o=y(n.value);if("data"===o&&r.splice(a,1),"vars"!==o&&"params"!==o)return;const i=r.find(e=>"path"===e.name),l="value"===i?.kind?Ye(e,i.value):null;if(null===l||"value"!==i?.kind){if("vars"!==o)return;const i=e.order++;return Fe(e,"error",s.bareVars,`'${n.value}': with 'from: ${n.value}' the path's first key names the var, so the path must be written out and start with a key`,n.path,i,{operator:"get",parameter:"from"}),r.splice(a,1),void(t.params.from=Le(n.value,n.path,i))}const[c,...u]=l;n.value=g(o,[c]),i.value=Array.isArray(i.value)?u:d(u)},Ye=(e,t)=>{const r=t=>{if("string"!=typeof t)return k(t);const{kind:r}=a(t,e.scope);return"plain"===r||"unrecognized"===r};try{const e=Array.isArray(t)?t.every(r)&&t:"string"==typeof t&&r(t)&&w(t);return e&&"string"==typeof e[0]?e:null}catch{return null}},Ze=(e,t)=>{if("buildString"!==t.name)return;((e,t)=>{const r=t.params.substitutions;if(void 0===r)return;const a="constant"===r.kind?r.value:"skeleton"===r.kind?r.skeleton:void 0;(Array.isArray(a)||n(a))&&Object.values(a).some(ae)&&Fe(e,"error",s.operatorValidate,ne,r.path,r.order,{operator:t.name,parameter:"substitutions"})})(e,t);const r=t.params.template;if("constant"!==r?.kind||"string"!=typeof r.value)return;const a=we(r.value).filter(e=>"text"!==e.kind);if(0===a.length)return;const o=t.params.substitutions,i=(e=>{if(void 0===e)return{mode:"absent"};if("constant"===e.kind)return Array.isArray(e.value)?{mode:"array",length:e.value.length}:n(e.value)?{mode:"object",keys:new Set(Object.keys(e.value))}:{mode:"dynamic"};if("skeleton"===e.kind){const{skeleton:t,holes:r}=e;if(Array.isArray(t))return{mode:"array",length:t.length};if(n(t)){const e=new Set(Object.keys(t));for(const t of r)e.add(String(t.at[0]));return{mode:"object",keys:e}}}return{mode:"dynamic"}})(o);if(tt(e,t,r,a,i),"absent"!==i.mode&&"object"!==i.mode)return;const l=[],c=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(c.has(t.body))continue;const a=We(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,c.add(t.body),l.push({path:r.path,at:[t.body],node:a}))}0!==l.length&&(t.params.substitutions=et(e,t,o,l))},et=(e,t,r,a)=>{const n="skeleton"===r?.kind?{...r,skeleton:{...r.skeleton},holes:[...r.holes]}:{kind:"skeleton",skeleton:"constant"===r?.kind?{...r.value}:{},holes:[],path:r?.path??xe(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},tt=(e,t,r,a,n)=>{const o=(a,n)=>Fe(e,"warning",a,n,r.path,r.order,{operator:t.name}),i=(e,t)=>o(s.unboundToken,`'${e}' binds to nothing and renders as its own text${t}`),l=e=>{for(const t of e)o(s.unusedSubstitution,`substitution ${t} is never named by the template`)};if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&o(s.inertReferenceToken,`a reference token needs the named face — beside ${"array"===n.mode?"positional substitutions":"a dynamically supplied map"} it is not recognized and renders as its own text`),"array"===n.mode){const e=new Set,t=[];for(const r of a)"positional"===r.kind&&(r.index>=1&&r.index<=n.length?e.add(r.index):t.push(r));const r=[];for(let t=1;t<=n.length;t++)e.has(t)||r.push(String(t));if(0===t.length)return void l(r);const o=0===n.length?"there are no substitutions":1===n.length?"there is only 1 substitution":`there are only ${n.length} substitutions`;for(const e of t)i(e.raw,` — ${e.index<1?"numbering starts at %1":o}${rt(r)}`);return}if("object"===n.mode){const e=new Set,t=[];for(const r of a)"named"===r.kind&&(n.keys.has(r.body)?e.add(r.body):r.body.startsWith("$")||t.push(r.raw));const r=[...n.keys].filter(t=>!e.has(t)).map(e=>`'${e}'`);0===t.length&&l(r);for(const e of t)i(e,rt(r))}},rt=e=>{if(0===e.length)return"";if(1===e.length)return`, and substitution ${e[0]} is unused`;const t=e[e.length-1];return`, and substitutions ${e.slice(0,-1).join(", ")} and ${t} are unused`},at=(e,t,r,a)=>{let n,o;void 0!==r&&c(r)?(n=r,o=t):(o=u(t),n=d(o)),e.dataPaths.set(n,o),e.dataReads.push({kind:"path",key:n,segments:o,path:a})},nt=(e,t)=>{if("get"!==t.name||void 0!==t.params.from)return;const r=t.params.path;if(void 0!==r)if("constant"===r.kind)try{const a="string"==typeof r.value?w(r.value):r.value;if(!Array.isArray(a)||!a.every(k))return void(e.dynamic=!0);if(0===a.length)return void(e.dynamic=!0);at(e,a,"string"==typeof r.value?r.value:void 0,t.path)}catch{e.dynamic=!0}else e.dynamic=!0},ot=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=ct(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=ut(e,t,a);if(null!==r)return r}return"value"===t.kind?Re(e,t.value,t.path,a+1):st(e,t,a)},st=(e,t,r)=>{const{order:a,containerDepth:n}=it(e,r),o=lt(e,t.elements,t.basePath,t.offset,n);return Pt(e,t.elements,o,!0,!1,void 0,t.basePath,a)},it=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},lt=(e,t,r,a,n)=>Array.from(t,(t,o)=>({key:o,rawChild:t,node:Re(e,t,xe(r,a+o),n+1)})),ct=(e,t,r)=>{const a="slice"===t.kind?t.elements:t.value;if(!Array.isArray(a))return null;const n="slice"===t.kind?t.basePath:t.path,o="slice"===t.kind?t.offset:0,{order:s,containerDepth:i}=it(e,r),l=lt(e,a,n,o,i);if(l.every(e=>"constant"===e.node.kind))return Pt(e,a,l,!0,!1,void 0,n,s);return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:s}},ut=(e,t,r)=>{if("value"!==t.kind)return null;const a=t.value;if(!n(a)||m(a,e.recognizes))return null;const{order:o,containerDepth:s}=it(e,r),{entries:i,vars:l,changed:c}=Ot(e,a,t.path,s,o,!0);if(i.every(e=>"constant"===e.node.kind))return Pt(e,a,i,!1,c,l,t.path,o);const u={};for(const{key:e,node:t}of i)u[String(e)]=t;const d={kind:"entries",entries:u,path:t.path,order:o};return void 0!==l&&(d.vars=l),d},dt=(e,t,n,o,i)=>{const l=r=>{Fe(e,"error",s.invalidAs,r,o,i,{operator:t.name})};if("string"!=typeof n||"plain"!==a(n).kind)return l("'as' must be a literal name — a dynamic value cannot be statically resolved");const c=r(n);if(!c.ok)return l(`'${n}' is not a legal binding name — ${c.reason}`);const u=[n,$(n)];for(const t of u){if(Te.has(t))return l(`'${n}' collides with the reserved namespace word '${t}'`);if(null!==b(t,e.scope.bindings))return l(`'${n}' collides with an enclosing 'as' binding ('${t}')`)}for(const t of u)e.asNames.add(t);return n},pt=(e,t,r,a,n,o)=>{const i=r.slice(1),l="literal"===i,c=!l&&e.registry.fragments.has(i);for(const n in t)if(n!==r&&!p.has(n))return Fe(e,"error",s.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,xe(a,n),o),Le(t,a,o);const u=t[r],d=xe(a,r);if(l){for(const r of["fallback","vars","noCache"])r in t&&Fe(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,xe(a,r),o);return gt(e,t,u,!0,a,o)}if(c)return wt(e,t,i,u,a,n,o);const f=Er(e.registry,i),m=Ke(e,f,a,o);for(const s in t){const i=t[s];s!==r&&"//"!==s&&void 0!==i&&Ge(e,m,s,i,a,n,o)}const h=[];return ft(e,m,h,u,d,o),Qe(e,m,h,n,o),m},ft=(e,t,r,a,o,s)=>{if(Array.isArray(a))ht(e,t,r,a,o,s);else if(!n(a)||m(a,e.recognizes))mt(e,t,r,a,o,s);else for(const n in a){const i=a[n];"//"!==n&&void 0!==i&&He(e,t,r,n,i,xe(o,n),s)}},mt=(e,t,r,a,n,o)=>{const s=v(t.entry.definition);null!==s?r.push({name:s,kind:"value",value:a,path:n}):vt(e,t,n,o)},ht=(e,t,r,a,n,o)=>{const s=t.entry.definition,i=h(s,a.length);if(null===i)return void yt(e,t,a,n,o);const l=s.positionalParams;for(let e=0;e<i.bound;e++)r.push({name:l[e],kind:"value",value:a[e],path:xe(n,e)});const{restAt:c}=i;null!==c&&r.push({name:s.restParam,kind:"slice",elements:0===c?a:a.slice(c),basePath:n,offset:c})},vt=(e,t,r,a)=>Fe(e,"error",s.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),yt=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void vt(e,t,a,n);const i=o.length;Fe(e,"error",s.positionalArity,`'${t.name}' takes at most ${i} positional argument${1===i?"":"s"} (${o.join(", ")}), got ${r.length}`,a,n,{operator:t.name})},gt=(e,t,r,a,n,o)=>{if("operator"in t){for(const r in t)"operator"!==r&&"value"!==r&&"//"!==r&&("fallback"!==r&&"vars"!==r&&"noCache"!==r?Fe(e,"error",s.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,xe(n,r),o,{operator:"literal"}):Fe(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,xe(n,r),o));if(!a)return Fe(e,"error",s.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Le(t,n,o)}return Ve(r,n,o)},bt=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return Fe(e,"error",s.malformedNode,"the 'fragment' value must be a literal string",r,n),Le(t,r,n);const i={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};kt(e,i,a);for(const o in t){const l=t[o];"fragment"!==o&&"//"!==o&&void 0!==l&&("parameters"!==o?"fallback"!==o?"vars"!==o?"noCache"!==o?Fe(e,"error",s.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,xe(r,o),n):_e(e,i,l,r,n):i.vars=xt(e,l,r,a,n):i.fallback=Re(e,l,xe(r,"fallback"),a+1):$t(e,i,l,xe(r,"parameters"),a,n))}return i},wt=(e,t,r,a,o,i,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};kt(e,c,i);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=Re(e,n,xe(o,"fallback"),i+1)),"noCache"===a&&_e(e,c,n,o,l),"vars"===a&&(c.vars=xt(e,n,o,i,l)))}return n(a)?$t(e,c,a,xe(o,`$${r}`),i,l):Fe(e,"error",s.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,xe(o,`$${r}`),l),c},kt=(e,t,r)=>{const{name:a,path:n,order:o}=t;e.fragmentNames.add(a);const i=e.registry.fragments.get(a);if(void 0===i){const t=f(a,e.registry.fragments.keys());return void Fe(e,"error",s.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,o,{suggestion:t})}t.entry=i,e.fragmentCalls.push({name:a,depth:r}),e.dataReads.push({kind:"call",fragment:i,path:n})},$t=(e,t,r,o,i,l)=>{if(void 0!==r){if(m(r,e.recognizes)||"string"==typeof r&&"reference"===a(r).kind)return t.argumentsMode="dynamic",t.parameters=Re(e,r,o,i+1),void(e.dynamic=!0);if(n(r)){const a={};for(const t in r){const n=r[t];"//"!==t&&void 0!==n&&(a[t]=Re(e,n,xe(o,t),i+1))}return void(t.parameters=a)}Fe(e,"error",s.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},xt=(e,t,a,o,i)=>{const l=xe(a,"vars");if(!n(t))return void Fe(e,"error",s.invalidVars,"a 'vars' block must be an object of name → expression entries",l,i);const c={};for(const a in t){const n=t[a];if("//"===a||void 0===n)continue;const u=xe(l,a),d=r(a);d.ok?c[a]=Re(e,n,u,o+1):Fe(e,"error",s.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,i)}return c},jt=(e,t,r,a,n)=>{const{entries:o,vars:s,changed:i}=Ot(e,t,r,a,n);return Pt(e,t,o,!1,i,s,r,n)},Ot=(e,t,r,a,n,o=!1)=>{let i,l=!1;const c=[];for(const u in t){const d=t[u];if("//"!==u)if("vars"!==u)if(void 0!==d){if(u.startsWith("$")){const t=f(u.slice(1),St(e)),a=void 0!==t?` — did you mean '$${t}'?`:o?"":" — data with a '$' key goes inside 'literal'";Fe(e,o?"warning":"error",s.unrecognizedIdentifier,`'${u}' is not a registered operator or fragment${o?", so it is a plain key":""}${a}`,xe(r,u),n,{suggestion:void 0===t?void 0:`$${t}`})}c.push({key:u,rawChild:d,node:Re(e,d,xe(r,u),a+1)})}else l=!0;else i=xt(e,d,r,a,n),l=!0;else l=!0}return{entries:c,vars:i,changed:l}},Pt=(e,t,r,a,n,o,i,l)=>{const c=[],u=a?new Array(r.length):{};let d=n;for(const{key:e,rawChild:t,node:a}of r)"constant"!==a.kind?(d=!0,"skeleton"!==a.kind||void 0!==a.vars?c.push({path:a.path,at:[e],node:a}):(De(u,e,a.skeleton),c.push(...a.holes.map(t=>({...t,at:[e,...t.at]}))))):(De(u,e,a.value),a.value!==t&&(d=!0));if(0===c.length)return void 0!==o&&Object.keys(o).length>0&&Fe(e,"warning",s.unreferencedVar,"this vars block declares names nothing in its scope references",xe(i,"vars"),l),Ve(d||void 0!==o?u:t,i,l);const p={kind:"skeleton",skeleton:u,holes:c,path:i,order:l};return void 0!==o&&(p.vars=o),p},At=(e,t=[])=>{if("skeleton"===e.kind)for(const r of e.holes)At(r.node,t);else if("constant"!==e.kind){const r=Ct(e);t.push(void 0===r?{node:e}:{node:e,timeoutFallback:r})}return t},Ct=e=>{if("operator"===e.kind||"fragmentCall"===e.kind){if(void 0!==e.fallback)return"constant"===e.fallback.kind?{value:e.fallback.value}:void 0;if("operator"===e.kind){const t=e.entry.hostDefaults;return void 0!==t&&Object.hasOwn(t,"fallback")?{value:t.fallback}:void 0}return e.entry?.timeoutFallback}},Dt=new WeakMap,St=e=>{const t=Dt.get(e.registry);if(void 0!==t)return t;const r=[...e.registry.operators.keys(),...e.registry.aliases.keys(),...e.registry.fragments.keys()];return Dt.set(e.registry,r),r},Nt=e=>{switch(e.kind){case"operator":return e.entry.definition.returns;case"fragmentCall":return e.entry?.returns??"any";case"skeleton":return Array.isArray(e.skeleton)?"array":"object";case"constant":return zt(e.value);default:return"any"}},zt=t=>{if(null===t)return"null";if(Array.isArray(t))return"array";if(e(t))return"object";switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"any"}},Tt=/*#__PURE__*/Object.freeze({parsePath:w,resolvePath:x,checkType:J,checkConstraints:B,describeType:F,renderText:re,isTruthy:se}),Et=(e,t={})=>{Mt({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),Oe(e.issues),e.hasErrors=Pe(e.issues)},qt=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:je(n)};void 0!==s.operator&&(i.operator=s.operator),void 0!==s.fragment&&(i.fragment=s.fragment),void 0!==s.parameter&&(i.parameter=s.parameter),void 0!==s.suggestion&&(i.suggestion=s.suggestion),e.artifact.issues.push({issue:i,order:o})},Mt=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Gt(e,t);case"skeleton":{const r=Xt(e,t.vars,t.path);for(const r of t.holes)Mt(e,r.node);return void Yt(e,r)}case"fragmentCall":return void Ut(e,t);case"elements":for(const r of t.nodes)Mt(e,r);return;case"entries":{const r=Xt(e,t.vars,t.path);for(const r in t.entries)Mt(e,t.entries[r]);return void Yt(e,r)}case"operator":return void Rt(e,t)}return t},Ft=e=>"kind"in e&&"string"==typeof e.kind,Rt=(e,t)=>{const r=Xt(e,t.vars,t.path);void 0!==t.fallback&&Mt(e,t.fallback);const a=t.entry.definition,n=Bt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?Vt(e,n,r,o,a,It(t,r)):o.required&&qt(e,"error",s.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}Kt(e,t);const o=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?o.push([r,n]):Mt(e,n)}if(o.length>0){const r={as:Ae(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)Mt(e,t);e.iteratorFrames.pop(),r.referenced||qt(e,"warning",s.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}Yt(e,r)},It=(e,t)=>{const{definition:r,hostDefaults:a}=e.entry;if(void 0!==r.parameters[t]?.elementNullPolicy)return!1;for(const[n,o]of r.resolution.entries){if(!o.replacesNullAt?.includes(t))continue;const r=e.params[n];if(void 0===r){if(void 0!==a&&Object.hasOwn(a,n)&&null!==a[n])return!0}else if("constant"!==r.kind||null!==r.value)return!0}return!1},Vt=(e,t,r,a,n,o=!1)=>{if("elements"===n.kind){const o=a.constraints?.length;return void(void 0!==o&&n.nodes.length!==o&&qt(e,"error",s.typeCheck,`'${t.label}.${r}': expected ${o} element${1===o?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("constant"!==n.kind&&"structural"===a.evaluation&&"as"!==r)return void qt(e,"error",s.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r});const i=`'${t.label}.${r}'`,l=Wt(a,n,o);void 0!==l&&qt(e,"error",l.code,l.code===s.returnsMismatch?`${l.reason} — it can never satisfy ${i}`:`${i}: ${l.reason}`,n.path,n.order,{...t.extra,parameter:r});let c=n;for(;"operator"===c.kind||"fragmentCall"===c.kind;){const n=c.fallback;if(void 0===n)return void("operator"===c.kind&&Lt(e,t,r,a,c,o));const l=Wt(a,n,o);void 0!==l&&qt(e,"warning",s.fallbackMismatch,`this fallback can never satisfy ${i}: ${l.reason}`,n.path,n.order,{...t.extra,parameter:r}),c=n}},Lt=(e,t,r,a,n,o)=>{const i=n.entry.hostDefaults;if(void 0===i||!Object.hasOwn(i,"fallback"))return;const l=Jt(a,i.fallback,o);void 0!==l&&qt(e,"warning",s.fallbackMismatch,`'${n.name}' falls back to its operatorDefaults fallback, which can never satisfy '${t.label}.${r}': ${l.reason}`,n.path,n.order,{...t.extra,parameter:r})},Wt=(e,t,r)=>{switch(t.kind){case"constant":return Jt(e,t.value,r);case"operator":case"fragmentCall":{if("fragmentCall"===t.kind&&void 0===t.entry)return;const r=Nt(t);if(j(r,e.type))return;const a="operator"===t.kind?`'${t.name}'`:`fragment '${t.name}'`;return{code:s.returnsMismatch,reason:`${a} returns ${JSON.stringify(r)}`}}case"skeleton":{const r=J(Array.isArray(t.skeleton)?[]:{},e.type);return r.ok?void 0:{code:s.typeCheck,reason:`expected ${r.expected}, received ${r.actual}`}}default:return}},Jt=(e,t,r)=>{if(null===t&&(r||!e.required&&!V(e.type)))return;const a=J(t,e.type);if(!a.ok)return{code:s.typeCheck,reason:`expected ${a.expected}, received ${a.actual}`};if(void 0===e.constraints)return;const n=H(t,e.constraints,void 0!==e.elementNullPolicy);return n.ok?void 0:{code:s.typeCheck,reason:`expected ${n.expected}, received ${n.actual}`}},Bt=e=>({label:e.name,extra:{operator:e.name}}),Ut=(e,t)=>{const r=Xt(e,t.vars,t.path);void 0!==t.fallback&&Mt(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||Ft(t.parameters)?void 0:t.parameters;if(void 0!==a&&"static"===t.argumentsMode){const r={label:t.name,extra:{fragment:t.name}};for(const o in a){const i=a[o],l=n?.[o];void 0!==l?Vt(e,r,o,i,l):i.required&&qt(e,"error",s.missingRequired,`fragment '${t.name}' – requires '${o}'`,t.path,t.order,{fragment:t.name,parameter:o})}if(void 0!==n)for(const r in n){const o=n[r];if(void 0===a[r]){const n=f(r,Object.keys(a));qt(e,"error",s.unknownNodeKey,`fragment '${t.name}' declares no parameter '${r}'${n?` — did you mean '${n}'?`:""}`,o.path,o.order,{parameter:r,suggestion:n})}}}if(void 0!==t.parameters)if(Ft(t.parameters))Mt(e,t.parameters);else for(const r in t.parameters)Mt(e,t.parameters[r]);Yt(e,r)},Kt=(e,t)=>{const r=t.entry.definition.validate;if(void 0===r)return;const a={};for(const e in t.params){const r=t.params[e];"constant"===r.kind&&(a[e]=r.value)}let n;try{n=r(a,Tt)}catch(r){return void qt(e,"error",s.operatorValidate,`'${t.name}' validate hook threw: ${r.message}`,t.path,t.order,{operator:t.name})}for(const r of n){const a=void 0!==r.parameter?t.params[r.parameter]:void 0;qt(e,r.severity,s.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Gt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void _t(e,t);case"params":return void Ht(e,t);case"element":case"index":return void Qt(e,t,t.namespace)}},_t=(e,t)=>{const r=t.segments[0],a="string"==typeof r?r:void 0;if(void 0!==a)for(let t=e.varsFrames.length-1;t>=0;t--){const r=e.varsFrames[t],n=r.names.get(a);if(void 0!==n){if(n.referenced=!0,null!==r.currentVar){const e=r.edges.get(r.currentVar)??new Set;e.add(a),r.edges.set(r.currentVar,e)}return}}qt(e,"error",s.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},Ht=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void qt(e,"error",s.unresolvedParam,`'${t.raw}': $params is only available inside a fragment body`,t.path,t.order);if(0===t.segments.length)return;const a=t.segments[0];"string"==typeof a&&r.has(a)||qt(e,"error",s.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Qt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Ce(n.as,r,t.binding))return void(n.referenced=!0)}qt(e,"error",s.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Xt=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=xe(r,"vars");for(const r in t){const o=t[r],i=xe(n,r);for(const t of e.varsFrames)if(t.names.has(r)){qt(e,"warning",s.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,i,o.order);break}a.names.set(r,{node:o,declaredAt:i,order:o.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,Mt(e,r.node),a.currentVar=null;return a},Yt=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||qt(e,"warning",s.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Zt(e,t)}},Zt=(e,t)=>{const r=new Map([...t.names.keys()].map((e,t)=>[e,t])),a=[],n=new Set,o=new Set,i=new Set,l=c=>{if(!o.has(c))if(n.has(c))(a=>{const n=[...a].sort((e,t)=>r.get(e)-r.get(t)),o=n.join("\0");if(i.has(o))return;i.add(o);const l=n.map(e=>`'${e}'`),c=1===l.length?`${l[0]} depends on itself`:`${l.slice(0,-1).join(", ")} and ${l[l.length-1]} form a vars cycle — a var may not depend on itself`,u=t.names.get(n[0]);qt(e,"error",s.varCycle,c,u.declaredAt,u.order)})(a.slice(a.indexOf(c)));else{n.add(c),a.push(c);for(const e of t.edges.get(c)??[])l(e);a.pop(),n.delete(c),o.add(c)}};for(const e of t.names.keys())l(e)},er={capable:!1,effective:!1,disabled:[]},tr={capable:!0,effective:!0,disabled:[]},rr=e=>{const{effective:t}=ar(e,e.root,!1);return Oe(e.issues),t},ar=(e,t,r)=>{switch(t.kind){case"constant":case"reference":return er;case"invalid":return tr;case"skeleton":return lr(e,[...t.holes.map(e=>e.node),...cr(t.vars)],r);case"elements":return lr(e,t.nodes,r);case"entries":return lr(e,[...Object.values(t.entries),...cr(t.vars)],r);case"operator":return nr(e,t,Sr(t.entry),r);case"fragmentCall":return nr(e,t,t.entry?.caches??!0,r)}return t},nr=(e,t,r,a)=>{const n=!0===t.noCache,o=lr(e,ir(t),a||n),s=r||o.capable,i=or(t),l=void 0===i?o.disabled:[i,...o.disabled];return n&&a?ur(e,t,"'noCache' is redundant — an enclosing node already sets it"):n&&!s&&ur(e,t,l.length>0?`'noCache' is redundant — caching is already disabled for ${sr(l)}`:"'noCache' is dead — nothing beneath this node caches"),{capable:s,effective:!n&&(r||o.effective),disabled:l}},or=e=>"operator"===e.kind&&e.entry.definition.cache&&!Sr(e.entry)?e.entry.definition.name:void 0,sr=e=>{const t=[...new Set(e)].map(e=>`'${e}'`);return t.length<2?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`},ir=e=>{const t=[];return"operator"===e.kind?t.push(...Object.values(e.params)):void 0!==e.parameters&&("dynamic"===e.argumentsMode?t.push(e.parameters):t.push(...Object.values(e.parameters))),void 0!==e.fallback&&t.push(e.fallback),t.push(...cr(e.vars)),t},lr=(e,t,r)=>{const a={capable:!1,effective:!1,disabled:[]};for(const n of t){const{capable:t,effective:o,disabled:s}=ar(e,n,r);a.capable||=t,a.effective||=o,a.disabled.push(...s)}return a},cr=e=>void 0===e?[]:Object.values(e),ur=(e,t,r)=>{const a={severity:"warning",code:s.uselessModifier,message:r,path:je(xe(t.path,"noCache"))};"operator"===t.kind?a.operator=t.name:a.fragment=t.name,e.issues.push({issue:a,order:t.order})};class dr{max;entries=new Map;constructor(e){this.max=e,pr(e)}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.max&&this.evictOldest()}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}resize(e){for(pr(e),this.max=e;this.entries.size>this.max;)this.evictOldest()}evictOldest(){const e=this.entries.keys().next();!0!==e.done&&this.entries.delete(e.value)}}const pr=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},fr=Symbol("fig-tree:lazy-handle"),mr="~",hr=(e,t)=>{if(t>o)return"refused";switch(typeof e){case"boolean":return"json";case"string":return e.length>4096?"serializer":"json";case"number":return Number.isFinite(e)&&!Object.is(e,-0)?"json":"serializer";case"undefined":return"serializer";case"object":break;default:return"refused"}if(null===e)return"json";if(Array.isArray(e)){for(let r=0;r<e.length;r++){const a=hr(e[r],t+1);if("json"!==a)return a}return"json"}if(!n(e))return"refused";for(const r in e){if(r.length>4096)return"serializer";const a=hr(e[r],t+1);if("json"!==a)return a}return"json"},vr=(e,t)=>yr(e,0,t)?t.join(""):void 0,yr=(e,t,r)=>{if(t>o)return!1;if(null===e)return br(r,"n");if(void 0===e)return br(r,"u");switch(typeof e){case"boolean":return br(r,e?"t":"f");case"number":return gr(e,r);case"string":return br(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!yr(a,t+1,r))return!1;return br(r,"]")}if(!n(e)||fr in e)return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!yr(e[a],t+1,r))return!1;return br(r,"}")},gr=(e,t)=>Number.isNaN(e)?br(t,"N"):e===1/0?br(t,"I"):e===-1/0?br(t,"J"):Object.is(e,-0)?br(t,"#-0"):br(t,`#${String(e)}`),br=(e,t)=>(e.push(t),!0);class wr{deps;identity=new WeakMap;content=new dr(200);constructor(e){this.deps=e}resolve(e){const t="object"==typeof e&&null!==e?e:void 0;if(void 0!==t){const e=this.identity.get(t);if(void 0!==e)return e}const r=this.deps.probe(e);if(r.constant){const e={kind:"inert",depth:r.depth};return void 0!==t&&this.identity.set(t,e),e}const a=void 0===t?void 0:(e=>{const t=hr(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?vr(e,[mr]):void 0})(e),n=void 0===a?void 0:this.content.get(a),o=n??this.deps.compile(e),s={kind:"artifact",artifact:o};return void 0!==t&&this.identity.set(t,s),void 0!==a&&void 0===n&&!o.identityOnly&&o.holes.length>0&&this.content.set(a,o),s}}const kr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),$r=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),xr=(t,a,n)=>{const o=(...e)=>["fragments",t,...e],i=r(t);if(!i.ok)return void n(s.invalidName,`'${t}' is not a legal fragment name: ${i.reason}`,o());if(O.has(t))return void n(s.reservedName,`'${t}' is a reserved name and may not name a fragment`,o());if(!e(a))return void n(s.invalidDefinition,`fragment '${t}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,o());if(!("expression"in a))return void n(s.invalidDefinition,`fragment '${t}' has no 'expression'`,o());for(const e of Object.keys(a))$r.has(e)||n(s.invalidDefinition,`'${e}' is not a key of a fragment definition`,o(e));const l={name:t,parameters:{},body:{kind:"constant",value:null,path:null,order:0},returns:"any",warnings:[],nodeCount:0,maxDepth:0,dependencies:{dataPaths:new Map,dynamic:!1,operators:[],fragments:[]},identityOnly:!1,caches:!1};if(void 0!==a.description&&("string"!=typeof a.description?n(s.invalidDefinition,"'description' must be a string",o("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(s.invalidDefinition,"'metadata' must be a plain object",o("metadata"))),void 0!==a.parameters)if(e(a.parameters))for(const[e,t]of Object.entries(a.parameters)){const r=jr(e,t,o,n);void 0!==r&&(l.parameters[e]=r)}else n(s.invalidDefinition,"'parameters' must be a plain object",o("parameters"));return l},jr=(t,a,n,o)=>{const i=n("parameters",t),l=r(t);if(!l.ok)return void o(s.invalidName,`'${t}' is not a legal parameter name: ${l.reason}`,i);if(P.has(t))return void o(s.reservedName,`'${t}' is a reserved node key and may not name a parameter`,i);if(!e(a))return void o(s.invalidDefinition,`the declaration of '${t}' must be an object`,i);for(const e of Object.keys(a))kr.has(e)||o(s.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...i,e]);const c=a.type??"any";if(!W(c))return void o(s.invalidDefinition,`'${t}' declares an unknown type`,[...i,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void o(s.invalidDefinition,"'required' must be a boolean",[...i,"required"]);let u;if(void 0!==a.constraints){const e=G(a.constraints);if(!e.ok)return void o(s.invalidDefinition,`'${t}' declares invalid constraints: expected ${e.expected}, got ${e.actual}`,[...i,"constraints"]);u=a.constraints}const d="default"in a;if(d&&!0===a.required)return void o(s.invalidDefinition,`'${t}' is declared required and also declares a default — the default could never apply`,[...i,"default"]);if(d){const e=J(a.default,c);if(!e.ok)return void o(s.typeCheck,`the default for '${t}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...i,"default"]);if(void 0!==u){const e=B(a.default,u);if(!e.ok)return void o(s.typeCheck,`the default for '${t}' violates its declared constraints: expected ${e.expected}, got ${e.actual}`,[...i,"default"])}}const p={type:c,required:a.required??!d};return d&&(p.default=a.default),"string"==typeof a.description&&(p.description=a.description),e(a.metadata)&&(p.metadata=a.metadata),void 0!==u&&(p.constraints=u),p},Or=e=>{const t=new Set,r=new Set,a=e=>{if(r.has(e.name)||t.has(e.name))return;t.add(e.name);const n=e.body;"fragmentCall"===n.kind&&void 0!==n.entry&&a(n.entry),e.returns=Nt(n),t.delete(e.name),r.add(e.name)};for(const t of e.fragments.values())a(t)},Pr=(e,t)=>{const r=[],a=new Set,n=new Set,o=i=>{const l=r.indexOf(i);if(-1!==l){const e=[...r.slice(l),i],a=[...e].sort().join("\0");return n.has(a)||t(s.fragmentCycle,`fragment '${i}' reaches itself: ${e.join(" → ")} — recursion is not supported`,["fragments",i]),void n.add(a)}if(!a.has(i)){r.push(i);for(const t of e.get(i)?.fragmentCalls??[])o(t.name);r.pop(),a.add(i)}};for(const t of e.keys())o(t);return 0===n.size},Ar=(e,t)=>{const r=new Set,a=n=>{if(r.has(n))return;r.add(n);const o=e.fragments.get(n),s=t.get(n);if(void 0===o||void 0===s)return;for(const e of s.fragmentCalls)a(e.name);const i=qe(s.own,s.fragmentCalls,e.fragments);o.nodeCount=i.nodeCount,o.maxDepth=i.maxDepth,o.dependencies=i.dependencies,o.identityOnly=i.identityOnly,o.caches=rr(s),o.timeoutFallback=Cr(s,e.fragments)};for(const e of t.keys())a(e)},Cr=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=Dr(e,t);if(void 0===r)return;n.push(r.value)}let o=0;const s=e=>"skeleton"===e.kind?Se(e.skeleton,e.holes,e.holes.map(e=>s(e.node))):n[o++];return{value:s(r)}},Dr=(e,t)=>{if(void 0!==e.timeoutFallback)return e.timeoutFallback;const{node:r}=e;return"fragmentCall"===r.kind&&void 0===r.fallback?t.get(r.name)?.timeoutFallback:void 0},Sr=e=>e.definition.cache&&!0!==e.hostDefaults?.noCache,Nr=["fallback","noCache"],zr=t=>{const r=[],a=(e,t,a,n)=>{r.push({severity:"error",code:e,message:t,path:a,...void 0!==n?{operator:n}:{}})},n={operators:new Map,aliases:new Map,fragments:new Map},{operators:o,aliases:i}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(s.duplicateOperator,`'${e}' is already registered (by '${n}') — one namespace, no silent precedence`,t,r),!1):(l.set(e,r),!0)},u=(e,t)=>{if("function"==typeof e)return void a(s.invalidOptions,`operators[${t[1]}]${t.length>2?`[${t[2]}]`:""} is a function — factories must be called: httpOperators(client)`,t);if(!Z(e))return void a(s.invalidOptions,"every operators entry must be built with defineOperator() — a plain definition object is not accepted",t);const{name:r,alias:n}=e,l=c(r,t,r),u=void 0===n||c(n,t,r);l&&u&&(o.set(r,{definition:e}),void 0!==n&&i.set(n,r))};return Array.isArray(t.operators)?t.operators.forEach((e,t)=>{Array.isArray(e)?e.forEach((e,r)=>{Array.isArray(e)?a(s.invalidOptions,"'operators' is flattened one level only — arrays may not nest deeper",["operators",t,r]):u(e,["operators",t,r])}):u(e,["operators",t])}):a(s.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&Tr(t.operatorDefaults,o,i,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(s.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=xr(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const o=new Map;for(const[e,a]of r.fragments){const n=t[e],s=Ee(n.expression,r,{basePath:["expression"]});a.body=s.root,o.set(e,s)}Or(r);for(const[e,t]of r.fragments){const r=o.get(e);Et(r,{fragmentParams:new Set(Object.keys(t.parameters))});for(const{issue:t}of r.issues)"error"===t.severity&&n(t.code,`fragment '${e}': ${t.message}`,["fragments",e,...t.path])}Pr(o,n)&&Ar(r,o);for(const[e,t]of r.fragments)for(const{issue:r}of o.get(e).issues)if("error"!==r.severity){const e={...r,path:[...r.path]};Object.freeze(e.path),t.warnings.push(Object.freeze(e))}})(t.fragments,n,(e,t)=>c(e,t,e),a),r.length>0&&(e=>{const[t]=e,r=e.length-1,a=r>0?`${t.message} (+ ${r} more issue${1===r?"":"s"})`:t.message;throw new A({code:s.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},Tr=(t,r,a,n)=>{if(e(t))for(const[o,i]of Object.entries(t)){const t=["operatorDefaults",o],l=r.get(o);if(void 0===l){const e=a.get(o);void 0!==e?n(s.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${o}'`,t,e):n(s.unknownOperator,`'${o}' names no registered operator`,t);continue}if(!e(i)){n(s.invalidOptions,`the defaults for '${o}' must be a plain object`,t,o);continue}let c=!0;for(const[e,r]of Object.entries(i)){const a=[...t,e];if(Nr.includes(e)){"fallback"!==e||ke(r).constant||(n(s.invalidOptions,`the default fallback for '${o}' must be a constant value — it is returned as written, never evaluated`,a,o),c=!1),"noCache"===e&&(!0!==r?(n(s.invalidOptions,"the 'noCache' modifier takes only the literal true",a,o),c=!1):l.definition.cache||(n(s.invalidOptions,`'noCache' on '${o}', which never caches — its definition does not declare 'cache: true'`,a,o),c=!1));continue}const i=l.definition.parameters[e];if(void 0===i){n(s.invalidOptions,`'${e}' names no declared parameter of '${o}' (nor 'fallback'/'noCache')`,a,o),c=!1;continue}if(i.required){n(s.invalidOptions,`'${e}' is a required parameter of '${o}' — operatorDefaults may only target optional parameters`,a,o),c=!1;continue}const u=J(r,i.type);if(u.ok){if(void 0!==i.constraints){const t=B(r,i.constraints);t.ok||(n(s.typeCheck,`the default for '${o}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,o),c=!1)}}else n(s.typeCheck,`the default for '${o}.${e}' does not satisfy its declared type: expected ${u.expected}, got ${u.actual}`,a,o),c=!1}c&&(l.hostDefaults=Object.freeze({...i}))}else n(s.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},Er=(e,t)=>{const r=e.operators.get(t);if(void 0!==r)return r;const a=e.aliases.get(t);return void 0!==a?e.operators.get(a):void 0},qr="fig-tree:scope-settled",Mr="fig-tree:request-expired",Fr="fig-tree:evaluation-timeout";class Rr{parent;controller;upstream;forward;settled=!1;verified=-1;clock;constructor(e){this.parent=e,this.clock=void 0===e?{epoch:0}:e.clock}get aborted(){return void 0!==this.controller?this.controller.signal.aborted:!!this.settled||this.verified!==this.clock.epoch&&(!(void 0===this.parent||!this.parent.aborted)||(this.verified=this.clock.epoch,!1))}get reason(){return void 0!==this.controller?this.controller.signal.reason:this.settled?qr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(qr);else if(void 0!==this.parent){const t=this.parent.signal;t.aborted?e.abort(t.reason):(this.upstream=t,this.forward=()=>e.abort(t.reason),t.addEventListener("abort",this.forward,{once:!0}))}}return this.controller.signal}settle(){this.settled||(this.settled=!0,this.clock.epoch+=1,void 0!==this.controller&&(void 0!==this.upstream&&void 0!==this.forward&&this.upstream.removeEventListener("abort",this.forward),this.controller.abort(qr)))}}const Ir=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:C}),Vr=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(qr)}})():(e=>{const t=new AbortController;e.aborted&&t.abort(e.reason);const r=()=>t.abort(e.reason);return e.addEventListener("abort",r,{once:!0}),{signal:t.signal,abort:e=>t.abort(e),settle:()=>{e.removeEventListener("abort",r),t.abort(qr)}}})(e),{signal:n}=a;let o;const s=new Promise((e,t)=>{o=t});s.catch(C);const i=()=>o(n.reason);n.aborted?i():n.addEventListener("abort",i,{once:!0});const l=void 0===t?void 0:setTimeout(()=>a.abort(r),Math.min(t,2147483647));return{signal:n,expiry:s,settle:()=>{void 0!==l&&clearTimeout(l),n.removeEventListener("abort",i),a.settle()}}},Lr=(e,t)=>Vr(e,t,Mr),Wr=(e,t)=>(r,a)=>{const n=(o=[e.operator,e.fingerprint,r],vr(o,[]));var o;return void 0===n?a():(async(e,t,r,a)=>{const n=e.generation,o=await e.lookup(t);if(a?.({type:"cache",hit:o.hit}),o.hit)return o.value;const s=await r();return await e.write(t,s,n),s})(t,n,a,e.note)},Jr=/*#__PURE__*/Object.freeze({}),Br=(e,t)=>!0!==t||!0===e.noCache?e:{...e,noCache:t};class Ur{options;cache;trace;#e;constructor(e,t,r,a){this.options=t,this.cache=r,this.trace=a,this.#e=e}get signal(){return this.#e.signal}}const Kr={memo:(e,t)=>t()},Gr={note:C},_r=Symbol("fig-tree:internal-error"),Hr=e=>na(`[fig-tree internal] ${e}`,_r),Qr=e=>sa(e,_r),Xr=Symbol("fig-tree:cancelled"),Yr=()=>na("[fig-tree] evaluation cancelled",Xr),Zr=e=>sa(e,Xr),ea=(e,t,r)=>e.rootScope.aborted?ta(e.rootScope.reason,t,r):e.abortScope.aborted?Yr():void 0,ta=(e,t,r)=>e===qr?Yr():ra(e,je(t),{operator:r}),ra=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===Fr,i=void 0===n?"":`${n}ms `;return new A({code:o?s.timeout:s.aborted,message:o?`evaluation exceeded its ${i}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},aa=e=>D(e)&&(e.code===s.aborted||e.code===s.timeout),na=(e,t)=>{const r=new Error(e);return oa(r,t),r},oa=(e,t)=>{e[t]=!0},sa=(e,t)=>e instanceof Error&&!0===e[t],ia=()=>performance.now(),la=e=>{const t=new Map,r=new WeakMap,a=new WeakSet;let n;const o=(e,r,n)=>{const o=t.get(e);if(void 0===o)return;t.delete(e),a.has(e)||("fallback"!==e.status&&(e.status=r),void 0!==n.error&&void 0===e.error&&(e.error=n.error),"failed"!==r&&"cancelled"!==r&&(e.value=n.value),void 0!==n.elapsed&&(e.elapsed=n.elapsed));const s=[...o.children,...ca(o)];s.length>0&&(e.children=s.sort((e,t)=>e.order-t.order||e.index-t.index).map(e=>e.entry))},s=(e,t)=>{(e.events??=[]).push(t)},i=(e,a,o,s)=>{const i=va(e),l=ya(e),c={path:je(e.path),kind:ma(e),status:"value",...void 0!==o?{source:o}:{},...void 0!==i?{operator:i}:{},...void 0!==l?{ref:l}:{},...void 0!==s?.var?{var:s.var}:{}};return t.set(c,{node:e,children:[],seen:new Set,started:ia()}),r.set(e,c),((e,r,a)=>{if(void 0===e)return void(n=r.entry);const o=t.get(e);void 0!==o&&(o.children.push(r),o.seen.add(a))})(a,{entry:c,order:e.order,index:s?.index??0},e),c};return{enter:(e,t,r,a)=>i(e,t,void 0!==r?{fragment:r.fragment}:void 0,a),settle:o,markFallback:(e,t)=>{e.status="fallback",e.error=t},note:s,markShielded:(e,n,l)=>{const c=r.get(e),u=void 0===c?void 0:t.get(c);if(void 0===c||void 0===u)return;a.add(c),c.status="fallback",c.error=n,c.value=l,c.elapsed=ia()-u.started,s(c,{type:"shielded-fallback"});const d=ha(e);void 0!==d&&o(i(d,c,c.source,void 0),"value",{value:l})},finish:()=>{for(const e of[...t.keys()].reverse())o(e,"cancelled",{});return void 0!==n&&e.length>0&&(n.warnings=e),n}}},ca=e=>ua(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:je(e.path),kind:ma(e),status:"skipped"},order:e.order,index:0})),ua=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(da),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...pa(e.parameters),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{}),...void 0!==e.entry?[e.entry.body]:[]];case"skeleton":return[...e.holes.map(e=>e.node),...Object.values(e.vars??{})];case"elements":return e.nodes;case"entries":return Object.values(e.entries);default:return[]}},da=e=>"elements"===e.kind||"entries"===e.kind?ua(e):[e],pa=e=>void 0===e?[]:fa(e)?[e]:Object.values(e),fa=e=>"string"==typeof e.kind,ma=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},ha=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.fallback:void 0,va=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,ya=e=>"reference"===e.kind?e.raw:void 0,ga=(e,t)=>{if(void 0===t)return e;const r={parent:e.scope,vars:new Map},a={...e,scope:r};for(const[e,n]of Object.entries(t))r.vars.set(e,S(()=>on(n,a,{var:e})));return a},ba=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await ka(e,t,a):wa(e,t,a),frame:n};delete o.scope,delete o.bindings;const s=await on(t.body,o);return void 0===s?null:s},wa=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,s]of Object.entries(t.parameters)){const t=a[o],i=S(async()=>{if(void 0===t)return $a(e,o,s,r);let a;try{a=await on(t,r)}catch(e){throw Aa(e,r.frame)}return xa(e,o,s,a,t.path,r)});n.set(o,()=>{const e=i();return e.catch(C),e})}return n},ka=async(t,r,a)=>{const n=t.parameters;let o;try{o=await on(n,a)}catch(e){throw Aa(e,a.frame)}if(!e(o))throw Aa(ja(t,s.typeCheck,`'parameters' must evaluate to an object, received ${Oa(o)}`,n.path),a.frame);const i=new Map;for(const[e,s]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?xa(t,e,s,o[e],n.path,a):$a(t,e,s,a,n.path);i.set(e,()=>Promise.resolve(r))}return i},$a=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw Aa(ja(e,s.missingRequired,`requires '${t}'`,n),a.frame)},xa=(e,t,r,a,n,o)=>{const i=void 0===a?null:a;if(null===i&&!r.required&&!V(r.type))return r.default??null;const l=J(i,r.type);if(!l.ok)throw Aa(ja(e,s.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=B(i,r.constraints);if(!a.ok)throw Aa(ja(e,s.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return i},ja=(e,t,r,a)=>new A({code:t,message:`fragment '${e.name}' – ${r}`,path:je(a)}),Oa=e=>null===e?"null":Array.isArray(e)?"array":typeof e,Pa=Symbol("fig-tree:anchored"),Aa=(e,t)=>!D(e)||sa(e,Pa)?e:(oa(e,Pa),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=je(t.callPath)),e);class Ca extends Error{code;errorData;constructor(e,t={}){super(e),this.name="OperatorFailure",void 0!==t.code&&(this.code=t.code),void 0!==t.errorData&&(this.errorData=t.errorData)}}const Da=e=>e instanceof Ca,Sa=(e,t,r)=>za(Array.from({length:e},(e,a)=>Na(a,()=>t(a),r)),e),Na=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},za=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[fr]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},Ta=e=>({[fr]:!0,evaluate:S(e)}),Ea=e=>({[fr]:!0,evaluate:()=>Promise.resolve(e)}),qa=(e,t,r,a,n)=>Ta(async()=>Ma(await on(e,n),t,r,a)),Ma=(e,t,r,a)=>{const n=J(e,a.type);if(!n.ok)throw La(t,r,n);if(null!==e&&void 0!==a.constraints){const n=H(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw La(t,r,n)}return a.truthiness?Ua(e,a.type):e},Fa=(e,t,r,a,n,o)=>{const s=Array.isArray(t)?t:[],i=Ae(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>Ma(await on(e,((e,t,r,a)=>({...e,bindings:{parent:e.bindings,as:t,element:r,index:a}}))(o,i,s[t],t),{index:t}),r,a,n))();return u.catch(C),l.set(t,u),u};return{[fr]:!0,evaluate:c,settle:()=>Sa(s.length,c,e=>e)}},Ra=(e,t)=>t.truthiness?se(e):e,Ia=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>Ta(async()=>Ra(await on(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>Sa(e.length,r=>on(e[r],t,{index:r}),r))(e.nodes,r,e=>Ra(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=ga(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=Ta(async()=>Ra(await on(o,a),t));return n}},Va=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>Ea(Ra(e,t)));case"race":return((e,t)=>Sa(e.length,t=>Promise.resolve(e[t]),t))(e,e=>Ra(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=Ea(Ra(n,t));return r}case"lazy":return Ea(e);default:return e}},La=(e,t,r)=>new A({code:s.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:je(e.path),operator:e.name}),Wa=(e,t,r)=>{if("string"==typeof t.nullPolicy)return t.nullPolicy;const a=t.nullPolicy,n=e.entry.definition.parameters[a.selector],o=r[a.selector],s=J(o,n.type);if(!s.ok)throw La(e,a.selector,s);const i=a.table.find(e=>e.value===o);if(void 0===i)throw Hr(`no null-policy row for ${e.name}.${a.selector}`);return i.policy},Ja=async(t,r,a)=>{if(void 0!==r.elementNullPolicy){if(Array.isArray(t)&&t.includes(null)){const e=await a();return t.map(t=>null===t?e:t)}if(e(t)&&Object.values(t).includes(null)){const e=await a(),r={};for(const[a,n]of Object.entries(t))r[a]=null===n?e:n;return r}return t}return null===t?a():t},Ba=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),Ua=(t,r)=>{if((e=>!("object"==typeof e&&!Array.isArray(e))&&(Array.isArray(e)?e:[e]).every(e=>"array"===e||"object"===e))(r)){if(Array.isArray(t))return t.map(se);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=se(a);return e}}return se(t)},Ka=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,hostDefaults:a}=e.entry,{entries:n,whole:o,perElement:s}=r.resolution,i=[],l=[],c={};let u;const d={};for(const[r,o]of n){const n=e.params[r];switch(o.evaluation){case"eager":void 0!==n&&(i.push(r),l.push(on(n,t)));break;case"structural":"constant"===n?.kind&&(c[r]=n.value);break;case"lazy":if(void 0!==o.replacesNullAt){const e=void 0!==n?S(()=>on(n,t)):void 0!==a&&Object.hasOwn(a,r)?S(()=>a[r]):void 0;if(void 0!==e)for(const t of o.replacesNullAt)(u??={})[t]=e;break}void 0!==n&&(d[r]=qa(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=Ia(n,o,t);if(void 0!==e){d[r]=e;break}i.push(r),l.push(on(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[i[0]]=N(e)?await e:e}else{const e=await Promise.all(l);i.forEach((t,r)=>{c[t]=e[r]})}for(const[e,r]of o){if(Object.hasOwn(d,e))continue;const n=c[e];(void 0===n||null===n&&!r.required&&!V(r.type))&&(void 0!==a&&Object.hasOwn(a,e)?c[e]=a[e]:"default"in r?c[e]=r.default===X?t.data:r.default:delete c[e])}for(const[t,r]of o){if(Object.hasOwn(d,t))continue;let a=c[t];if(void 0===a)continue;const n=u?.[t];void 0!==n&&(a=await Ja(a,r,n));const o="eager"!==r.evaluation&&"structural"!==r.evaluation;if(null===a&&V(r.type)&&!o&&"propagate"===Wa(e,r,c))return{params:d,propagate:!0};if("propagate"===r.elementNullPolicy&&Ba(a))return{params:d,propagate:!0};a=Ma(a,e,t,r),d[t]=Va(a,r)}for(const[r,a]of s){if(void 0===a.over)throw Hr(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=Fa(n,d[a.over],e,r,a,t))}return{params:d,propagate:!1}})(e,t);if(a)return null;const{definition:n}=e.entry,o=!0!==t.noCache&&Sr(e.entry),s=_a(n,r),i=void 0===s?void 0:Lr(t.abortScope.signal,s),l=void 0===i?t:{...t,abortScope:Ir(i.signal,t.abortScope)},c=(e=>{const{trace:t,traceParent:r}=e;if(void 0!==t&&void 0!==r)return e=>{t.note(r,e)}})(t),u=((e,t,r,a)=>new Ur(e.abortScope,e.options,r?{memo:Wr({operator:t.name,fingerprint:t.fingerprint,note:a},e.cache)}:Kr,void 0===a?Gr:{note:a}))(l,n,o,c);try{return await Ga(e,t,r,u,i)}catch(r){throw Ha(r,e,t,i,s)}finally{i?.settle()}},Ga=async(e,t,r,a,n)=>{const o=ea(t,e.path,e.name);if(void 0!==o)throw o;const s=Promise.resolve(e.entry.definition.evaluate(r,a));return void 0===n?Xa(await s,e):(s.catch(C),Xa(await Promise.race([s,n.expiry]),e))},_a=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},Ha=(e,t,r,a,n)=>{if(Qr(e)||Zr(e))return e;const o=ea(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===Mr?new Ca(`request exceeded its ${String(n)}ms timeout`,{code:s.requestTimeout}):e},Qa=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>on(r,t);const a=e.entry.hostDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Xa=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new A({code:s.nonFiniteResult,message:`${t.name} – produced a non-finite number (${String(e)})`,path:je(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[fr])throw new A({code:s.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:je(t.path),operator:t.name});var r;return e},Ya=(e,t)=>{if(D(e))return e;if(Da(e))return new A({code:e.code??s.operatorFailure,message:`${t.name} – ${e.message}`,path:je(t.path),operator:t.name,...void 0!==e.errorData?{errorData:e.errorData}:{}});const r=e instanceof Error?e.message:String(e);return new A({code:s.operatorFailure,message:`${t.name} – ${r}`,path:je(t.path),operator:t.name})},Za=(e,t)=>0===e.segments.length?t.data:an(t.data,e.segments,e,t,"is absent from the evaluation data"),en=async(e,t)=>{const[r,...a]=e.segments,n="string"==typeof r?((e,t)=>{for(let r=e;void 0!==r;r=r.parent){const e=r.vars.get(t);if(void 0!==e)return e}})(t.scope,r):void 0;if("string"!=typeof r||void 0===n)throw Hr(`'${e.raw}': no var named '${String(r)}' is in scope — the static gate should have refused it`);const o=await n();return 0===a.length?nn(o):an(o,a,e,t,`is absent from the value of '$vars.${r}'`)},tn=async(e,t)=>{const r=t.params;if(void 0===r)throw Hr(`'${e.raw}': $params outside a fragment body — the static gate should have refused it`);const[a,...n]=e.segments;if(void 0===a){const e={};return await Promise.all([...r].map(async([t,r])=>{e[t]=nn(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Hr(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const s=await o();return 0===n.length?nn(s):an(s,n,e,t,`is absent from the value of '$params.${String(a)}'`)},rn=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Ce(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Hr(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?nn(a.element):an(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},an=(e,t,r,a,n)=>{const o=x(e,t);if(o.found)return nn(o.value);if(!a.strictDataPaths)return null;throw new A({code:s.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:je(r.path)})},nn=e=>void 0===e?null:e,on=(e,t,r)=>void 0!==t.trace?sn(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(ea(t,e.path)):ln(e,t),sn=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=ia();try{if(t.abortScope.aborted)throw ea(t,e.path);const a=await ln(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:ia()-o}),a}catch(e){throw r.settle(n,Zr(e)?"cancelled":"failed",{...D(e)?{error:e}:{},elapsed:ia()-o}),e}},ln=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Za(e,t);case"vars":return en(e,t);case"params":return tn(e,t);case"element":case"index":return rn(e,t)}})(e,t);case"skeleton":return cn(e,t);case"operator":return(async(e,t)=>{const r=ga(Br(t,e.noCache),e.vars),a=e.entry.definition.deliversLazily?new Rr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await Ka(e,n)}finally{a?.settle()}}catch(a){if(Qr(a)||Zr(a)||aa(a))throw a;const n=Ya(a,e),o=Qa(e,r);if(void 0===o)throw n;try{const e=await o();return void 0!==t.trace&&void 0!==t.traceParent&&t.trace.markFallback(t.traceParent,n),e}catch(t){if(Qr(t)||Zr(t)||aa(t))throw t;const r=Ya(t,e);throw void 0===r.cause&&(r.cause=n),r}}})(e,t);case"fragmentCall":return(async(e,t)=>{const{entry:r}=e;if(void 0===r)throw Hr(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=ga(Br(t,e.noCache),e.vars),n=new Rr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},s={...a,abortScope:n};try{try{return await ba(e,r,s,a,o)}finally{n.settle()}}catch(r){if(Qr(r)||Zr(r)||aa(r))throw r;const n=Aa(r,o),{fallback:s}=e;if(void 0===s)throw n;try{const e=await on(s,a);return void 0!==t.trace&&void 0!==t.traceParent&&D(n)&&t.trace.markFallback(t.traceParent,n),e}catch(e){if(Qr(e)||Zr(e)||aa(e))throw e;const r=Aa(e,t.frame);throw D(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Hr(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Hr("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},cn=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=ga(a,e.vars),o=e.holes.map(({node:e})=>void 0===r?on(e,n):"skeleton"===e.kind?on(e,{...n,rootBoundary:r}):r(()=>on(e,n),e)),s=o.some(N)?await Promise.all(o):o;return Se(e.skeleton,e.holes,s)},un=async(e,t,r)=>{const{timeout:a,signal:n}=t,o=e.holes.length>0,s=void 0!==a||void 0!==n?Vr(n,a,Fr):void 0,i=void 0!==s?((e,t)=>{const r={epoch:0};return e.addEventListener("abort",()=>{r.epoch+=1},{once:!0}),{get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:r,settle:t}})(s.signal,s.settle):new Rr(void 0),l=void 0!==s&&void 0!==a&&e.timeoutShielded&&o,c=!0===t.trace?la(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,u=((e,t,r,a)=>({options:e,data:e.data??Jr,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,...void 0!==a?{trace:a}:{}}))(t,r,i,c),d=l?pn(e,s.expiry,a,c):void 0,p=void 0!==d&&"skeleton"!==e.root.kind,f=void 0===d||p?u:{...u,rootBoundary:d};try{if(i.aborted)throw ra(i.reason,[]);const t=()=>p&&void 0!==d?d(()=>on(e.root,f),e.root):on(e.root,f),r=await(l||void 0===s?t():dn(t,s,a));return void 0!==c?{result:r,trace:c.finish()}:{result:r}}catch(e){throw void 0!==c&&D(e)&&void 0===e.trace&&(e.trace=c.finish()),e}finally{i.settle()}},dn=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw ra(e,[],{ms:r})})]),pn=(e,t,r,a)=>{const n=new Map(e.holes.map(e=>[e.node,e]));return(e,o)=>{const s=n.get(o);if(void 0===s)throw Hr(`the hole boundary was handed the node at ${JSON.stringify(je(o.path))}, which is not one of the artifact's holes`);let i=!1;const l=Promise.resolve(e()).then(e=>(i=!0,e));return Promise.race([l,t.catch(e=>{if(e!==Fr)throw ra(e,[]);if(i)return;const t=mn(s);return a?.markShielded(s.node,fn(s,e,r),t),t})])}},fn=(e,t,r)=>{const{node:a}=e,n="operator"===a.kind?a.name:void 0;return ra(t,je(a.path),{operator:n,ms:r})},mn=e=>{if(void 0===e.timeoutFallback)throw Hr("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},hn={hit:!1},vn=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw gn("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!yn(t))throw gn("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw gn("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw gn("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},yn=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),gn=e=>new A({code:s.invalidOptions,message:e,path:[]});class bn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new dr(e.maxSize),this.store=this.own):this.store=e.store,this.maxTime=e.maxTime}get generation(){return this.current}async lookup(e){let t;try{t=await this.store.get(e)}catch{return hn}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||wn(t)?(this.drop(e),hn):{hit:!0,value:t.value}:hn;var r}async write(e,t,r){if(r!==this.current)return;const a={fig:"ft3",value:t,generation:r,...Number.isFinite(this.maxTime)?{expiresAt:Date.now()+1e3*this.maxTime}:{}};try{await this.store.set(e,a)}catch{}}clear(){this.current+=1;try{Promise.resolve(this.store.clear()).catch(C)}catch{}}configure(e){void 0!==e.store&&e.store!==this.store&&(this.store=e.store,this.own=void 0),this.maxTime=e.maxTime,this.own?.resize(e.maxSize)}drop(e){try{Promise.resolve(this.store.delete(e)).catch(C)}catch{}}}const wn=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),kn=e=>e===z?0:"number"==typeof e?1:2,$n=e=>({data:{paths:[...e.dataPaths].sort(([,e],[,t])=>((e,t)=>{const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a],n=t[a];if(r===n)continue;const o=kn(r)-kn(n);return 0!==o?o:"number"==typeof r&&"number"==typeof n?r-n:r<n?-1:1}return e.length-t.length})(e,t)).map(([e])=>e),dynamic:e.dynamic},operators:[...e.operators],fragments:[...e.fragments]}),xn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e)){const e={...n};void 0!==t&&Object.hasOwn(t,a)&&(e.hostDefault=t[a]),r[a]=e}return r},jn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(Pn(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:s.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},On=(e,t)=>e.hasErrors||void 0!==t.maxDepth||void 0!==t.maxNodes?[...jn(e,t),...e.issues.map(e=>e.issue)]:[],Pn=(e,t)=>({severity:"error",code:s.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),An=(e,t,r)=>{const a=[...jn(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...Cn(e.dataReads,t.data)),a},Cn=(e,t)=>{const r=new Map,a=new Map,n=[],o=(e,o,i,l)=>{let c=r.get(e);if(void 0===c&&(c=x(t,o).found,r.set(e,c)),c)return;let u=a.get(i.path);if(void 0===u&&a.set(i.path,u=new Set),u.has(e))return;u.add(e);const d=void 0===l?"":` (read by fragment '${l}')`;n.push({severity:"warning",code:s.missingDataPath,message:`'${T(o)}' is absent from the supplied sample data${d}`,path:je(i.path)})};for(const t of e)if("path"===t.kind)o(t.key,t.segments,t,void 0);else for(const[e,r]of t.fragment.dependencies.dataPaths)o(e,r,t,t.fragment.name);return n},Dn="...",Sn=/*#__PURE__*/new Set(["propagate","value"]),Nn=e=>e,zn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=Tn(e.parameters,t,(t,r,a)=>{throw new A({code:t,message:r,path:a,operator:e.name})});return En(e,r)},Tn=(e,r,a)=>{const n=Object.entries(r).filter(([,e])=>t(e)).map(([e])=>e),o=new Map;for(const[i,l]of Object.entries(e)){if("function"!=typeof l.nullPolicy)continue;const e=["parameters",i,"nullPolicy"];if(1!==n.length){a(s.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${n.length}`,e,i);continue}const c=n[0],u=r[c];if(!t(u))continue;const d=[];let p=!0;for(const t of u.literal){let r;try{r=l.nullPolicy(t)}catch(r){a(s.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(r)}`,e,i),p=!1;break}if("string"!=typeof r||!Sn.has(r)){a(s.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(r)} for ${JSON.stringify(t)}`,e,i),p=!1;break}d.push({value:t,policy:r})}p&&o.set(i,{selector:c,table:d})}return o},En=(e,t)=>{const r={};for(const[a,n]of Object.entries(e.parameters)){const e=t.get(a),o="string"==typeof n.nullPolicy?n.nullPolicy:void 0,s=n.type??"any",i=!0===n.truthiness&&V(s)?"value":"propagate",l={type:Mn(s),required:n.required??!("default"in n),evaluation:n.evaluation??"eager",truthiness:n.truthiness??!1,nullPolicy:e??o??i};"default"in n&&(l.default=n.default),void 0!==n.description&&(l.description=n.description),void 0!==n.metadata&&(l.metadata=n.metadata),void 0!==n.elementNullPolicy&&(l.elementNullPolicy=n.elementNullPolicy),void 0!==n.constraints&&(l.constraints=Fn(n.constraints)),void 0!==n.over&&(l.over=n.over),void 0!==n.replacesNullAt&&(l.replacesNullAt=[...n.replacesNullAt]),r[a]=l}const a=e.positionalParams?.at(-1),n=a?.startsWith(Dn)?a.slice(3):null,o={[Y]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:Rn(r),restParam:n,deliversLazily:Object.values(r).some(e=>"eager"!==e.evaluation&&"structural"!==e.evaluation),timeoutParam:e.timeoutParam??null,cache:!0===e.cache,fingerprint:"",evaluate:e.evaluate,returns:void 0!==e.returns?Mn(e.returns):"any"};return void 0!==e.alias&&(o.alias=e.alias),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.positionalParams&&(o.positionalParams=[...e.positionalParams]),void 0!==e.validate&&(o.validate=e.validate),void 0!==e.analysis&&(o.analysis=Fn(e.analysis)),o.fingerprint=qn(o),In(o)},qn=e=>E(JSON.stringify([e.name,e.parameters,e.positionalParams,e.restParam,e.returns,e.cache,e.timeoutParam,e.evaluate,e.validate],(e,t)=>"function"==typeof t||"symbol"==typeof t||t instanceof RegExp?String(t):t)),Mn=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],Fn=t=>{if(Array.isArray(t))return t.map(Fn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=Fn(a);return e}return t},Rn=e=>{const t=Object.entries(e);return{entries:t,whole:t.filter(([,e])=>void 0===e.replacesNullAt&&"perElement"!==e.evaluation),perElement:t.filter(([,e])=>"perElement"===e.evaluation)}},In=e=>{for(const t of Object.values(e.parameters))"string"!=typeof t.type&&Object.freeze(t.type),"object"==typeof t.type&&"literal"in t.type&&Object.freeze(t.type.literal),"object"==typeof t.nullPolicy&&(t.nullPolicy.table.forEach(e=>Object.freeze(e)),Object.freeze(t.nullPolicy.table),Object.freeze(t.nullPolicy)),void 0!==t.constraints&&Vn(t.constraints),void 0!==t.replacesNullAt&&Object.freeze(t.replacesNullAt),Object.freeze(t);Object.freeze(e.parameters);for(const t of Object.values(e.resolution))t.forEach(e=>Object.freeze(e)),Object.freeze(t);return Object.freeze(e.resolution),"string"!=typeof e.returns&&Object.freeze(e.returns),void 0!==e.positionalParams&&Object.freeze(e.positionalParams),Object.freeze(e)},Vn=t=>{Array.isArray(t)?(t.forEach(Vn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(Vn),Object.freeze(t))},Ln=e=>{if(Array.isArray(e))return e;try{return w(e)}catch(e){throw new Ca(e.message)}},Wn=(e,t)=>{if("string"!=typeof e)return[];try{return w(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},Jn=e=>Array.isArray(e.values)&&0===e.values.length?[{severity:"error",parameter:"values",message:"an empty values array has no result — supply at least one value"}]:[],Bn=e=>t=>{const r=t[e];return Array.isArray(r)&&0===r.length?[{severity:"warning",parameter:e,message:`an empty ${e} array is a dead expression — the result is always the identity`}]:[]},Un=/*#__PURE__*/Bn("values"),Kn=/*#__PURE__*/Bn("input"),Gn=/*#__PURE__*/Bn("entries"),_n=e=>Array.isArray(e.values)&&e.values.length<2?[{severity:"warning",parameter:"values",message:"fewer than two values is a dead comparison — the result never varies"}]:[],Hn=(e,t)=>new Ca(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:s.emptyAggregate}),Qn=async(e,t)=>{const r=[];for await(const a of e){if(a.ok&&a.value===t)return t;a.ok||r.push(a)}if(r.length>0)throw r.sort((e,t)=>e.index-t.index),Xn(r);return!t},Xn=e=>{const[t,...r]=e,a=r.map(e=>e.error).filter(D);return a.length>0&&D(t.error)&&void 0===t.error.related&&(t.error.related=a),t.error},Yn=async e=>{const t=new Array(e.length);let r=0;for await(const a of e){t[a.index]=a;for(let e=t[r];void 0!==e;e=t[r]){if(!e.ok)throw e.error;r+=1}}return t.map(e=>e?.value)},Zn=(e,t)=>{const r=e=>t&&"string"==typeof e?e.toLowerCase():e;if(e.length<2)return!0;const a=r(e[0]);return e.every(e=>ge(r(e),a))},eo={values:{type:"array",elementNullPolicy:"value",description:"The values compared; null is comparable (null equals null)"},caseInsensitive:{type:"boolean",default:!1,description:"Fold string operands to one case before comparing (shallow)"}},to={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:eo,positionalParams:["...values"],returns:"boolean",validate:_n,evaluate:({values:e,caseInsensitive:t})=>Zn(e,t)},ro={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:eo,positionalParams:["...values"],returns:"boolean",validate:_n,evaluate:({values:e,caseInsensitive:t})=>!Zn(e,t)},ao=(e,t,r,a)=>({name:e,alias:t,category:"comparison",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{length:2,homogeneous:["number","string"]},description:"Exactly two operands: both numbers, or both strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces a null operand before comparing"}},positionalParams:["...values"],returns:"boolean",evaluate:({values:e})=>{const[t,r]=e;return a(ie(t,r))}}),no=/*#__PURE__*/ao("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),oo=/*#__PURE__*/ao("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),so=/*#__PURE__*/ao("lessThan","<","Is the first value strictly less than the second?",e=>e<0),io=/*#__PURE__*/ao("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),lo={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},co=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,uo={name:"plus",alias:"+",category:"math",description:"Add numbers, concatenate strings or arrays, or shallow-merge objects — all operands must share one type",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string","array","object"]},description:"The operands; homogeneous: all numbers, strings, arrays or objects"},expect:{type:{literal:["number","string","array","object"]},required:!1,description:"Pin the mode: every operand must be this type, and an empty input yields its identity"},nullValueDefault:{type:["number","string","array","object"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null operand before the addition"}},positionalParams:["...values"],returns:["number","string","array","object"],validate:({values:e,expect:t})=>void 0!==t?Un({values:e}):Jn({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw Hn("the sum","pin the mode with 'expect' to get its identity");return lo[t]()}const r=t??co(e[0]),a=e.find(e=>co(e)!==r);if(void 0!==a)throw n=`all operands must be ${r}s — received ${F(a)}`,new Ca(n,{code:s.typeCheck});var n;switch(r){case"number":return e.reduce((e,t)=>e+t,0);case"string":return e.join("");case"array":return e.flat(1);case"object":return Object.assign({},...e)}}},po={name:"subtract",alias:"-",category:"math",description:"Subtract one number from another",parameters:{value:{type:["number","null"],description:"The main operand"},minus:{type:["number","null"],description:"The amount subtracted from value"}},positionalParams:["value","minus"],returns:"number",evaluate:({value:e,minus:t})=>e-t},fo={name:"divide",alias:"/",category:"math",description:"Divide one number by another — true division; zero divisors fail",parameters:{value:{type:["number","null"],description:"The main operand"},by:{type:["number","null"],description:"The divisor"}},positionalParams:["value","by"],returns:"number",evaluate:({value:e,by:t})=>e/t},mo={name:"modulo",category:"math",description:"The floored remainder: the result takes the sign of mod, so modulo(-7, 3) is 2",parameters:{value:{type:["number","null"],description:"The main operand"},mod:{type:["number","null"],description:"The modulus"}},positionalParams:["value","mod"],returns:"number",evaluate:({value:e,mod:t})=>(e%t+t)%t},ho={name:"multiply",alias:"*",category:"math",description:"Multiply numbers together — an empty input is 1, the empty product",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number"]},description:"The factors"},nullValueDefault:{type:"number",required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null factor before multiplying"}},positionalParams:["...values"],returns:"number",validate:Un,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},vo={name:"power",alias:"^",category:"math",description:"Raise a base to an exponent — overflow and complex results fail",parameters:{base:{type:["number","null"],description:"The number to raise"},exponent:{type:["number","null"],description:"The power to raise it to"}},positionalParams:["base","exponent"],returns:"number",evaluate:({base:e,exponent:t})=>e**t},yo={name:"round",category:"math",description:"Round to a number of decimal places — ties go half away from zero; negative decimals round to tens, hundreds, …",parameters:{value:{type:["number","null"],description:"The number to round"},decimals:{type:"integer",default:0,description:"Decimal places to keep; negative values round to powers of ten"}},positionalParams:["value","decimals"],returns:"number",evaluate:({value:e,decimals:t})=>((e,t=0)=>{if(!Number.isFinite(e))return e;const r=e<0?-1:1,a=Math.round(he(Math.abs(e),t));return r*he(a,-t)})(e,t)},go=(e,t,r,a,n="number")=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"],description:r}},positionalParams:["value"],returns:n,evaluate:({value:e})=>a(e)}),bo=/*#__PURE__*/go("floor","Round down toward negative infinity","The number to round down",Math.floor,"integer"),wo=/*#__PURE__*/go("ceil","Round up toward positive infinity","The number to round up",Math.ceil,"integer"),ko=/*#__PURE__*/go("abs","The absolute value","The number",Math.abs),$o=(e,t,r,a)=>({name:e,category:"math",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string"]},description:"The candidates: all numbers, or all strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null candidate before comparing"}},positionalParams:["...values"],returns:["number","string"],validate:Jn,evaluate:({values:e})=>{const r=e;if(0===r.length)throw Hn(t);return r.reduce((e,t)=>a(ie(t,e))?t:e)}}),xo=(e,t,r,a)=>({name:e,category:"string",description:t,parameters:{value:{type:["string","null"],description:r}},positionalParams:["value"],returns:"string",evaluate:({value:e})=>a(e)}),jo={name:"split",category:"string",description:"Divide a string on a delimiter into an array of pieces — empty pieces are kept; an empty delimiter splits into code points",parameters:{value:{type:["string","null"],description:"The string to divide"},delimiter:{type:"string",default:" ",description:'Split on each occurrence; "" splits into code points'},trim:{type:"boolean",default:!0,description:"Trim whitespace from each piece"}},positionalParams:["value","delimiter"],returns:"array",evaluate:({value:e,delimiter:t,trim:r})=>{const a=""===t?me(e):e.split(t);return r?a.map(ce):a}},Oo=e=>Array.isArray(e.values)&&e.values.some(ae)?[{severity:"error",parameter:"values",message:ne}]:[],Po={name:"join",category:"string",description:"Render array elements to text and concatenate them with a delimiter",parameters:{values:{type:"array",elementNullPolicy:"value",description:'Elements of any type, rendered by the stringification table; a null renders "" and still occupies its slot'},delimiter:{type:"string",default:" ",description:"Placed between each adjacent pair — shares its contract with split"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:'Rendered in place of a null element, instead of ""'}},positionalParams:["...values"],returns:"string",validate:e=>[...Un(e),...Oo(e)],evaluate:({values:e,delimiter:t},r)=>e.map((e,t)=>{const a=`[${t}]`;return null===e?r.trace.note({type:"render",token:a,rendered:"empty"}):ae(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),re(e)}).join(t)},Ao=e=>{const t=new Set,r=[];for(const a of e)if("imsu".includes(a)){if(t.has(a))return`duplicate regex flag '${a}'`;t.add(a)}else r.includes(a)||r.push(a);if(0===r.length)return;const a=r.includes("g")||r.includes("y")?" — all matches is mode: 'match'":"";return`unknown regex flag${1===r.length?"":"s"}: ${r.join(", ")}${a}`},Co={type:"array",description:"The collection iterated over; a null input is a type error"},Do={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},So={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},No={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},zo={name:"get",category:"data",description:"Read a path out of the evaluation data, or out of a supplied object — the dynamic face of a $data reference",parameters:{path:{type:["string","array","null"],description:"Dot and bracket segments, quoted keys and the [*] projection — or an array of segments, taken verbatim"},from:{type:"any",nullPolicy:"value",default:X,description:"The source the path reads: a value, or a bare namespace ($data, $vars, $params, $element) whose var or parameter name opens the path — replace, never merge; a null source misses every path"},default:{type:"any",required:!1,evaluation:"lazy",description:"The answer when the path is missing — a stored null passes through unchanged (firstOf replaces one); supplying it also opts out of strictDataPaths"}},positionalParams:q,returns:"any",validate:({path:e})=>Wn(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=x(t,Ln(e));if(n.found)return void 0===n.value?null:n.value;if(void 0!==r)return r.evaluate();if(a.options.strictDataPaths)throw new Ca(`'${To(e)}' is missing (strictDataPaths)`,{code:s.missingDataPath});return null}},To=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),Eo={name:"buildObject",category:"data",description:"Assemble an object from computed key/value entries — for keys known only at runtime",parameters:{entries:{type:"array",constraints:{elementShape:{key:{type:["string","number","boolean"]},value:{type:"any"}}},description:'Objects with a "key" and a "value"; a null value keeps its key'}},positionalParams:["...entries"],returns:"object",validate:e=>[...Gn(e),...qo(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=re(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},qo=e=>{const t=e.entries;if(!Array.isArray(t))return[];const r=new Set,a=new Set,n=[];for(const e of t){const t=e?.key;if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)continue;const o=re(t);r.has(o)&&!a.has(o)&&(a.add(o),n.push({severity:"warning",parameter:"entries",message:`duplicate key '${o}' — the last entry wins and the earlier one is dead`})),r.add(o)}return n},Mo=(e,t)=>new Ca(`cannot convert ${F(e)} to ${t}`),Fo=/*#__PURE__*/[{name:"and",category:"logic",description:"True when every value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Un,evaluate:({values:e})=>Qn(e,!1)},{name:"or",category:"logic",description:"True when any value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Un,evaluate:({values:e})=>Qn(e,!0)},{name:"not",alias:"!",category:"logic",description:"Negate the truthiness of a value",parameters:{value:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy, so not(null) is true"}},positionalParams:["value"],returns:"boolean",evaluate:({value:e})=>!e},{name:"if",alias:"?",category:"logic",description:"Choose between two branches — only the chosen branch evaluates",parameters:{condition:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy"},then:{type:"any",evaluation:"lazy",description:"The value when the condition holds"},else:{type:"any",evaluation:"lazy",default:null,description:"The value when it does not; omitted means null"}},positionalParams:["condition","then","else"],evaluate:({condition:e,then:t,else:r})=>e?t.evaluate():r.evaluate()},{name:"match",category:"logic",description:"Dispatch on a value — only the matching branch evaluates",parameters:{value:{type:["string","number","boolean","null"],nullPolicy:"value",description:"Matched against branch keys by its canonical string form"},branches:{type:"object",evaluation:"lazyEntries",description:"A literal map of branches, or an expression computing one"},default:{type:"any",required:!1,evaluation:"lazy",description:"The branch taken when none matches; absent means failure"}},positionalParams:["value","branches","default"],evaluate:({value:e,branches:t,default:r})=>{const a=null===e?null:re(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new Ca(`no branch matches ${null===a?"null":`'${a}'`}, and no default was supplied`)}},{name:"firstOf",category:"logic",description:"The first candidate that is not null (SQL COALESCE) — later candidates never evaluate",parameters:{values:{type:"array",evaluation:"lazyElements",description:"Candidates, tried in order; only null is skipped"}},positionalParams:["...values"],validate:Un,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},to,ro,no,oo,so,io,uo,po,ho,fo,mo,vo,yo,bo,wo,ko,/*#__PURE__*/$o("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/$o("max","the maximum","The largest of the values — numbers numerically, strings in codepoint order",e=>e>0),{name:"buildString",category:"string",description:"Render a template, filling its tokens — the result is always a string",parameters:{template:{type:["string","null"],description:"The text, with %N or {{name}} tokens; in a literal template, {{$data.x}} is that reference"},substitutions:{type:["array","object"],default:[],elementNullPolicy:"value",description:"An array pairs with %N tokens, an object with {{name}} tokens; the mode dispatches on which arrives"},trim:{type:"boolean",default:!1,description:"Trim whitespace from each rendered value, never from the template text"},closeGaps:{type:"boolean",default:!1,description:"A value that renders empty also takes one run of adjacent template whitespace"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["substitutions"],description:'Rendered in place of a null value, instead of ""'}},positionalParams:["template","...substitutions"],returns:"string",evaluate:({template:e,substitutions:t,trim:r,closeGaps:a},n)=>{const o=Array.isArray(t)?t:void 0,s=void 0===o?t:void 0,i=[];for(const t of we(e)){if("text"===t.kind){i.push({text:t.text,site:!1});continue}if(!("positional"===t.kind?void 0!==o&&t.index>=1&&t.index<=o.length:void 0!==s&&Object.hasOwn(s,t.body))){n.trace.note({type:"render",token:t.raw,rendered:"literal"}),i.push({text:t.raw,site:!1});continue}const e="positional"===t.kind?o[t.index-1]:s[t.body],a=re(e);ae(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?ce(a):a;""===l&&n.trace.note({type:"render",token:t.raw,rendered:"empty"}),i.push({text:l,site:!0,token:t.raw})}if(a)for(const e of(e=>{const t=[];for(let r=0;r<e.length;r++){const a=e[r];if(!a.site||""!==a.text)continue;const n=e[r-1];if(void 0!==n&&!n.site){const e=pe(n.text);if(e!==n.text){n.text=e,t.push(a.token);continue}}const o=e[r+1];if(void 0!==o&&!o.site){const e=fe(o.text);e!==o.text&&t.push(a.token),o.text=e}}return t})(i))n.trace.note({type:"render",token:e,rendered:"gap-closed"});return i.map(e=>e.text).join("")}},jo,Po,/*#__PURE__*/xo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/xo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/xo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",ce),{name:"regex",category:"string",description:"Test, extract or match a string against a regular expression",parameters:{value:{type:["string","null"],description:"The subject string"},pattern:{type:["string","null"],description:"The regular expression source"},flags:{type:"string",default:"",description:"The admitted subset: i, m, s, u"},mode:{type:{literal:["test","extract","match"]},default:"test",description:"test gives a boolean, extract the first matching substring, match every one of them"},noMatchDefault:{type:["string","null"],required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The extract answer when nothing matches — a matched empty string still passes through"}},positionalParams:["value","pattern"],returns:["boolean","string","array","null"],validate:({pattern:e,flags:t})=>{const r=[],a="string"==typeof t?Ao(t):void 0;if(void 0!==a&&r.push({severity:"error",parameter:"flags",message:a}),"string"==typeof e)try{new RegExp(e,"string"==typeof t&&void 0===a?t:"")}catch(e){r.push({severity:"error",parameter:"pattern",message:`pattern does not compile: ${e.message}`})}return r},evaluate:({value:e,pattern:t,flags:r,mode:a,noMatchDefault:n})=>{const o=Ao(r);if(void 0!==o)throw new Ca(o);const s=e=>{try{return new RegExp(t,r+e)}catch(e){throw new Ca(`pattern does not compile: ${e.message}`)}};switch(a){case"test":return s("").test(e);case"extract":{const t=s("").exec(e);return null===t?n.evaluate():t[0]}case"match":return[...e.matchAll(s("g"))].map(e=>e[0])}}},{name:"length",category:"array",description:"An array's element count, or a string's Unicode code-point count",parameters:{value:{type:["string","array","null"],description:"The array or string measured"}},positionalParams:["...value"],returns:"integer",evaluate:({value:e})=>"string"==typeof e?me(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:Co,as:Do,nullInputDefault:So,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Kn,evaluate:({each:e})=>Yn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:Co,as:Do,nullInputDefault:So,each:No},positionalParams:["input","each"],returns:"array",validate:Kn,evaluate:async({input:e,each:t})=>{const r=await Yn(t.settle());return e.filter((e,t)=>r[t])}},{name:"find",category:"array",description:"The first element of an array whose predicate is truthy",parameters:{input:Co,as:Do,nullInputDefault:So,each:No,noMatchDefault:{type:"any",required:!1,default:null,evaluation:"lazy",description:"The answer when nothing matches; a found null passes through unchanged"}},positionalParams:["input","each"],validate:Kn,evaluate:async({input:e,each:t,noMatchDefault:r})=>{const a=new Array(e.length);let n=0;for await(const r of t.settle()){a[r.index]=r;for(let t=a[n];void 0!==t;t=a[n]){if(!t.ok)throw t.error;if(!0===t.value)return e[n];n+=1}}return r.evaluate()}},{name:"some",category:"array",description:"True when any element satisfies the predicate",parameters:{input:Co,as:Do,nullInputDefault:So,each:No},positionalParams:["input","each"],returns:"boolean",validate:Kn,evaluate:({each:e})=>Qn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:Co,as:Do,nullInputDefault:So,each:No},positionalParams:["input","each"],returns:"boolean",validate:Kn,evaluate:({each:e})=>Qn(e.settle(),!1)},zo,Eo,{name:"convert",category:"other",description:"Convert a value to a number, string, boolean or array — strict: a failed conversion is an error, never a guess",parameters:{value:{type:"any",nullPolicy:e=>"boolean"===e?"value":"propagate",description:"The value to convert; null propagates except for boolean, where it is false"},to:{type:{literal:["number","string","boolean","array"]},description:"The target type"}},positionalParams:["value","to"],returns:["number","string","boolean","array"],evaluate:({value:t,to:r})=>{switch(r){case"number":if("number"==typeof t)return t;if("boolean"==typeof t)return t?1:0;if("string"==typeof t){const e=t.trim(),r=""===e?NaN:Number(e);if(Number.isNaN(r))throw new Ca(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw Mo(t,"number");case"string":if(Array.isArray(t)||e(t))throw new Ca(`cannot convert ${F(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw Mo(t,"string");return re(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return se(t);case"array":return Array.isArray(t)?t:[t]}}}].map(zn),Ro="3.0.0-preview.9",Io=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,a]of Object.entries(t)){if(void 0===a)continue;if(null===a){delete r[e];continue}if("data"===e||!n(a)){r[e]=a;continue}const t=r[e],o=n(t)?{...t}:{};for(const[e,t]of Object.entries(a))void 0!==t&&(null===t?delete o[e]:o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);Xo(r);const a=Vo(r);if(null!==e&&!(e=>void 0!==e.operators||void 0!==e.fragments||void 0!==e.operatorDefaults)(t))return{options:r,evaluation:a,registry:e.registry,compileCache:e.compileCache};const o=zr({operators:r.operators??[Fo],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:a,registry:o,compileCache:new wr({compile:e=>Lo(e,o),probe:ke})}},Vo=e=>{const t={...e};return delete t.operators,delete t.fragments,t},Lo=(e,t)=>{const r=Ee(e,t);return Et(r),r.hasNoCache&&rr(r),r};class Wo{state;results;version=Ro;constructor(e={}){this.state=Io(null,e),this.results=new bn(vn(this.state.options.cache))}updateOptions(e={}){const t=Io(this.state,e),r=vn(t.options.cache);this.state=t,this.results.configure(r)}clearCache(){this.results.clear()}getOptions(){return(e=>{const t={};for(const[r,a]of Object.entries(e))t[r]=n(a)?{...a}:a;return t})(this.state.evaluation)}getOperators(){return[...this.state.registry.operators.values()].map(e=>{const{definition:t,hostDefaults:r}=e,a={name:t.name,category:t.category,description:t.description,parameters:xn(t.parameters,r),restParam:t.restParam,timeoutParam:t.timeoutParam,cache:t.cache,returns:t.returns,hasValidate:void 0!==t.validate};return void 0!==t.alias&&(a.alias=t.alias),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.positionalParams&&(a.positionalParams=t.positionalParams),void 0!==r&&(!0===r.noCache&&(a.hostNoCache=!0),Object.hasOwn(r,"fallback")&&(a.hostFallback=r.fallback)),a})}getFragments(){return[...this.state.registry.fragments.values()].map(e=>{const t={name:e.name,parameters:Object.fromEntries(Object.entries(e.parameters).map(([e,t])=>[e,{...t}])),returns:e.returns,warnings:[...e.warnings],dependencies:$n(e.dependencies),caches:e.caches};return void 0!==e.description&&(t.description=e.description),void 0!==e.metadata&&(t.metadata=e.metadata),t})}validate(e,t){const r=void 0===t?this.state.evaluation:Ho(this.state.evaluation,t),a=Lo(e,this.state.registry),n=An(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n}}getDependencies(e){return $n(Ee(e,this.state.registry).dependencies)}isEvaluable(e){const t=Ee(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return Jo(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>Lo(e,r.registry))}compile(e){const{state:t}=this;return Go(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const Jo=async(e,t,r,a,n,o)=>{const s=void 0===a?e:Ho(e,a),i=n(),l="inert"===i.kind&&!0===s.trace?{kind:"artifact",artifact:o()}:i;if("inert"===l.kind){if(void 0!==s.maxDepth&&l.depth>s.maxDepth){const e=Pn(l.depth,s.maxDepth);throw Zo(e,[e])}return r}const{artifact:c}=l,u=On(c,s),d=u.find(e=>"error"===e.severity);if(void 0!==d)throw Zo(d,u);const p=await un(c,s,t);return!0===s.trace?p:p.result};let Bo;const Uo=(e,t)=>Bo?.(e,t);class Ko{#t;#r;#a;#n;#o;#s;#i;constructor(e,t,r,a,n){this.#t=e,this.#r=t,this.#a=r,this.#n=a,this.#o=n,Bo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Ho(e.#a,t);return{expression:e.#t,artifact:e.#l(),options:r}}}get expression(){return this.#t}get issues(){return this.#i??=this.#l().issues.map(e=>e.issue)}get hasErrors(){return this.#l().hasErrors}evaluate(e){return Jo(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return $n(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#s??=Lo(this.#t,this.#n)}}const Go=(e,t,r,a,n)=>new Ko(e,t,r,a,n),_o=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,trace:0})),Ho=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!_o.has(a))throw Qo(a);r??={...e},r[a]=n}}return void 0===r?e:(Xo(t),r)},Qo=e=>new A({code:s.invalidOptions,message:`'${e}' is not a per-call option — a call may supply data, signal, timeout and trace; configure the rest at construction or via updateOptions()`,path:[]}),Xo=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new A({code:s.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!Yo(r))throw new A({code:s.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},Yo=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Zo=(e,t)=>new A({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},issues:t});export{Ro as A,An as B,ee as C,te as D,X as E,Wo as F,ie as G,ge as H,Sn as N,Q as O,Dn as R,H as a,V as b,J as c,Fo as d,Da as e,Ce as f,Uo as g,On as h,se as i,W as j,Z as k,G as l,B as m,Tn as n,En as o,Ca as p,Ln as q,Ae as r,Se as s,je as t,re as u,Tt as v,F as w,zn as x,Nn as y,Wn as z};
@@ -1 +1 @@
1
- class e extends Error{code;path;operator;fragment;fragmentPath;errorData;related;cause;issues;trace;constructor(e){super(e.message),this.name="FigTreeError",this.code=e.code,this.path=e.path,void 0!==e.operator&&(this.operator=e.operator),void 0!==e.fragment&&(this.fragment=e.fragment),void 0!==e.fragmentPath&&(this.fragmentPath=e.fragmentPath),void 0!==e.errorData&&(this.errorData=e.errorData),void 0!==e.related&&(this.related=e.related),void 0!==e.cause&&(this.cause=e.cause),void 0!==e.issues&&(this.issues=e.issues),void 0!==e.trace&&(this.trace=e.trace)}prettyPrint(){const e=this.operator?` (operator: ${this.operator})`:"",n=this.path.length>0?` at ${t(this.path)}`:"",r=`${this.code}${e}${n}`,a=this.errorData&&Object.keys(this.errorData).length>0?`\n${JSON.stringify(this.errorData,null,2)}`:"";return`${r}\n${this.message}${a}`}}const n=n=>n instanceof e,t=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:0===n?e:`.${e}`).join(""),r={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",fallbackMismatch:"fallback-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",inertReferenceToken:"inert-reference-token",invalidDefinition:"invalid-definition",invalidName:"invalid-name",reservedName:"reserved-name",invalidNullPolicy:"invalid-null-policy",duplicateOperator:"duplicate-operator",invalidOptions:"invalid-options"},a=()=>{},i=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then,s=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=e=>{if("object"!=typeof e||null===e||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||null===n},l=(e,n,t)=>{if(e===n)return 0;const r=e.length,a=n.length;if(Math.abs(r-a)>t)return t+1;let i=new Array(a+1),s=new Array(a+1);for(let e=0;e<=a;e++)i[e]=e;for(let o=1;o<=r;o++){s[0]=o;let r=o;const l=e.charCodeAt(o-1);for(let e=1;e<=a;e++){const t=i[e-1]+(l===n.charCodeAt(e-1)?0:1),a=Math.min(i[e]+1,s[e-1]+1,t);s[e]=a,a<r&&(r=a)}if(r>t)return t+1;const d=i;i=s,s=d}return i[a]},d=(e,n)=>{let t,r=3;for(const a of n){const n=l(e,a,r-1);if(n<r&&(t=a,r=n,0===n))break}return t},u=e=>{let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")},c=e=>{let n;return()=>(void 0===n&&(n=(async()=>e())()),n)},m=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"literal"in e,f=(e,n)=>{const t=p(e),r=p(n);return!(!t.any&&!r.any)||(void 0!==t.literals&&void 0!==r.literals?t.literals.some(e=>r.literals.includes(e)):void 0!==t.literals?t.literals.some(e=>h(e,r.basics)):void 0!==r.literals?r.literals.some(e=>h(e,t.basics)):t.basics.some(e=>r.basics.includes(e)||"integer"===e&&r.basics.includes("number")||"number"===e&&r.basics.includes("integer")))},p=e=>{if(m(e))return{any:!1,basics:[],literals:e.literal};const n="string"==typeof e?[e]:e;return{any:n.includes("any"),basics:n}},h=(e,n)=>"string"==typeof e?n.includes("string"):"boolean"==typeof e?n.includes("boolean"):n.includes("number")||Number.isInteger(e)&&n.includes("integer"),g=/*#__PURE__*/new Set(["operator","fragment","parameters","fallback","noCache","vars","//"]),v=/*#__PURE__*/new Set([...g,"data","params","element","index","d","v","p","e","i","literal"]),y=e=>"string"!=typeof e?{ok:!1,reason:"a name must be a string"}:""===e?{ok:!1,reason:"a name must be non-empty"}:e.startsWith("$")?{ok:!1,reason:"a name may not start with '$'"}:/[.[\]]/.test(e)?{ok:!1,reason:"a name may not contain '.', '[' or ']'"}:{ok:!0},b=Symbol("figtree.path.wildcard"),k=e=>"string"==typeof e||"number"==typeof e||e===b,$={found:!1,value:void 0},x=e=>{const n=[];let t="",r=!1,a=0;const i=()=>{r&&(n.push(t),t="",r=!1)};for(;a<e.length;){const s=e[a];if("."!==s){if("["===s){i();const{segment:t,next:r}=w(e,a);n.push(t),a=r;continue}t+=s,r=!0,a++}else i(),a++}return i(),n},w=(e,n)=>{let t=n+1;if(t>=e.length)throw A(e,'unterminated "["');const r=e[t];if("*"===r){if("]"!==e[t+1])throw A(e,'expected "]" after "[*"');return{segment:b,next:t+2}}if('"'===r||"'"===r){const n=r;t++;let a="";for(;t<e.length;){const r=e[t];if("\\"===r){const n=e[t+1];if(void 0===n)throw A(e,"trailing escape in quoted key");a+=n,t+=2;continue}if(r===n){if("]"!==e[t+1])throw A(e,'expected "]" after quoted key');return{segment:a,next:t+2}}a+=r,t++}throw A(e,"unterminated quoted key")}let a="";for(;t<e.length&&e[t]>="0"&&e[t]<="9";)a+=e[t],t++;if(a.length>0&&"]"===e[t])return{segment:Number(a),next:t+1};throw A(e,'expected a number, "*", or a quoted key inside "[…]"')},A=(e,n)=>new Error(`Invalid path "${e}": ${n}`),j=(e,n)=>P(e,(e=>Array.isArray(e)?e.slice():x(e))(n),0),P=(e,n,t)=>{if(t>=n.length)return{found:!0,value:e};const r=n[t];if(r===b){if(!Array.isArray(e))return $;const r=t+1;if(r>=n.length)return{found:!0,value:e};return{found:!0,value:e.map(e=>{const t=P(e,n,r);return t.found?t.value:null})}}const a=D(e,r);return a.found?P(a.value,n,t+1):$},D=(e,n)=>{if(null===e||"object"!=typeof e)return $;if(Array.isArray(e)){const t="number"==typeof n?n:N(n);return void 0===t||t<0||t>=e.length?$:{found:!0,value:e[t]}}const t=String(n);return Object.prototype.propertyIsEnumerable.call(e,t)?{found:!0,value:e[t]}:$},N=e=>/^\d+$/.test(e)?Number(e):void 0,S=e=>e.map(e=>"string"==typeof e?N(e)??e:e),q={data:"data",d:"data",vars:"vars",v:"vars",params:"params",p:"params",element:"element",e:"element",index:"index",i:"index"},C=e=>{if(!e.startsWith("$"))return null;const n=/^\$([^.[]*)/.exec(e)[1];return{token:n,rest:e.slice(1+n.length)}},O=e=>""===e?[]:x(e.startsWith(".")?e.slice(1):e),W=e=>`${e}Index`,E=(e,n)=>{for(const t of n){if(e===t)return"element";if(e===W(t))return"index"}return null},M=(e,n)=>{const t=C(e);if(null===t)return{kind:"plain"};const{token:a,rest:i}=t,s=q[a];if(void 0===s){const e=void 0===n?.bindings?null:E(a,n.bindings);return null===e?{kind:"unrecognized"}:V(a,i,e)}if(""===i)return"vars"===s?{kind:"invalid",namespace:s,code:r.bareVars,reason:"'$vars' must name a var — there is no whole-scope value"}:{kind:"reference",namespace:s,segments:[],drill:i};if("index"===s)return{kind:"invalid",namespace:s,reason:"'$index' is bare-only — it cannot be drilled"};try{return{kind:"reference",namespace:s,segments:O(i),drill:i}}catch(e){return{kind:"invalid",namespace:s,reason:e.message}}},V=(e,n,t)=>{if("index"===t)return""!==n?{kind:"invalid",namespace:t,reason:"the index binding is bare-only — it cannot be drilled"}:{kind:"reference",namespace:t,segments:[],drill:n,binding:e};try{return{kind:"reference",namespace:t,segments:O(n),drill:n,binding:e}}catch(e){return{kind:"invalid",namespace:t,reason:e.message}}},z=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:e===b?"[*]":I(e,0===n)).join(""),F=/[.[\]"\\]/,I=(e,n)=>""===e||F.test(e)?`["${e.replace(/[\\"]/g,e=>`\\${e}`)}"]`:n?e:`.${e}`,R=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/,T=e=>R.test(e),B=(e,n)=>{const t=z(n);return""===t?`$${e}`:t.startsWith("[")?`$${e}${t}`:`$${e}.${t}`},Z=e=>B("data",e),_=/*#__PURE__*/new Set(["fallback","noCache","vars","//"]),G=500,H={kind:"operator"},J={kind:"fragment"},K={kind:"plain"},L=e=>({kind:"malformed",message:e}),Q=(e,n)=>{const t="operator"in e,r="fragment"in e,a=[];for(const t in e)t.startsWith("$")&&n(t.slice(1))&&a.push(t);return t&&r?L("'operator' and 'fragment' may not share a node"):(t||r)&&a.length>0?L(`a canonical '${t?"operator":"fragment"}' key may not sit beside the shorthand key '${a[0]}'`):t?H:r?J:a.length>=2?L(`one node, one invocation: found ${a.map(e=>`'${e}'`).join(" and ")}`):1===a.length?{kind:"shorthand",key:a[0]}:K},U=(e,n)=>{if(!o(e))return!1;if("operator"in e||"fragment"in e)return!0;for(const t in e)if(t.startsWith("$")&&n(t.slice(1)))return!0;return!1},X=(e,n)=>{const t=e.positionalParams;if(void 0===t)return null;const r=e.restParam,a=null===r?t.length:t.length-1;return n>a&&null===r?null:{bound:Math.min(n,a),restAt:null!==r&&n>=a?a:null}},Y=e=>{const n=e.positionalParams?.[0];return void 0===n?null:n.startsWith("...")?e.restParam:n},ee=["path","default"];export{Z as A,u as B,G as D,r as E,e as F,ee as G,g as R,_ as S,b as W,s as a,n as b,Q as c,o as d,U as e,M as f,C as g,z as h,m as i,x as j,y as k,v as l,B as m,T as n,S as o,X as p,d as q,j as r,Y as s,f as t,E as u,k as v,W as w,a as x,c as y,i as z};
1
+ class e extends Error{code;path;operator;fragment;fragmentPath;errorData;related;cause;issues;trace;constructor(e){super(e.message),this.name="FigTreeError",this.code=e.code,this.path=e.path,void 0!==e.operator&&(this.operator=e.operator),void 0!==e.fragment&&(this.fragment=e.fragment),void 0!==e.fragmentPath&&(this.fragmentPath=e.fragmentPath),void 0!==e.errorData&&(this.errorData=e.errorData),void 0!==e.related&&(this.related=e.related),void 0!==e.cause&&(this.cause=e.cause),void 0!==e.issues&&(this.issues=e.issues),void 0!==e.trace&&(this.trace=e.trace)}prettyPrint(){const e=this.operator?` (operator: ${this.operator})`:"",n=this.path.length>0?` at ${t(this.path)}`:"",r=`${this.code}${e}${n}`,a=this.errorData&&Object.keys(this.errorData).length>0?`\n${JSON.stringify(this.errorData,null,2)}`:"";return`${r}\n${this.message}${a}`}}const n=n=>n instanceof e,t=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:0===n?e:`.${e}`).join(""),r={unknownOperator:"unknown-operator",typeCheck:"type-check",operatorFailure:"operator-failure",timeout:"timeout",requestTimeout:"request-timeout",aborted:"aborted",unknownNodeKey:"unknown-node-key",unresolvedVar:"unresolved-var",unrecognizedIdentifier:"unrecognized-identifier",depthCeiling:"depth-ceiling",nonFiniteResult:"non-finite-result",escapedHandle:"escaped-handle",emptyAggregate:"empty-aggregate",malformedNode:"malformed-node",unknownFragment:"unknown-fragment",positionalArity:"positional-arity",invalidVars:"invalid-vars",invalidReference:"invalid-reference",uselessModifier:"useless-modifier",unreferencedVar:"unreferenced-var",missingRequired:"missing-required",unresolvedParam:"unresolved-param",unresolvedBinding:"unresolved-binding",deadBinding:"dead-binding",invalidAs:"invalid-as",maxDepthExceeded:"max-depth",maxNodesExceeded:"max-nodes",returnsMismatch:"returns-mismatch",fallbackMismatch:"fallback-mismatch",operatorValidate:"operator-validate",missingDataPath:"missing-data-path",shadowedVar:"shadowed-var",varCycle:"var-cycle",bareVars:"bare-vars",fragmentCycle:"fragment-cycle",unboundToken:"unbound-token",unusedSubstitution:"unused-substitution",inertReferenceToken:"inert-reference-token",invalidDefinition:"invalid-definition",invalidName:"invalid-name",reservedName:"reserved-name",invalidNullPolicy:"invalid-null-policy",duplicateOperator:"duplicate-operator",invalidOptions:"invalid-options"},a=()=>{},i=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then,s=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),o=e=>{if("object"!=typeof e||null===e||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||null===n},l=(e,n,t)=>{if(e===n)return 0;const r=e.length,a=n.length;if(Math.abs(r-a)>t)return t+1;let i=new Array(a+1),s=new Array(a+1);for(let e=0;e<=a;e++)i[e]=e;for(let o=1;o<=r;o++){s[0]=o;let r=o;const l=e.charCodeAt(o-1);for(let e=1;e<=a;e++){const t=i[e-1]+(l===n.charCodeAt(e-1)?0:1),a=Math.min(i[e]+1,s[e-1]+1,t);s[e]=a,a<r&&(r=a)}if(r>t)return t+1;const d=i;i=s,s=d}return i[a]},d=(e,n)=>{let t,r=3;for(const a of n){const n=l(e,a,r-1);if(n<r&&(t=a,r=n,0===n))break}return t},u=e=>{let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")},c=e=>{let n;return()=>(void 0===n&&(n=(async()=>e())()),n)},m=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"literal"in e,f=(e,n)=>{const t=p(e),r=p(n);return!(!t.any&&!r.any)||(void 0!==t.literals&&void 0!==r.literals?t.literals.some(e=>r.literals.includes(e)):void 0!==t.literals?t.literals.some(e=>h(e,r.basics)):void 0!==r.literals?r.literals.some(e=>h(e,t.basics)):t.basics.some(e=>r.basics.includes(e)||"integer"===e&&r.basics.includes("number")||"number"===e&&r.basics.includes("integer")))},p=e=>{if(m(e))return{any:!1,basics:[],literals:e.literal};const n="string"==typeof e?[e]:e;return{any:n.includes("any"),basics:n}},h=(e,n)=>"string"==typeof e?n.includes("string"):"boolean"==typeof e?n.includes("boolean"):n.includes("number")||Number.isInteger(e)&&n.includes("integer"),g=/*#__PURE__*/new Set(["operator","fragment","parameters","fallback","noCache","vars","//"]),v=/*#__PURE__*/new Set([...g,"data","params","element","index","d","v","p","e","i","literal"]),y=e=>"string"!=typeof e?{ok:!1,reason:"a name must be a string"}:""===e?{ok:!1,reason:"a name must be non-empty"}:e.startsWith("$")?{ok:!1,reason:"a name may not start with '$'"}:/[.[\]]/.test(e)?{ok:!1,reason:"a name may not contain '.', '[' or ']'"}:{ok:!0},b=Symbol("figtree.path.wildcard"),k=e=>"string"==typeof e||"number"==typeof e||e===b,$={found:!1,value:void 0},x=e=>{const n=[];let t="",r=!1,a=0;const i=()=>{r&&(n.push(t),t="",r=!1)};for(;a<e.length;){const s=e[a];if("."!==s){if("["===s){i();const{segment:t,next:r}=w(e,a);n.push(t),a=r;continue}t+=s,r=!0,a++}else i(),a++}return i(),n},w=(e,n)=>{let t=n+1;if(t>=e.length)throw A(e,'unterminated "["');const r=e[t];if("*"===r){if("]"!==e[t+1])throw A(e,'expected "]" after "[*"');return{segment:b,next:t+2}}if('"'===r||"'"===r){const n=r;t++;let a="";for(;t<e.length;){const r=e[t];if("\\"===r){const n=e[t+1];if(void 0===n)throw A(e,"trailing escape in quoted key");a+=n,t+=2;continue}if(r===n){if("]"!==e[t+1])throw A(e,'expected "]" after quoted key');return{segment:a,next:t+2}}a+=r,t++}throw A(e,"unterminated quoted key")}let a="";for(;t<e.length&&e[t]>="0"&&e[t]<="9";)a+=e[t],t++;if(a.length>0&&"]"===e[t])return{segment:Number(a),next:t+1};throw A(e,'expected a number, "*", or a quoted key inside "[…]"')},A=(e,n)=>new Error(`Invalid path "${e}": ${n}`),j=(e,n)=>P(e,(e=>Array.isArray(e)?e.slice():x(e))(n),0),P=(e,n,t)=>{if(t>=n.length)return{found:!0,value:e};const r=n[t];if(r===b){if(!Array.isArray(e))return $;const r=t+1;if(r>=n.length)return{found:!0,value:e};return{found:!0,value:e.map(e=>{const t=P(e,n,r);return t.found?t.value:null})}}const a=D(e,r);return a.found?P(a.value,n,t+1):$},D=(e,n)=>{if(null===e||"object"!=typeof e)return $;if(Array.isArray(e)){const t="number"==typeof n?n:C(n);return void 0===t||t<0||t>=e.length?$:{found:!0,value:e[t]}}const t=String(n);return Object.prototype.propertyIsEnumerable.call(e,t)?{found:!0,value:e[t]}:$},C=e=>/^\d+$/.test(e)?Number(e):void 0,N=e=>e.map(e=>"string"==typeof e?C(e)??e:e),S={data:"data",d:"data",vars:"vars",v:"vars",params:"params",p:"params",element:"element",e:"element",index:"index",i:"index"},q=e=>{if(!e.startsWith("$"))return null;const n=/^\$([^.[]*)/.exec(e)[1];return{token:n,rest:e.slice(1+n.length)}},O=e=>{const n=q(e);return null===n||""!==n.rest?null:S[n.token]??null},W=e=>""===e?[]:x(e.startsWith(".")?e.slice(1):e),E=e=>`${e}Index`,M=(e,n)=>{for(const t of n){if(e===t)return"element";if(e===E(t))return"index"}return null},V=(e,n)=>{const t=q(e);if(null===t)return{kind:"plain"};const{token:a,rest:i}=t,s=S[a];if(void 0===s){const e=void 0===n?.bindings?null:M(a,n.bindings);return null===e?{kind:"unrecognized"}:z(a,i,e)}if(""===i)return"vars"===s?{kind:"invalid",namespace:s,code:r.bareVars,reason:"'$vars' must name a var — there is no whole-scope value"}:{kind:"reference",namespace:s,segments:[],drill:i};if("index"===s)return{kind:"invalid",namespace:s,reason:"'$index' is bare-only — it cannot be drilled"};try{return{kind:"reference",namespace:s,segments:W(i),drill:i}}catch(e){return{kind:"invalid",namespace:s,reason:e.message}}},z=(e,n,t)=>{if("index"===t)return""!==n?{kind:"invalid",namespace:t,reason:"the index binding is bare-only — it cannot be drilled"}:{kind:"reference",namespace:t,segments:[],drill:n,binding:e};try{return{kind:"reference",namespace:t,segments:W(n),drill:n,binding:e}}catch(e){return{kind:"invalid",namespace:t,reason:e.message}}},F=e=>e.map((e,n)=>"number"==typeof e?`[${e}]`:e===b?"[*]":R(e,0===n)).join(""),I=/[.[\]"\\]/,R=(e,n)=>""===e||I.test(e)?`["${e.replace(/[\\"]/g,e=>`\\${e}`)}"]`:n?e:`.${e}`,T=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/,B=e=>T.test(e),Z=(e,n)=>{const t=F(n);return""===t?`$${e}`:t.startsWith("[")?`$${e}${t}`:`$${e}.${t}`},_=e=>Z("data",e),G=/*#__PURE__*/new Set(["fallback","noCache","vars","//"]),H=500,J={kind:"operator"},K={kind:"fragment"},L={kind:"plain"},Q=e=>({kind:"malformed",message:e}),U=(e,n)=>{const t="operator"in e,r="fragment"in e,a=[];for(const t in e)t.startsWith("$")&&n(t.slice(1))&&a.push(t);return t&&r?Q("'operator' and 'fragment' may not share a node"):(t||r)&&a.length>0?Q(`a canonical '${t?"operator":"fragment"}' key may not sit beside the shorthand key '${a[0]}'`):t?J:r?K:a.length>=2?Q(`one node, one invocation: found ${a.map(e=>`'${e}'`).join(" and ")}`):1===a.length?{kind:"shorthand",key:a[0]}:L},X=(e,n)=>{if(!o(e))return!1;if("operator"in e||"fragment"in e)return!0;for(const t in e)if(t.startsWith("$")&&n(t.slice(1)))return!0;return!1},Y=(e,n)=>{const t=e.positionalParams;if(void 0===t)return null;const r=e.restParam,a=null===r?t.length:t.length-1;return n>a&&null===r?null:{bound:Math.min(n,a),restAt:null!==r&&n>=a?a:null}},ee=e=>{const n=e.positionalParams?.[0];return void 0===n?null:n.startsWith("...")?e.restParam:n},ne=["path","default"];export{i as A,_ as B,u as C,H as D,r as E,e as F,ne as G,g as R,G as S,b as W,s as a,n as b,U as c,o as d,X as e,V as f,q as g,F as h,m as i,O as j,x as k,y as l,v as m,Z as n,B as o,Y as p,N as q,j as r,ee as s,f as t,d as u,M as v,k as w,E as x,a as y,c as z};
@@ -1 +1 @@
1
- import{c as e,E as r,p as n,S as a,d as s,e as o,R as i,s as l,f as u,g as f,G as c,h as p,W as m,j as d,F as h,D as k}from"../chunks/shared.js";export{t as typesIntersect}from"../chunks/shared.js";const g=e=>{const r=new Map;for(const{name:t,alias:n,positionalParams:a,restParam:s}of e.getOperators()){const e={name:t,alias:n,positionalParams:a,restParam:s};r.set(t,e),void 0!==n&&r.set(n,e)}const t=new Set(e.getFragments().map(({name:e})=>e));return{operators:r,fragments:t,recognizes:e=>"literal"===e||r.has(e)||t.has(e)}},v=(e,r)=>{const t=n(e,r.length);if(null===t)return null;const a=e.positionalParams,s=[];for(let e=0;e<t.bound;e++)s.push([a[e],r[e]]);return null!==t.restAt&&s.push([e.restParam,0===t.restAt?r:r.slice(t.restAt)]),s},y=/*#__PURE__*/new Set(["fallback","noCache","vars"]),$="'noCache' takes only the literal true — it is settled before the subtree runs",w=(e,t,n)=>{const a=e.operator;if("string"!=typeof a)return n(r.malformedNode,"the 'operator' value must be a literal string");if("literal"===a)return P(e,n);const s=t.operators.get(a);if(void 0===s)return n(r.unknownOperator,`'${a}' names no registered operator`);const o=[],i=[];for(const t in e){const a=e[t];if(void 0!==a)if("operator"===t)o.push({kind:"invocation"});else{if("noCache"===t&&!0!==a)return n(r.malformedNode,$);if("//"===t||y.has(t))o.push({kind:"keep",key:t,value:a});else{if("parameters"===t)return n(r.malformedNode,"'parameters' is reserved and unused on operator nodes");o.push({kind:"param",name:t,value:a}),i.push([t,a])}}}return{kind:"operator",operator:s,spelling:a,slots:o,params:i,fromPayload:!1}},P=(e,t)=>{if(!("value"in e))return t(r.malformedNode,"'literal' requires its content in 'value'");const n=[];for(const a in e){const s=e[a];if("operator"===a)n.push({kind:"invocation"});else if("value"===a)n.push({kind:"param",name:"value",value:s});else{if(void 0===s)continue;if("//"!==a&&!y.has(a))return t(r.unknownNodeKey,`'${a}' is not a key of 'literal' — content goes in 'value'`);n.push({kind:"keep",key:a,value:s})}}return{kind:"literal",content:e.value,slots:n,fromPayload:!1}},A=(e,t,n)=>{const a=e.fragment;if("string"!=typeof a)return n(r.malformedNode,"the 'fragment' value must be a literal string");if(!t.fragments.has(a))return n(r.unknownFragment,`'${a}' names no registered fragment`);const s=[];for(const a in e){const o=e[a];if(void 0!==o)if("fragment"===a)s.push({kind:"invocation"});else if("parameters"===a)N(o,t,n),s.push({kind:"param",name:a,value:o});else{if("noCache"===a&&!0!==o)return n(r.malformedNode,$);if("//"!==a&&!y.has(a))return n(r.unknownNodeKey,`'${a}' is not a key of a fragment call — arguments live only in 'parameters'`);s.push({kind:"keep",key:a,value:o})}}return{kind:"fragment",name:a,slots:s,parameters:e.parameters,fromPayload:!1}},N=(e,t,n)=>{s(e)||o(e,t.recognizes)||"string"==typeof e&&"reference"===u(e).kind||n(r.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one")},b=(e,t,n,o)=>{const i=t.slice(1),l="literal"===i,u=!l&&n.fragments.has(i),f=[];for(const n in e){const s=e[n];if(n!==t){if(!a.has(n))return o(r.malformedNode,`'${n}' may not sit beside the shorthand key '${t}' — reserved modifiers only`);if("noCache"===n&&!0!==s&&!l)return o(r.malformedNode,$);void 0!==s&&f.push({kind:"keep",key:n,value:s})}else f.push({kind:"invocation"})}const c=e[t];if(l)return{kind:"literal",content:c,slots:f,fromPayload:!0};if(u)return s(c)?{kind:"fragment",name:i,slots:f,parameters:c,fromPayload:!0}:o(r.malformedNode,`fragments have no single-value or positional form — '${t}' takes a named-arguments object`);const p=n.operators.get(i);return{kind:"operator",operator:p,spelling:i,slots:f,params:j(p,c,n,o),fromPayload:!0}},j=(e,t,n,a)=>{const u=()=>a(r.positionalArity,`'${e.name}' takes no positional arguments — use the named form`);if(Array.isArray(t)){const n=v(e,t);if(null!==n)return n;if(void 0===e.positionalParams)return u();const s=e.positionalParams;return a(r.positionalArity,`'${e.name}' takes at most ${s.length} positional argument${1===s.length?"":"s"} (${s.join(", ")}), got ${t.length}`)}if(s(t)&&!o(t,n.recognizes)){const n=[];for(const s in t){const o=t[s];if(void 0!==o){if("//"!==s&&i.has(s))return a(r.unknownNodeKey,`'${s}' is not a parameter of '${e.name}'`);n.push([s,o])}}return n}const f=l(e);return null===f?u():[[f,t]]},z={positionalParams:c,restParam:null},C=/*#__PURE__*/new Set(["path","from","default"]),W={data:"d",vars:"v",params:"p",element:"e",index:"i"},x=(e,r,t)=>"canonical"===t?r:"alias"===t?W[r]:e,M=(e,r)=>{if("preserve"===r)return e;const t=u(e);if("reference"!==t.kind)return e;const{token:n,rest:a}=f(e);return`$${x(n,t.namespace,r)}${a}`},S=e=>e.startsWith(".")?e.slice(1):e,F=(e,r)=>{if("string"!=typeof e)return null;const t=u(e);if("reference"!==t.kind)return null;const{namespace:n}=t,{token:a,rest:s}=f(e),o=`$${x(a,n,r)}`;switch(n){case"data":return{operator:"get",path:S(s)};case"element":return{operator:"get",path:S(s),from:o};case"vars":case"params":{if(0===t.segments.length)return{operator:"get",path:"",from:o};const e=(e=>{if(e.startsWith(".")){let r=1;for(;r<e.length&&"."!==e[r]&&"["!==e[r];)r++;return r>1?r:null}const r=e[1];if("["!==e[0]||'"'!==r&&"'"!==r)return null;for(let t=2;t<e.length;t++)if("\\"===e[t])t++;else if(e[t]===r)return"]"===e[t+1]?t+2:null;return null})(s);return null===e?null:{operator:"get",path:S(s.slice(e)),from:`${o}${s.slice(0,e)}`}}default:return null}},K=(e,r)=>{if(e.has("default"))return null;const t=(e=>{if("string"==typeof e){if(e.startsWith("$"))return null;try{return d(e)}catch{return null}}if(!Array.isArray(e))return null;for(const r of e)if(!("string"==typeof r&&!r.startsWith("$")||"number"==typeof r&&Number.isInteger(r)&&r>=0))return null;return e})(e.get("path"));if(null===t)return null;const n=p(t);let a;const s=e.get("from");if(void 0===s)a="canonical"===r?"$data":"$d";else{if("string"!=typeof s)return null;const e=u(s);if("reference"!==e.kind||"index"===e.namespace)return null;if(""!==n&&e.segments.includes(m))return null;a=M(s,r).replace(/\.$/,"")}return""===n?a:n.startsWith("[")?`${a}${n}`:`${a}.${n}`},O=e=>{const r=[];for(let t=e;null!==t;t=t.parent)r.push(t.key);return r.reverse()};class E{lookup;writer;path=null;depth=0;constructor(e,r){this.lookup=e,this.writer=r}fail=(e,r)=>{throw new h({code:e,message:r,path:O(this.path)})};child(e,r){return this.within(r,()=>this.value(e))}within(e,r){const{path:t,depth:n}=this;this.path={parent:t,key:e},this.depth=n+1;const a=r();return this.path=t,this.depth=n,a}value(t){if(this.depth>k&&this.fail(r.depthCeiling,`the expression nests deeper than the engine's ceiling of ${k} levels`),"string"==typeof t)return this.writer.string(t);if(Array.isArray(t))return t.map((e,r)=>this.child(e,r));if(!s(t))return t;const n=((t,n,a)=>{const s=e(t,n.recognizes);switch(s.kind){case"malformed":return a(r.malformedNode,s.message);case"plain":return s;case"operator":return w(t,n,a);case"fragment":return A(t,n,a);case"shorthand":return b(t,s.key,n,a)}})(t,this.lookup,this.fail);switch(n.kind){case"plain":return this.entries(t,!0);case"operator":return this.writer.operator(n,this);case"fragment":return this.writer.fragment(n,this);case"literal":return this.writer.literal(n,this)}}keep({key:e,value:r}){return"fallback"===e?this.child(r,e):"vars"===e?this.vars(r):r}parameters(e){return!s(e)||o(e,this.lookup.recognizes)?this.child(e,"parameters"):this.within("parameters",()=>this.entries(e,!1))}entries(e,r){const t={};for(const n in e){const a=e[n];t[n]="//"===n?a:r&&"vars"===n?this.vars(a):this.child(a,n)}return t}vars(e){return s(e)?this.within("vars",()=>this.entries(e,!1)):e}}const G=(e,r)=>"canonical"===r?e.operator.name:"alias"===r?e.operator.alias??e.operator.name:e.spelling,I=e=>Array.isArray(e)?e:[e],R=(e,r)=>[...I(e),...I(r)],q=e=>e.params.find(([e])=>"//"===e)?.[1],D=e=>e.slots.some(e=>"keep"===e.kind&&"//"===e.key),B={kind:"named"},H=(e,r)=>!(Array.isArray(e)||s(e)&&!o(e,r.recognizes)),J=(e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n="named"===e.arguments,a=e.getAsReference??!0;return{operator:(e,s)=>{const o=e.params.map(([e,r])=>[e,"//"===e?r:s.child(r,e)]),i=o.filter(([e])=>"//"!==e);if(a&&"get"===e.operator.name){const r=e.slots.some(e=>"keep"===e.kind)||e.params.some(([e])=>"//"===e)?null:K(new Map(i),t);if(null!==r)return r}const l=n?B:((e,r,t)=>{const n=e.positionalParams;if(void 0===n||0===r.length)return B;const a=e.restParam,s=null===a?n:n.slice(0,-1),o=new Map(r);for(const e of o.keys())if(e!==a&&!s.includes(e))return B;let i=0;for(;i<s.length&&o.has(s[i]);)i++;for(let e=i;e<s.length;e++)if(o.has(s[e]))return B;const l=null!==a&&o.has(a);if(null!==a&&l!==(i===s.length))return B;const u=s.slice(0,i).map(e=>o.get(e));if(l){const e=o.get(a);return Array.isArray(e)?{kind:"array",value:[...u,...e]}:0===s.length&&H(e,t)?{kind:"single",value:e}:B}return 1===i&&H(u[0],t)?{kind:"single",value:u[0]}:{kind:"array",value:u}})(e.operator,i,s.lookup),u="named"===l.kind?void 0:q(e),f=void 0!==u&&D(e),c={};for(const t of e.slots)"invocation"===t.kind?(void 0===u||f||(c["//"]=u),c[`$${G(e,r)}`]="named"===l.kind?Object.fromEntries(o):l.value):"keep"===t.kind&&(c[t.key]="//"===t.key&&f?R(t.value,u):s.keep(t));return c},fragment:(e,r)=>{const t=void 0===e.parameters?{}:r.parameters(e.parameters),n="string"==typeof t,a={};for(const s of e.slots)"invocation"===s.kind?n?(a.fragment=e.name,e.fromPayload&&(a.parameters=t)):a[`$${e.name}`]=t:"param"===s.kind?n&&(a.parameters=t):a[s.key]=r.keep(s);return a},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?t.$literal=e.content:"keep"===n.kind&&(t[n.key]=r.keep(n));return t},string:e=>M(e,t)}},L=(e,r,t)=>new E(g(r),((e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n=e.referencesAsGet??!1;return{operator:(e,t)=>{const n={},a=e.fromPayload?q(e):void 0,s=void 0!==a&&D(e);for(const o of e.slots)if("invocation"===o.kind){if(void 0===a||s||(n["//"]=a),n.operator=G(e,r),e.fromPayload)for(const[r,a]of e.params)"//"!==r&&(n[r]=t.child(a,r))}else"param"===o.kind?n[o.name]=t.child(o.value,o.name):"//"===o.key&&s?n["//"]=R(o.value,a):n[o.key]=t.keep(o);return n},fragment:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.fragment=e.name,e.fromPayload&&(t.parameters=r.parameters(e.parameters))):"param"===n.kind?t.parameters=r.parameters(n.value):t[n.key]=r.keep(n);return t},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.operator="literal",e.fromPayload&&(t.value=e.content)):"param"===n.kind?t.value=e.content:t[n.key]=r.keep(n);return t},string:e=>{if(n){const r=F(e,t);if(null!==r)return r}return M(e,t)}}})(t)).value(e),Q=(e,r,t)=>new E(g(r),J(t)).value(e),T=(e,r)=>F(e,r?.referenceNames??"preserve"),U=(e,r)=>{const t=(e=>{if(!s(e))return null;const r=new Map;if("operator"in e){if("get"!==e.operator)return null;for(const t in e){const n=e[t];if("operator"!==t&&"//"!==t&&void 0!==n){if(!C.has(t))return null;r.set(t,n)}}return r}for(const r in e)if("$get"!==r&&"//"!==r)return null;if(!("$get"in e))return null;const t=e.$get;if(Array.isArray(t)){const e=v(z,t);if(null===e)return null;for(const[t,n]of e)r.set(t,n);return r}if(s(t)){for(const e in t){const n=t[e];if("//"!==e&&void 0!==n){if(!C.has(e))return null;r.set(e,n)}}return r}return r.set(l(z),t),r})(e);return null===t?null:K(t,r?.referenceNames??"preserve")};export{e as classifyObject,n as positionalLayout,u as recognizeReference,l as singlePositionalTarget,L as toCanonical,T as toGet,U as toReference,Q as toShorthand};
1
+ import{c as e,E as r,p as n,S as a,d as s,e as o,R as i,s as l,f as u,g as f,G as p,h as m,j as c,W as d,k as h,F as k,D as g}from"../chunks/shared.js";export{t as typesIntersect}from"../chunks/shared.js";const v=e=>{const r=new Map;for(const{name:t,alias:n,positionalParams:a,restParam:s}of e.getOperators()){const e={name:t,alias:n,positionalParams:a,restParam:s};r.set(t,e),void 0!==n&&r.set(n,e)}const t=new Set(e.getFragments().map(({name:e})=>e));return{operators:r,fragments:t,recognizes:e=>"literal"===e||r.has(e)||t.has(e)}},y=(e,r)=>{const t=n(e,r.length);if(null===t)return null;const a=e.positionalParams,s=[];for(let e=0;e<t.bound;e++)s.push([a[e],r[e]]);return null!==t.restAt&&s.push([e.restParam,0===t.restAt?r:r.slice(t.restAt)]),s},$=/*#__PURE__*/new Set(["fallback","noCache","vars"]),w="'noCache' takes only the literal true — it is settled before the subtree runs",P=(e,t,n)=>{const a=e.operator;if("string"!=typeof a)return n(r.malformedNode,"the 'operator' value must be a literal string");if("literal"===a)return A(e,n);const s=t.operators.get(a);if(void 0===s)return n(r.unknownOperator,`'${a}' names no registered operator`);const o=[],i=[];for(const t in e){const a=e[t];if(void 0!==a)if("operator"===t)o.push({kind:"invocation"});else{if("noCache"===t&&!0!==a)return n(r.malformedNode,w);if("//"===t||$.has(t))o.push({kind:"keep",key:t,value:a});else{if("parameters"===t)return n(r.malformedNode,"'parameters' is reserved and unused on operator nodes");o.push({kind:"param",name:t,value:a}),i.push([t,a])}}}return{kind:"operator",operator:s,spelling:a,slots:o,params:i,fromPayload:!1}},A=(e,t)=>{if(!("value"in e))return t(r.malformedNode,"'literal' requires its content in 'value'");const n=[];for(const a in e){const s=e[a];if("operator"===a)n.push({kind:"invocation"});else if("value"===a)n.push({kind:"param",name:"value",value:s});else{if(void 0===s)continue;if("//"!==a&&!$.has(a))return t(r.unknownNodeKey,`'${a}' is not a key of 'literal' — content goes in 'value'`);n.push({kind:"keep",key:a,value:s})}}return{kind:"literal",content:e.value,slots:n,fromPayload:!1}},N=(e,t,n)=>{const a=e.fragment;if("string"!=typeof a)return n(r.malformedNode,"the 'fragment' value must be a literal string");if(!t.fragments.has(a))return n(r.unknownFragment,`'${a}' names no registered fragment`);const s=[];for(const a in e){const o=e[a];if(void 0!==o)if("fragment"===a)s.push({kind:"invocation"});else if("parameters"===a)b(o,t,n),s.push({kind:"param",name:a,value:o});else{if("noCache"===a&&!0!==o)return n(r.malformedNode,w);if("//"!==a&&!$.has(a))return n(r.unknownNodeKey,`'${a}' is not a key of a fragment call — arguments live only in 'parameters'`);s.push({kind:"keep",key:a,value:o})}}return{kind:"fragment",name:a,slots:s,parameters:e.parameters,fromPayload:!1}},b=(e,t,n)=>{s(e)||o(e,t.recognizes)||"string"==typeof e&&"reference"===u(e).kind||n(r.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one")},j=(e,t,n,o)=>{const i=t.slice(1),l="literal"===i,u=!l&&n.fragments.has(i),f=[];for(const n in e){const s=e[n];if(n!==t){if(!a.has(n))return o(r.malformedNode,`'${n}' may not sit beside the shorthand key '${t}' — reserved modifiers only`);if("noCache"===n&&!0!==s&&!l)return o(r.malformedNode,w);void 0!==s&&f.push({kind:"keep",key:n,value:s})}else f.push({kind:"invocation"})}const p=e[t];if(l)return{kind:"literal",content:p,slots:f,fromPayload:!0};if(u)return s(p)?{kind:"fragment",name:i,slots:f,parameters:p,fromPayload:!0}:o(r.malformedNode,`fragments have no single-value or positional form — '${t}' takes a named-arguments object`);const m=n.operators.get(i);return{kind:"operator",operator:m,spelling:i,slots:f,params:x(m,p,n,o),fromPayload:!0}},x=(e,t,n,a)=>{const u=()=>a(r.positionalArity,`'${e.name}' takes no positional arguments — use the named form`);if(Array.isArray(t)){const n=y(e,t);if(null!==n)return n;if(void 0===e.positionalParams)return u();const s=e.positionalParams;return a(r.positionalArity,`'${e.name}' takes at most ${s.length} positional argument${1===s.length?"":"s"} (${s.join(", ")}), got ${t.length}`)}if(s(t)&&!o(t,n.recognizes)){const n=[];for(const s in t){const o=t[s];if(void 0!==o){if("//"!==s&&i.has(s))return a(r.unknownNodeKey,`'${s}' is not a parameter of '${e.name}'`);n.push([s,o])}}return n}const f=l(e);return null===f?u():[[f,t]]},z={positionalParams:p,restParam:null},C=/*#__PURE__*/new Set(["path","from","default"]),W={data:"d",vars:"v",params:"p",element:"e",index:"i"},M=(e,r,t)=>"canonical"===t?r:"alias"===t?W[r]:e,S=(e,r)=>{if("preserve"===r)return e;const t=u(e);if("reference"!==t.kind)return e;const{token:n,rest:a}=f(e);return`$${M(n,t.namespace,r)}${a}`},F=(e,r)=>{if("string"!=typeof e)return null;const t=u(e);if("reference"!==t.kind)return null;const{namespace:n,segments:a}=t;if("index"===n)return null;const{token:s,rest:o}=f(e),i=(l=o).startsWith(".")?l.slice(1):l;var l;return"data"===n?{operator:"get",path:i}:"element"!==n&&a.length>0&&"string"!=typeof a[0]?null:{operator:"get",path:i,from:`$${M(s,n,r)}`}},K=(e,r)=>{if(e.has("default"))return null;const t=(e=>{if("string"==typeof e){if(e.startsWith("$"))return null;try{return h(e)}catch{return null}}if(!Array.isArray(e))return null;for(const r of e)if(!("string"==typeof r&&!r.startsWith("$")||"number"==typeof r&&Number.isInteger(r)&&r>=0))return null;return e})(e.get("path"));if(null===t)return null;const n=m(t);let a;const s=e.get("from");if(void 0===s)a="canonical"===r?"$data":"$d";else{if("string"!=typeof s)return null;const e=c(s);if("vars"===e||"params"===e){if(0===t.length?"vars"===e:"string"!=typeof t[0])return null;a=`$${M(f(s).token,e,r)}`}else{const e=u(s);if("reference"!==e.kind||"index"===e.namespace)return null;if(""!==n&&e.segments.includes(d))return null;a=S(s,r).replace(/\.$/,"")}}return""===n?a:n.startsWith("[")?`${a}${n}`:`${a}.${n}`},O=e=>{const r=[];for(let t=e;null!==t;t=t.parent)r.push(t.key);return r.reverse()};class E{lookup;writer;path=null;depth=0;constructor(e,r){this.lookup=e,this.writer=r}fail=(e,r)=>{throw new k({code:e,message:r,path:O(this.path)})};child(e,r){return this.within(r,()=>this.value(e))}within(e,r){const{path:t,depth:n}=this;this.path={parent:t,key:e},this.depth=n+1;const a=r();return this.path=t,this.depth=n,a}value(t){if(this.depth>g&&this.fail(r.depthCeiling,`the expression nests deeper than the engine's ceiling of ${g} levels`),"string"==typeof t)return this.writer.string(t);if(Array.isArray(t))return t.map((e,r)=>this.child(e,r));if(!s(t))return t;const n=((t,n,a)=>{const s=e(t,n.recognizes);switch(s.kind){case"malformed":return a(r.malformedNode,s.message);case"plain":return s;case"operator":return P(t,n,a);case"fragment":return N(t,n,a);case"shorthand":return j(t,s.key,n,a)}})(t,this.lookup,this.fail);switch(n.kind){case"plain":return this.entries(t,!0);case"operator":return this.writer.operator(n,this);case"fragment":return this.writer.fragment(n,this);case"literal":return this.writer.literal(n,this)}}keep({key:e,value:r}){return"fallback"===e?this.child(r,e):"vars"===e?this.vars(r):r}parameters(e){return!s(e)||o(e,this.lookup.recognizes)?this.child(e,"parameters"):this.within("parameters",()=>this.entries(e,!1))}entries(e,r){const t={};for(const n in e){const a=e[n];t[n]="//"===n?a:r&&"vars"===n?this.vars(a):this.child(a,n)}return t}vars(e){return s(e)?this.within("vars",()=>this.entries(e,!1)):e}}const G=(e,r)=>"canonical"===r?e.operator.name:"alias"===r?e.operator.alias??e.operator.name:e.spelling,I=e=>Array.isArray(e)?e:[e],R=(e,r)=>[...I(e),...I(r)],q=e=>e.params.find(([e])=>"//"===e)?.[1],D=e=>e.slots.some(e=>"keep"===e.kind&&"//"===e.key),B={kind:"named"},H=(e,r)=>!(Array.isArray(e)||s(e)&&!o(e,r.recognizes)),J=(e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n="named"===e.arguments,a=e.getAsReference??!0;return{operator:(e,s)=>{const o=e.params.map(([e,r])=>[e,"//"===e?r:s.child(r,e)]),i=o.filter(([e])=>"//"!==e);if(a&&"get"===e.operator.name){const r=e.slots.some(e=>"keep"===e.kind)||e.params.some(([e])=>"//"===e)?null:K(new Map(i),t);if(null!==r)return r}const l=n?B:((e,r,t)=>{const n=e.positionalParams;if(void 0===n||0===r.length)return B;const a=e.restParam,s=null===a?n:n.slice(0,-1),o=new Map(r);for(const e of o.keys())if(e!==a&&!s.includes(e))return B;let i=0;for(;i<s.length&&o.has(s[i]);)i++;for(let e=i;e<s.length;e++)if(o.has(s[e]))return B;const l=null!==a&&o.has(a);if(null!==a&&l!==(i===s.length))return B;const u=s.slice(0,i).map(e=>o.get(e));if(l){const e=o.get(a);return Array.isArray(e)?{kind:"array",value:[...u,...e]}:0===s.length&&H(e,t)?{kind:"single",value:e}:B}return 1===i&&H(u[0],t)?{kind:"single",value:u[0]}:{kind:"array",value:u}})(e.operator,i,s.lookup),u="named"===l.kind?void 0:q(e),f=void 0!==u&&D(e),p={};for(const t of e.slots)"invocation"===t.kind?(void 0===u||f||(p["//"]=u),p[`$${G(e,r)}`]="named"===l.kind?Object.fromEntries(o):l.value):"keep"===t.kind&&(p[t.key]="//"===t.key&&f?R(t.value,u):s.keep(t));return p},fragment:(e,r)=>{const t=void 0===e.parameters?{}:r.parameters(e.parameters),n="string"==typeof t,a={};for(const s of e.slots)"invocation"===s.kind?n?(a.fragment=e.name,e.fromPayload&&(a.parameters=t)):a[`$${e.name}`]=t:"param"===s.kind?n&&(a.parameters=t):a[s.key]=r.keep(s);return a},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?t.$literal=e.content:"keep"===n.kind&&(t[n.key]=r.keep(n));return t},string:e=>S(e,t)}},L=(e,r,t)=>new E(v(r),((e={})=>{const r=e.operatorNames??"preserve",t=e.referenceNames??"preserve",n=e.referencesAsGet??!1;return{operator:(e,t)=>{const n={},a=e.fromPayload?q(e):void 0,s=void 0!==a&&D(e);for(const o of e.slots)if("invocation"===o.kind){if(void 0===a||s||(n["//"]=a),n.operator=G(e,r),e.fromPayload)for(const[r,a]of e.params)"//"!==r&&(n[r]=t.child(a,r))}else"param"===o.kind?n[o.name]=t.child(o.value,o.name):"//"===o.key&&s?n["//"]=R(o.value,a):n[o.key]=t.keep(o);return n},fragment:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.fragment=e.name,e.fromPayload&&(t.parameters=r.parameters(e.parameters))):"param"===n.kind?t.parameters=r.parameters(n.value):t[n.key]=r.keep(n);return t},literal:(e,r)=>{const t={};for(const n of e.slots)"invocation"===n.kind?(t.operator="literal",e.fromPayload&&(t.value=e.content)):"param"===n.kind?t.value=e.content:t[n.key]=r.keep(n);return t},string:e=>{if(n){const r=F(e,t);if(null!==r)return r}return S(e,t)}}})(t)).value(e),Q=(e,r,t)=>new E(v(r),J(t)).value(e),T=(e,r)=>F(e,r?.referenceNames??"preserve"),U=(e,r)=>{const t=(e=>{if(!s(e))return null;const r=new Map;if("operator"in e){if("get"!==e.operator)return null;for(const t in e){const n=e[t];if("operator"!==t&&"//"!==t&&void 0!==n){if(!C.has(t))return null;r.set(t,n)}}return r}for(const r in e)if("$get"!==r&&"//"!==r)return null;if(!("$get"in e))return null;const t=e.$get;if(Array.isArray(t)){const e=y(z,t);if(null===e)return null;for(const[t,n]of e)r.set(t,n);return r}if(s(t)){for(const e in t){const n=t[e];if("//"!==e&&void 0!==n){if(!C.has(e))return null;r.set(e,n)}}return r}return r.set(l(z),t),r})(e);return null===t?null:K(t,r?.referenceNames??"preserve")};export{e as classifyObject,n as positionalLayout,u as recognizeReference,l as singlePositionalTarget,L as toCanonical,T as toGet,U as toReference,Q as toShorthand};
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- declare const version = "3.0.0-preview.8";
1
+ declare const version = "3.0.0-preview.9";
2
2
 
3
3
  interface HttpRequest {
4
4
  url: string;
@@ -641,7 +641,7 @@ interface FragmentInfo {
641
641
  declare class FigTree<InstanceOpts extends FigTreeOptions = NoOptions> {
642
642
  private state;
643
643
  private readonly results;
644
- readonly version = "3.0.0-preview.8";
644
+ readonly version = "3.0.0-preview.9";
645
645
  constructor(options?: InstanceOpts);
646
646
  updateOptions(options?: OptionsUpdate): void;
647
647
  clearCache(): void;
package/build/index.js CHANGED
@@ -1 +1 @@
1
- import{j as t,O as a,k as r,l as n,E as o,c as s,m as l,N as u,b as c,R as p,n as m,o as f,p as y,q as h,u as v,w as g,x as w,y as P,z as $,t as k,s as O,g as A,A as q,B as x}from"./chunks/engine.js";export{C as ARRAY,F as FigTree,D as OBJECT,G as compareValues,d as coreOperators,H as deepEqual,e as isOperatorFailure,i as isTruthy}from"./chunks/engine.js";import{a as N,E,k as L,R as S,F as T,l as Q,r as R,d as z,D as J,m as U}from"./chunks/shared.js";export{W as WILDCARD,b as isFigTreeError,j as parsePath}from"./chunks/shared.js";const V=/*#__PURE__*/new Set(["failures","external","output"]),M=/*#__PURE__*/new Set(["code","parameter","when","options","may","overflow"]),B=e=>{if(null===e||["string","number","boolean"].includes(typeof e))return!0;if(!N(e))return!1;const a=Object.keys(e);if(1!==a.length)return!1;const r=e[a[0]];switch(a[0]){case"type":return t(r);case"below":return"number"==typeof r&&Number.isFinite(r);case"empty":case"invalid":return!0===r;case"supplied":return"boolean"==typeof r;case"some":case"not":return B(r);default:return!1}},I=["param","elementOf","kindOf","typeNamedBy","firstNonNull","sum","product","abs","min","max"],Y=e=>void 0===e||"number"==typeof e&&Number.isFinite(e),K=e=>void 0===e||Number.isInteger(e)&&e>=0,X=(e,t,...a)=>t in e&&Object.keys(e).every(e=>e===t||a.includes(e)),Z=(e,a)=>{if(t(e))return!0;if(!N(e))return!1;const r=Object.keys(e);return 1===r.length&&I.includes(r[0])?a(e[r[0]]):"type"in e?(e=>{const{type:t,min:a,max:r,minLength:n}=e;return"number"===t||"integer"===t?X(e,"type","min","max")&&Y(a)&&Y(r)&&!(a>r):("string"===t||"array"===t)&&X(e,"type","minLength")&&K(n)})(e):X(e,"difference")?Array.isArray(e.difference)&&2===e.difference.length&&e.difference.every(a):X(e,"arrayOf","minLength")?K(e.minLength)&&Z(e.arrayOf,a):X(e,"oneOf")?Array.isArray(e.oneOf)&&e.oneOf.length>0&&e.oneOf.every(e=>Z(e,a)):!(!X(e,"byParam","cases","otherwise")||!("cases"in e))&&(a(e.byParam)&&N(e.cases)&&Object.values(e.cases).every(e=>Z(e,a))&&(void 0===e.otherwise||Z(e.otherwise,a)))},_=/[a-z]Default$/,ee=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),te=/*#__PURE__*/new Set(a),ae=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),re=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),ne=(e,t)=>{const[a]=e,r=e.length-1,n=r>0?`${a.message} (+ ${r} more issue${1===r?"":"s"})`:a.message;throw new T({code:E.invalidDefinition,message:n,path:a.path,...void 0!==t?{operator:t}:{},issues:e})};function ie(e){if(r(e))return e;const a=[],i=N(e)?e.name:void 0,d="string"==typeof i?i:void 0,y=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==d?{operator:d}:{},...void 0!==n?{parameter:n}:{}})};N(e)||(y(E.invalidDefinition,"a definition must be a plain object",[]),ne(a));const h=e;"string"!=typeof h.name&&y(E.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof h.description&&""!==h.description||y(E.invalidDefinition,"'description' is required and must be non-empty",["description"]),N(h.parameters)||y(E.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof h.evaluate&&y(E.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&ne(a,d),"string"!=typeof h.category?y(E.invalidDefinition,`'category' is required and must be one of ${[...te].join(", ")}`,["category"]):te.has(h.category)||y(E.invalidDefinition,`'${h.category}' is not a category — expected one of ${[...te].join(", ")}`,["category"]),void 0!==h.alias&&"string"!=typeof h.alias&&y(E.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==h.cache&&!0!==h.cache&&y(E.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===h.metadata||N(h.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===h.positionalParams||Array.isArray(h.positionalParams)&&!h.positionalParams.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==h.timeoutParam&&"string"!=typeof h.timeoutParam&&y(E.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==h.validate&&"function"!=typeof h.validate&&y(E.invalidDefinition,"'validate' must be a function",["validate"]),void 0===h.returns||t(h.returns)||y(E.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const v=(e,t,a)=>{e===o?y(E.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,a):Array.isArray(e)&&e.forEach((e,r)=>{e===o&&v(e,[...t,r],a)})};for(const[e,t]of Object.entries(h))"parameters"!==e&&"metadata"!==e&&v(t,[e]);const b=(e,t)=>{const a=L(e);a.ok?Q.has(e)&&y(E.reservedName,`'${e}' is a reserved name`,t):y(E.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof h.name&&b(h.name,["name"]),"string"==typeof h.alias&&b(h.alias,["alias"]);const g=h.parameters,w={};for(const[e,t]of Object.entries(g)){const a=["parameters",e],r=L(e);r.ok?S.has(e)&&y(E.reservedName,`'${e}' is a reserved node key and cannot name a parameter`,a,e):y(E.invalidName,`'${e}': ${r.reason}`,a,e),N(t)?w[e]=t:y(E.invalidDefinition,`the declaration for '${e}' must be a plain object`,a,e)}const j={};for(const[e,a]of Object.entries(w)){const r=["parameters",e],i=e=>[...r,e],d=a;for(const[t,a]of Object.entries(d))"default"!==t&&"metadata"!==t&&v(a,i(t),e);let p=!0;void 0===d.type||t(d.type)||(y(E.invalidDefinition,"'type' must be a metadata-vocabulary type",i("type"),e),p=!1),p&&(j[e]=d.type??"any");let m=!1;if(void 0!==d.constraints){const t=n(d.constraints);t.ok?m=!0:y(E.invalidDefinition,`'constraints' is malformed: expected ${t.expected}, got ${t.actual}`,i("constraints"),e)}void 0!==d.required&&"boolean"!=typeof d.required&&y(E.invalidDefinition,"'required' must be a boolean",i("required"),e),void 0!==d.description&&"string"!=typeof d.description&&y(E.invalidDefinition,"'description' must be a string",i("description"),e),void 0===d.metadata||N(d.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",i("metadata"),e);const f="default"in d;if(f&&!0===d.required&&y(E.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",i("default"),e),f&&d.default!==o){const t=j[e];if(void 0!==t){const a=s(d.default,t);if(a.ok){if(m&&void 0!==d.constraints){const t=l(d.default,d.constraints);t.ok||y(E.typeCheck,`'default' violates the declared constraints: expected ${t.expected}, got ${t.actual}`,i("default"),e)}}else y(E.typeCheck,`'default' does not satisfy the declared type: expected ${a.expected}, got ${a.actual}`,i("default"),e)}}if(void 0===d.evaluation||ee.has(d.evaluation)||y(E.invalidDefinition,`'evaluation' must be one of ${[...ee].join(", ")}`,i("evaluation"),e),void 0!==d.truthiness&&"boolean"!=typeof d.truthiness&&y(E.invalidDefinition,"'truthiness' must be a boolean",i("truthiness"),e),void 0!==d.over&&"string"!=typeof d.over&&y(E.invalidDefinition,"'over' must be a parameter name",i("over"),e),void 0===d.replacesNullAt||Array.isArray(d.replacesNullAt)&&!d.replacesNullAt.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",i("replacesNullAt"),e),void 0!==d.nullPolicy){const t=d.nullPolicy;"function"==typeof t||u.has(t)||y(E.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",i("nullPolicy"),e);const a=j[e];void 0===a||c(a)||y(E.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",i("nullPolicy"),e),!0===d.truthiness&&"propagate"===t&&y(E.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",i("nullPolicy"),e)}if(void 0!==d.elementNullPolicy){u.has(d.elementNullPolicy)||y(E.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",i("elementNullPolicy"),e);const t=j[e];void 0===t||re(t)||y(E.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",i("elementNullPolicy"),e)}}if(Array.isArray(h.positionalParams)&&h.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=h.positionalParams;t.forEach((a,r)=>{const n=a.startsWith(p),i=n?a.slice(p.length):a;n&&r!==t.length-1&&y(E.invalidDefinition,`the rest entry '${a}' must be the last positional entry`,["positionalParams",r]),i in w||y(E.invalidDefinition,`positional entry '${a}' names no declared parameter`,["positionalParams",r]),e.has(i)&&y(E.invalidDefinition,`duplicate positional entry '${a}'`,["positionalParams",r]),e.add(i)})}for(const[e,t]of Object.entries(w)){const a=["parameters",e],r="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(r){const r=t.over;if(r in w&&r!==e){const t=j[r];void 0===t||ae(t)||y(E.invalidDefinition,`the 'over' target '${r}' must admit an array`,[...a,"over"],e)}else y(E.invalidDefinition,`'over' names no sibling parameter ('${r}')`,[...a,"over"],e)}else y(E.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...a,"over"],e);else r&&y(E.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...a,"evaluation"],e)}for(const[e,t]of Object.entries(w)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const a=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&y(E.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",a,e);(t.required??!("default"in t))&&y(E.invalidDefinition,"a 'replacesNullAt' holder must be optional",a,e),"default"in t&&y(E.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",a,e),t.replacesNullAt.forEach((t,r)=>{t===e?y(E.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...a,r],e):t in w||y(E.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...a,r],e)})}for(const[e,t]of Object.entries(w))_.test(e)&&"lazy"!==t.evaluation&&y(E.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const P=m(w,j,y);if("string"==typeof h.timeoutParam){void 0===w[h.timeoutParam]?y(E.invalidDefinition,`'timeoutParam' names no declared parameter ('${h.timeoutParam}')`,["timeoutParam"]):"integer"!==j[h.timeoutParam]&&y(E.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return void 0!==h.analysis&&((e,t,a)=>{const r=(e,...t)=>a(E.invalidDefinition,e,["analysis",...t]);if(!N(e))return r("'analysis' must be a plain object");for(const t of Object.keys(e))V.has(t)||r(`'${t}' is not an analysis field`,t);const{failures:n,external:i,output:o}=e,s=e=>"string"==typeof e&&Object.hasOwn(t,e);if(void 0!==i&&!0!==i&&r("'external' must be the literal true","external"),void 0===o||Z(o,s)||r("'output' must be a type, or an output declaration naming declared parameters","output"),void 0!==n){if(!Array.isArray(n))return r("'failures' must be an array of rules","failures");!0===i&&r("an external operator declares no 'failures': it may fail whatever its inputs","failures"),n.forEach((e,t)=>{const a=(...e)=>["failures",t,...e];if(!N(e))return r("a rule must be a plain object",...a());for(const t of Object.keys(e))M.has(t)||r(`'${t}' is not a rule field`,...a(t));if("string"==typeof e.code&&""!==e.code||r("a rule's 'code' must be a non-empty string",...a("code")),void 0===e.parameter||s(e.parameter)||r("'parameter' names no declared parameter",...a("parameter")),void 0!==e.when)if(N(e.when))for(const[t,n]of Object.entries(e.when))s(t)?B(n)||r(`the test on '${t}' is malformed`,...a("when",t)):r(`'${t}' is not a declared parameter`,...a("when",t));else r("'when' must be an object of tests",...a("when"));void 0===e.options||N(e.options)||r("'options' must be a plain object",...a("options"));for(const t of["may","overflow"])void 0!==e[t]&&!0!==e[t]&&r(`'${t}' must be the literal true`,...a(t))})}})(h.analysis,w,(e,t,a)=>y(e,t,a)),a.length>0&&ne(a,d),f(h,P)}const oe=e=>new y(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),se=(e,t)=>{const a=t instanceof Error?t.message:String(t),r=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof r[e]&&(n[e]=r[e]);return new y(`${e}: ${a}`,{errorData:n})},le=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class ue{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new y("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,a=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),r=await a.text();if(!a.ok)throw oe({status:a.status,statusText:a.statusText,url:a.url||e.url,payload:pe(r)});return de(r,a.url||e.url,a.status)}}class ce{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new y("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw oe({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const de=(e,t,a)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new y(`response was not JSON (${a}): ${t}`,{errorData:{status:a,url:t,response:le(e)}})}},pe=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return le(e)}},me=/^https?:\/\//i,fe=(e,t,a)=>{const r=me.test(e)?e:ye(a,e),n=he(t),i=""===n?r:`${r}${r.includes("?")?"&":"?"}${n}`;try{new URL(i)}catch{throw new y(`'${i}' is not a valid URL`,{code:E.typeCheck})}return i},ye=(e,t)=>{if(void 0===e||""===e)throw new y(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:E.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},he=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[a,r]of Object.entries(e))null!=r&&t.append(a,ge(r,`query['${a}']`,"query"));return t.toString()},ve=(...e)=>{const t={};for(const a of e)if(void 0!==a)for(const[e,r]of Object.entries(a))null!=r?t[e]=ge(r,`headers['${e}']`,"header"):delete t[e];return t},be=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),ge=(e,t,a)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return v(e);throw new y(`${t} is ${g(e)} — a ${a} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:E.typeCheck})},we=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),je=e=>Array.isArray(e)?e.length>0:N(e)?Object.keys(e).length>0:null!=e,Pe=(e,t)=>{if(void 0===t)return e;const a=R(e,h(t));return a.found?void 0===a.value?null:a.value:null},$e=(e,t)=>{if(!N(e))throw new y("a row was not an object");const a=Object.values(e);if(1!==a.length)throw new y(`shape: '${t}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:E.typeCheck});return a[0]},ke={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},De={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},Oe=e=>P({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:De,timeout:ke},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:a})=>[...$(e,"returnPath"),...xe(t,a)],evaluate:async({url:t,method:a,query:r,body:n,headers:i,returnPath:o},s)=>{if("get"===a&&void 0!==n)throw new y("a GET carries no body — did you mean method: 'post'?",{code:E.typeCheck});const l={method:a,url:fe(t,r,s.options.http?.baseEndpoint),headers:ve(be(void 0!==n),s.options.http?.headers,i),...void 0!==n?{body:n}:{}},u=await s.cache.memo(we(l),()=>(Le(s,l),e.request({...l,signal:s.signal})));return Pe(u,o)}}),Ae=e=>P({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:De,timeout:ke},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>$(e,"returnPath"),evaluate:async({query:t,variables:a,url:r,headers:n,returnPath:i},o)=>{const s=r??o.options.graphQL?.endpoint;if(void 0===s)throw new y("no endpoint — supply url, or set the graphQL.endpoint option");const l={method:"post",url:fe(s,void 0,o.options.http?.baseEndpoint),headers:ve(be(!0),o.options.http?.headers,o.options.graphQL?.headers,n),body:{query:t,...je(a)?{variables:a}:{}}},u=await o.cache.memo(we(l),async()=>(Le(o,l),(e=>{if(!N(e))throw new y("the GraphQL response was not an object");const t=e.errors;if(Array.isArray(t)&&t.length>0){const e=t[0]?.message;throw new y(`the GraphQL response carried ${t.length} error${1===t.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:t}})}if(!("data"in e))throw new y("the GraphQL response carried neither data nor errors");return e.data??null})(await e.request({...l,signal:o.signal}))));return Pe(u,i)}}),qe=e=>P({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:ke},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:a,shape:r,noRowDefault:n},i)=>{const o={text:t,...je(a)?{values:a}:{}};return(async(e,t,a)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?a.evaluate():e[0];case"column":return e.map(e=>$e(e,"column"));case"firstValue":return 0===e.length?a.evaluate():$e(e[0],"firstValue")}})(await i.cache.memo(o,()=>(i.trace.note({type:"query",text:o.text}),e.query({...o,signal:i.signal}))),r,n)}}),xe=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],Ne=(e=new ue)=>[w(Oe(e)),w(Ae(e))],Ee=e=>[w(qe(e))],Le=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class Ce{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new y("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new y("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw se("postgres",e)}}}class Se{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new y("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw se("sqlite",e)}}}const Te=e=>Qe(e,0,new Set),Qe=(e,t,a)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Re(e);if(!Array.isArray(e)&&!z(e))return Fe(e);if(a.has(e))return"[circular]";if(t>=J)return"[too deep]";a.add(e);const r=Array.isArray(e)?Array.from(e,e=>Qe(e,t+1,a)):Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qe(r,t+1,a)]));return a.delete(e),r},Re=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},Fe=e=>{const t=ze(e);try{const a=e.toJSON;if("function"==typeof a){const r=a.call(e);if("string"==typeof r)return`[${t} ${r}]`}}catch{}return`[${t}]`},ze=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ge=e=>{const t=new Map;for(const a of e.holes)void 0!==a.timeoutFallback&&t.set(a.node,a.timeoutFallback);const a=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),r=e=>{const a=t.get(e);return void 0===a?{}:{timeoutFallback:Te(a.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:k(e.path)},i="vars"in e&&void 0!==e.vars?{vars:a(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Te(e.value)};case"reference":return{...t,kind:e.kind,reference:U(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...i,operator:e.name,params:a(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.hostDefaults?{}:{hostDefaults:Object.keys(e.entry.hostDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...i,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):a(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const a=O(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...i,shape:Te(a),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...i,entries:a(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Te(e.raw)}}};return n(e.root)},Je=(e,t)=>{const a=A(e,t);if(void 0===a)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:r,artifact:n,options:i}=a;return{version:q,expression:Te(r),options:Ve(i),canonicalForm:Ge(n),issues:x(n,i,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:n.timeoutShielded,nodeCount:n.nodeCount,maxDepth:n.maxDepth,dependencies:Ie(n.dependencies),own:{nodeCount:n.own.nodeCount,maxDepth:n.own.maxDepth,dependencies:Ie(n.own.dependencies)}}},Ue="[supplied]",Ve=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Me(e,t)])),Me=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Ue;case"http":case"graphQL":return Be(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Te(e));case"cache":return Be(t,"store",()=>Ue);default:return Te(t)}},Be=(e,t,a)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,r])=>[e,e===t?a(r):Te(r)])):Te(e),Ie=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{ce as AxiosClient,E as ErrorCodes,o as EvaluationData,ue as FetchClient,T as FigTreeError,a as OPERATOR_CATEGORIES,y as OperatorFailure,Ce as PostgresConnection,Se as SQLiteConnection,ie as defineOperator,Ne as httpOperators,Je as inspect,v as renderText,R as resolvePath,Ee as sqlOperators,q as version};
1
+ import{j as t,O as a,k as r,l as n,E as o,c as s,m as l,N as u,b as c,R as p,n as m,o as f,p as y,q as h,u as v,w as g,x as w,y as j,z as P,t as $,s as O,g as A,A as q,B as x}from"./chunks/engine.js";export{C as ARRAY,F as FigTree,D as OBJECT,G as compareValues,d as coreOperators,H as deepEqual,e as isOperatorFailure,i as isTruthy}from"./chunks/engine.js";import{a as N,E,l as L,R as S,F as T,m as Q,r as R,d as z,D as J,n as U}from"./chunks/shared.js";export{W as WILDCARD,b as isFigTreeError,k as parsePath}from"./chunks/shared.js";const V=/*#__PURE__*/new Set(["failures","external","output"]),M=/*#__PURE__*/new Set(["code","parameter","when","options","may","overflow"]),B=e=>{if(null===e||["string","number","boolean"].includes(typeof e))return!0;if(!N(e))return!1;const a=Object.keys(e);if(1!==a.length)return!1;const r=e[a[0]];switch(a[0]){case"type":return t(r);case"below":return"number"==typeof r&&Number.isFinite(r);case"empty":case"invalid":return!0===r;case"supplied":return"boolean"==typeof r;case"some":case"not":return B(r);default:return!1}},I=["param","elementOf","kindOf","typeNamedBy","firstNonNull","sum","product","abs","min","max"],Y=e=>void 0===e||"number"==typeof e&&Number.isFinite(e),K=e=>void 0===e||Number.isInteger(e)&&e>=0,X=(e,t,...a)=>t in e&&Object.keys(e).every(e=>e===t||a.includes(e)),Z=(e,a)=>{if(t(e))return!0;if(!N(e))return!1;const r=Object.keys(e);return 1===r.length&&I.includes(r[0])?a(e[r[0]]):"type"in e?(e=>{const{type:t,min:a,max:r,minLength:n}=e;return"number"===t||"integer"===t?X(e,"type","min","max")&&Y(a)&&Y(r)&&!(a>r):("string"===t||"array"===t)&&X(e,"type","minLength")&&K(n)})(e):X(e,"difference")?Array.isArray(e.difference)&&2===e.difference.length&&e.difference.every(a):X(e,"arrayOf","minLength")?K(e.minLength)&&Z(e.arrayOf,a):X(e,"oneOf")?Array.isArray(e.oneOf)&&e.oneOf.length>0&&e.oneOf.every(e=>Z(e,a)):!(!X(e,"byParam","cases","otherwise")||!("cases"in e))&&(a(e.byParam)&&N(e.cases)&&Object.values(e.cases).every(e=>Z(e,a))&&(void 0===e.otherwise||Z(e.otherwise,a)))},_=/[a-z]Default$/,ee=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),te=/*#__PURE__*/new Set(a),ae=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),re=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),ne=(e,t)=>{const[a]=e,r=e.length-1,n=r>0?`${a.message} (+ ${r} more issue${1===r?"":"s"})`:a.message;throw new T({code:E.invalidDefinition,message:n,path:a.path,...void 0!==t?{operator:t}:{},issues:e})};function ie(e){if(r(e))return e;const a=[],i=N(e)?e.name:void 0,d="string"==typeof i?i:void 0,y=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==d?{operator:d}:{},...void 0!==n?{parameter:n}:{}})};N(e)||(y(E.invalidDefinition,"a definition must be a plain object",[]),ne(a));const h=e;"string"!=typeof h.name&&y(E.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof h.description&&""!==h.description||y(E.invalidDefinition,"'description' is required and must be non-empty",["description"]),N(h.parameters)||y(E.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof h.evaluate&&y(E.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&ne(a,d),"string"!=typeof h.category?y(E.invalidDefinition,`'category' is required and must be one of ${[...te].join(", ")}`,["category"]):te.has(h.category)||y(E.invalidDefinition,`'${h.category}' is not a category — expected one of ${[...te].join(", ")}`,["category"]),void 0!==h.alias&&"string"!=typeof h.alias&&y(E.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==h.cache&&!0!==h.cache&&y(E.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===h.metadata||N(h.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===h.positionalParams||Array.isArray(h.positionalParams)&&!h.positionalParams.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==h.timeoutParam&&"string"!=typeof h.timeoutParam&&y(E.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==h.validate&&"function"!=typeof h.validate&&y(E.invalidDefinition,"'validate' must be a function",["validate"]),void 0===h.returns||t(h.returns)||y(E.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const v=(e,t,a)=>{e===o?y(E.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,a):Array.isArray(e)&&e.forEach((e,r)=>{e===o&&v(e,[...t,r],a)})};for(const[e,t]of Object.entries(h))"parameters"!==e&&"metadata"!==e&&v(t,[e]);const b=(e,t)=>{const a=L(e);a.ok?Q.has(e)&&y(E.reservedName,`'${e}' is a reserved name`,t):y(E.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof h.name&&b(h.name,["name"]),"string"==typeof h.alias&&b(h.alias,["alias"]);const g=h.parameters,w={};for(const[e,t]of Object.entries(g)){const a=["parameters",e],r=L(e);r.ok?S.has(e)&&y(E.reservedName,`'${e}' is a reserved node key and cannot name a parameter`,a,e):y(E.invalidName,`'${e}': ${r.reason}`,a,e),N(t)?w[e]=t:y(E.invalidDefinition,`the declaration for '${e}' must be a plain object`,a,e)}const j={};for(const[e,a]of Object.entries(w)){const r=["parameters",e],i=e=>[...r,e],d=a;for(const[t,a]of Object.entries(d))"default"!==t&&"metadata"!==t&&v(a,i(t),e);let p=!0;void 0===d.type||t(d.type)||(y(E.invalidDefinition,"'type' must be a metadata-vocabulary type",i("type"),e),p=!1),p&&(j[e]=d.type??"any");let m=!1;if(void 0!==d.constraints){const t=n(d.constraints);t.ok?m=!0:y(E.invalidDefinition,`'constraints' is malformed: expected ${t.expected}, got ${t.actual}`,i("constraints"),e)}void 0!==d.required&&"boolean"!=typeof d.required&&y(E.invalidDefinition,"'required' must be a boolean",i("required"),e),void 0!==d.description&&"string"!=typeof d.description&&y(E.invalidDefinition,"'description' must be a string",i("description"),e),void 0===d.metadata||N(d.metadata)||y(E.invalidDefinition,"'metadata' must be a plain object",i("metadata"),e);const f="default"in d;if(f&&!0===d.required&&y(E.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",i("default"),e),f&&d.default!==o){const t=j[e];if(void 0!==t){const a=s(d.default,t);if(a.ok){if(m&&void 0!==d.constraints){const t=l(d.default,d.constraints);t.ok||y(E.typeCheck,`'default' violates the declared constraints: expected ${t.expected}, got ${t.actual}`,i("default"),e)}}else y(E.typeCheck,`'default' does not satisfy the declared type: expected ${a.expected}, got ${a.actual}`,i("default"),e)}}if(void 0===d.evaluation||ee.has(d.evaluation)||y(E.invalidDefinition,`'evaluation' must be one of ${[...ee].join(", ")}`,i("evaluation"),e),void 0!==d.truthiness&&"boolean"!=typeof d.truthiness&&y(E.invalidDefinition,"'truthiness' must be a boolean",i("truthiness"),e),void 0!==d.over&&"string"!=typeof d.over&&y(E.invalidDefinition,"'over' must be a parameter name",i("over"),e),void 0===d.replacesNullAt||Array.isArray(d.replacesNullAt)&&!d.replacesNullAt.some(e=>"string"!=typeof e)||y(E.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",i("replacesNullAt"),e),void 0!==d.nullPolicy){const t=d.nullPolicy;"function"==typeof t||u.has(t)||y(E.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",i("nullPolicy"),e);const a=j[e];void 0===a||c(a)||y(E.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",i("nullPolicy"),e),!0===d.truthiness&&"propagate"===t&&y(E.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",i("nullPolicy"),e)}if(void 0!==d.elementNullPolicy){u.has(d.elementNullPolicy)||y(E.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",i("elementNullPolicy"),e);const t=j[e];void 0===t||re(t)||y(E.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",i("elementNullPolicy"),e)}}if(Array.isArray(h.positionalParams)&&h.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=h.positionalParams;t.forEach((a,r)=>{const n=a.startsWith(p),i=n?a.slice(p.length):a;n&&r!==t.length-1&&y(E.invalidDefinition,`the rest entry '${a}' must be the last positional entry`,["positionalParams",r]),i in w||y(E.invalidDefinition,`positional entry '${a}' names no declared parameter`,["positionalParams",r]),e.has(i)&&y(E.invalidDefinition,`duplicate positional entry '${a}'`,["positionalParams",r]),e.add(i)})}for(const[e,t]of Object.entries(w)){const a=["parameters",e],r="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(r){const r=t.over;if(r in w&&r!==e){const t=j[r];void 0===t||ae(t)||y(E.invalidDefinition,`the 'over' target '${r}' must admit an array`,[...a,"over"],e)}else y(E.invalidDefinition,`'over' names no sibling parameter ('${r}')`,[...a,"over"],e)}else y(E.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...a,"over"],e);else r&&y(E.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...a,"evaluation"],e)}for(const[e,t]of Object.entries(w)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const a=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&y(E.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",a,e);(t.required??!("default"in t))&&y(E.invalidDefinition,"a 'replacesNullAt' holder must be optional",a,e),"default"in t&&y(E.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",a,e),t.replacesNullAt.forEach((t,r)=>{t===e?y(E.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...a,r],e):t in w||y(E.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...a,r],e)})}for(const[e,t]of Object.entries(w))_.test(e)&&"lazy"!==t.evaluation&&y(E.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const P=m(w,j,y);if("string"==typeof h.timeoutParam){void 0===w[h.timeoutParam]?y(E.invalidDefinition,`'timeoutParam' names no declared parameter ('${h.timeoutParam}')`,["timeoutParam"]):"integer"!==j[h.timeoutParam]&&y(E.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return void 0!==h.analysis&&((e,t,a)=>{const r=(e,...t)=>a(E.invalidDefinition,e,["analysis",...t]);if(!N(e))return r("'analysis' must be a plain object");for(const t of Object.keys(e))V.has(t)||r(`'${t}' is not an analysis field`,t);const{failures:n,external:i,output:o}=e,s=e=>"string"==typeof e&&Object.hasOwn(t,e);if(void 0!==i&&!0!==i&&r("'external' must be the literal true","external"),void 0===o||Z(o,s)||r("'output' must be a type, or an output declaration naming declared parameters","output"),void 0!==n){if(!Array.isArray(n))return r("'failures' must be an array of rules","failures");!0===i&&r("an external operator declares no 'failures': it may fail whatever its inputs","failures"),n.forEach((e,t)=>{const a=(...e)=>["failures",t,...e];if(!N(e))return r("a rule must be a plain object",...a());for(const t of Object.keys(e))M.has(t)||r(`'${t}' is not a rule field`,...a(t));if("string"==typeof e.code&&""!==e.code||r("a rule's 'code' must be a non-empty string",...a("code")),void 0===e.parameter||s(e.parameter)||r("'parameter' names no declared parameter",...a("parameter")),void 0!==e.when)if(N(e.when))for(const[t,n]of Object.entries(e.when))s(t)?B(n)||r(`the test on '${t}' is malformed`,...a("when",t)):r(`'${t}' is not a declared parameter`,...a("when",t));else r("'when' must be an object of tests",...a("when"));void 0===e.options||N(e.options)||r("'options' must be a plain object",...a("options"));for(const t of["may","overflow"])void 0!==e[t]&&!0!==e[t]&&r(`'${t}' must be the literal true`,...a(t))})}})(h.analysis,w,(e,t,a)=>y(e,t,a)),a.length>0&&ne(a,d),f(h,P)}const oe=e=>new y(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),se=(e,t)=>{const a=t instanceof Error?t.message:String(t),r=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof r[e]&&(n[e]=r[e]);return new y(`${e}: ${a}`,{errorData:n})},le=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class ue{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new y("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,a=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),r=await a.text();if(!a.ok)throw oe({status:a.status,statusText:a.statusText,url:a.url||e.url,payload:pe(r)});return de(r,a.url||e.url,a.status)}}class ce{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new y("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw oe({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const de=(e,t,a)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new y(`response was not JSON (${a}): ${t}`,{errorData:{status:a,url:t,response:le(e)}})}},pe=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return le(e)}},me=/^https?:\/\//i,fe=(e,t,a)=>{const r=me.test(e)?e:ye(a,e),n=he(t),i=""===n?r:`${r}${r.includes("?")?"&":"?"}${n}`;try{new URL(i)}catch{throw new y(`'${i}' is not a valid URL`,{code:E.typeCheck})}return i},ye=(e,t)=>{if(void 0===e||""===e)throw new y(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:E.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},he=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[a,r]of Object.entries(e))null!=r&&t.append(a,ge(r,`query['${a}']`,"query"));return t.toString()},ve=(...e)=>{const t={};for(const a of e)if(void 0!==a)for(const[e,r]of Object.entries(a))null!=r?t[e]=ge(r,`headers['${e}']`,"header"):delete t[e];return t},be=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),ge=(e,t,a)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return v(e);throw new y(`${t} is ${g(e)} — a ${a} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:E.typeCheck})},we=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),je=e=>Array.isArray(e)?e.length>0:N(e)?Object.keys(e).length>0:null!=e,Pe=(e,t)=>{if(void 0===t)return e;const a=R(e,h(t));return a.found?void 0===a.value?null:a.value:null},$e=(e,t)=>{if(!N(e))throw new y("a row was not an object");const a=Object.values(e);if(1!==a.length)throw new y(`shape: '${t}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:E.typeCheck});return a[0]},ke={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},De={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},Oe=e=>j({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:De,timeout:ke},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:a})=>[...P(e,"returnPath"),...xe(t,a)],evaluate:async({url:t,method:a,query:r,body:n,headers:i,returnPath:o},s)=>{if("get"===a&&void 0!==n)throw new y("a GET carries no body — did you mean method: 'post'?",{code:E.typeCheck});const l={method:a,url:fe(t,r,s.options.http?.baseEndpoint),headers:ve(be(void 0!==n),s.options.http?.headers,i),...void 0!==n?{body:n}:{}},u=await s.cache.memo(we(l),()=>(Le(s,l),e.request({...l,signal:s.signal})));return Pe(u,o)}}),Ae=e=>j({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:De,timeout:ke},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>P(e,"returnPath"),evaluate:async({query:t,variables:a,url:r,headers:n,returnPath:i},o)=>{const s=r??o.options.graphQL?.endpoint;if(void 0===s)throw new y("no endpoint — supply url, or set the graphQL.endpoint option");const l={method:"post",url:fe(s,void 0,o.options.http?.baseEndpoint),headers:ve(be(!0),o.options.http?.headers,o.options.graphQL?.headers,n),body:{query:t,...je(a)?{variables:a}:{}}},u=await o.cache.memo(we(l),async()=>(Le(o,l),(e=>{if(!N(e))throw new y("the GraphQL response was not an object");const t=e.errors;if(Array.isArray(t)&&t.length>0){const e=t[0]?.message;throw new y(`the GraphQL response carried ${t.length} error${1===t.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:t}})}if(!("data"in e))throw new y("the GraphQL response carried neither data nor errors");return e.data??null})(await e.request({...l,signal:o.signal}))));return Pe(u,i)}}),qe=e=>j({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:ke},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:a,shape:r,noRowDefault:n},i)=>{const o={text:t,...je(a)?{values:a}:{}};return(async(e,t,a)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?a.evaluate():e[0];case"column":return e.map(e=>$e(e,"column"));case"firstValue":return 0===e.length?a.evaluate():$e(e[0],"firstValue")}})(await i.cache.memo(o,()=>(i.trace.note({type:"query",text:o.text}),e.query({...o,signal:i.signal}))),r,n)}}),xe=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],Ne=(e=new ue)=>[w(Oe(e)),w(Ae(e))],Ee=e=>[w(qe(e))],Le=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class Ce{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new y("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new y("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw se("postgres",e)}}}class Se{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new y("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw se("sqlite",e)}}}const Te=e=>Qe(e,0,new Set),Qe=(e,t,a)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Re(e);if(!Array.isArray(e)&&!z(e))return Fe(e);if(a.has(e))return"[circular]";if(t>=J)return"[too deep]";a.add(e);const r=Array.isArray(e)?Array.from(e,e=>Qe(e,t+1,a)):Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qe(r,t+1,a)]));return a.delete(e),r},Re=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},Fe=e=>{const t=ze(e);try{const a=e.toJSON;if("function"==typeof a){const r=a.call(e);if("string"==typeof r)return`[${t} ${r}]`}}catch{}return`[${t}]`},ze=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ge=e=>{const t=new Map;for(const a of e.holes)void 0!==a.timeoutFallback&&t.set(a.node,a.timeoutFallback);const a=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),r=e=>{const a=t.get(e);return void 0===a?{}:{timeoutFallback:Te(a.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:$(e.path)},i="vars"in e&&void 0!==e.vars?{vars:a(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Te(e.value)};case"reference":return{...t,kind:e.kind,reference:U(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...i,operator:e.name,params:a(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.hostDefaults?{}:{hostDefaults:Object.keys(e.entry.hostDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...i,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):a(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...r(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const a=O(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...i,shape:Te(a),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...i,entries:a(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Te(e.raw)}}};return n(e.root)},Je=(e,t)=>{const a=A(e,t);if(void 0===a)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:r,artifact:n,options:i}=a;return{version:q,expression:Te(r),options:Ve(i),canonicalForm:Ge(n),issues:x(n,i,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:n.timeoutShielded,nodeCount:n.nodeCount,maxDepth:n.maxDepth,dependencies:Ie(n.dependencies),own:{nodeCount:n.own.nodeCount,maxDepth:n.own.maxDepth,dependencies:Ie(n.own.dependencies)}}},Ue="[supplied]",Ve=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Me(e,t)])),Me=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Ue;case"http":case"graphQL":return Be(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Te(e));case"cache":return Be(t,"store",()=>Ue);default:return Te(t)}},Be=(e,t,a)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,r])=>[e,e===t?a(r):Te(r)])):Te(e),Ie=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{ce as AxiosClient,E as ErrorCodes,o as EvaluationData,ue as FetchClient,T as FigTreeError,a as OPERATOR_CATEGORIES,y as OperatorFailure,Ce as PostgresConnection,Se as SQLiteConnection,ie as defineOperator,Ne as httpOperators,Je as inspect,v as renderText,R as resolvePath,Ee as sqlOperators,q as version};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fig-tree-evaluator",
3
- "version": "3.0.0-preview.8",
3
+ "version": "3.0.0-preview.9",
4
4
  "description": "Module to evaluate JSON-structured expression trees",
5
5
  "type": "module",
6
6
  "main": "./build/index.js",