fig-tree-evaluator 3.0.0-preview.6 → 3.0.0-preview.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/authoring/index.d.ts +20 -3
- package/build/authoring/index.js +1 -1
- package/build/chunks/engine.js +1 -1
- package/build/chunks/shared.js +1 -1
- package/build/format/index.js +1 -1
- package/build/index.d.ts +98 -14
- package/build/index.js +1 -1
- package/build/migrate/index.js +1 -1
- package/package.json +4 -1
package/build/chunks/engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e,m as t,g as r,r as a,i as n,D as o,E as s,b as i,c as l,n as c,o as u,d,S as p,q as f,a as m,p as h,s as v,u as y,e as g,v as b,w,j as k,t as $,h as x,R as j,F as O,x as P,l 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"]),L=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},V=(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)},J=(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:W(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},W=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)&&L(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&&!L(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=V(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=J(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 J(e,t);const{length:a,...n}=t;if(void 0!==a){const t=J(e,{length:a});if(!t.ok)return t}return J(e.filter(e=>null!==e),n)},H=["logic","comparison","math","string","array","data","io","other"],Q=Symbol("fig-tree:EvaluationData"),X=Symbol("fig-tree:validated-operator"),Y=e=>"object"==typeof e&&null!==e&&!0===e[X],Z=[!1,null,0,""],_=e=>-1===Z.indexOf(e),ee=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:te(String(e),String(t)),te=(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},re="<array>",ae="<object>",ne=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?re:ae,oe=e=>e.trim(),se=/\s+$/,ie=/^\s+/,le=e=>e.replace(se,""),ce=e=>e.replace(ie,""),ue=e=>Array.from(e),de=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},pe=Object.prototype.hasOwnProperty,fe=(e,t)=>{for(const r of e.keys())if(me(r,t))return r},me=(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--&&me(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=fe(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=fe(t,n),!n))return!1;if(!me(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(pe.call(e,r)&&++a&&!pe.call(t,r))return!1;if(!(r in t)||!me(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},he=e=>!e.includes("{")&&!e.includes("}")&&(e.startsWith("$")?e.length>1:r(e).ok),ve=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(he(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},ye=(e,t)=>{const r={registry:t,maxDepth:0};return{constant:ge(r,e,0),depth:r.maxDepth}},ge=(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(!ge(e,t[a],r+1))return!1;return!0}if(n(t)){for(const r in t){if("operator"===r||"fragment"===r||"vars"===r||"//"===r)return!1;if(r.startsWith("$")&&be(e.registry,r.slice(1)))return!1}for(const a in t)if(!ge(e,t[a],r+1))return!1;return!0}return!0},be=(e,t)=>"literal"===t||void 0!==Dr(e,t)||e.fragments.has(t),we=(e,t)=>({parent:e,key:t}),ke=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},$e=e=>{e.sort((e,t)=>e.order-t.order)},xe=e=>e.some(({issue:e})=>"error"===e.severity),je=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},Oe=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,Pe=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=Ae(n,e.at,r[t],a)}),n},Ae=(e,t,r,a)=>{const n=De(e,a),[o,...s]=t;return n[o]=0===s.length?r:Ae(n[o],s,r,a),n},De=(e,t)=>{if(t.has(e))return e;const r=Array.isArray(e)?[...e]:{...e};return t.add(r),r},Se=/*#__PURE__*/new Set(["data","vars","params","element","index","d","v","p","e","i"]),Ce=(e,t,r={})=>{const a={registry:t,recognizes:e=>be(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(we,null),o=Ee(a,e,n,0);ze(a);const s=kt(a,o);$e(a.issues);const i=xe(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,...Ne(l,a.fragmentCalls,t.fragments),fragmentCalls:a.fragmentCalls,dataReads:a.dataReads,hasNoCache:a.hasNoCache}},Ne=(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]}}},ze=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`})},Te=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:ke(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},Ee=(e,t,r,a)=>{const n=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>o)return Te(e,"error",s.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Fe(t,r,n);const i=qe(e,t,r,a,n);return"operator"!==i.kind&&"fragmentCall"!==i.kind&&"reference"!==i.kind&&"invalid"!==i.kind||e.nodeCount++,i},qe=(e,t,r,a,o)=>null==t?Me(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Me(t,r,o):"string"==typeof t?Re(e,t,r,o):Array.isArray(t)?Ie(e,t,r,a,o):n(t)?Le(e,t,r,a,o):(e.identityOnly=!0,Me(t,r,o)),Me=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Fe=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),Re=(e,t,r,n)=>{const o=a(t,e.scope);switch(o.kind){case"plain":return Me(t,r,n);case"unrecognized":{const a=Te(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}),Me(t,r,n)}case"invalid":return Te(e,"error",o.code??s.invalidReference,`'${t}': ${o.reason}`,r,n),Fe(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:Ye(e,s,i.startsWith(".")?i.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:s,raw:t,path:r,order:n})}}},Ie=(e,t,r,a,n)=>{const o=t.map((t,n)=>({key:n,rawChild:void 0===t?null:t,node:Ee(e,void 0===t?null:t,we(r,n),a+1)})),s=t.some(e=>void 0===e);return wt(e,t,o,!0,s,void 0,r,n)},Le=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return Te(e,"error",s.malformedNode,o.message,r,n),Fe(t,r,n);case"operator":return Ve(e,t,r,a,n);case"fragment":return ft(e,t,r,a,n);case"shorthand":return st(e,t,o.key,r,a,n);case"plain":return gt(e,t,r,a,n)}},Ve=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return Te(e,"error",s.malformedNode,"the 'operator' value must be a literal string",r,n),Fe(t,r,n);if("literal"===o)return pt(e,t,t.value,"value"in t,r,n);const i=Dr(e.registry,o);if(void 0===i){const a=f(o,jt(e));return Te(e,"error",s.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Fe(t,r,n)}const l=Je(e,i,r,n),c=[];for(const o in t){const i=t[o];"operator"!==o&&"//"!==o&&void 0!==i&&(We(e,l,o,i,r,a,n)||("parameters"!==o?Ue(e,l,c,o,i,we(r,o),n):Te(e,"error",s.malformedNode,"'parameters' is reserved and unused on operator nodes",we(r,o),n,{operator:l.name})))}return Ke(e,l,c,a,n),l},Je=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),We=(e,t,r,a,n,o,s)=>"fallback"===r?(t.fallback=Ee(e,a,we(n,"fallback"),o+1),!0):"noCache"===r?(Be(e,t,a,n,s),!0):"vars"===r&&(t.vars=yt(e,a,n,o,s),!0),Be=(e,t,r,a,n)=>{!0===r?(t.noCache=!0,e.hasNoCache=!0):Te(e,"error",s.malformedNode,"'noCache' takes only the literal true — it is settled before the subtree runs",we(a,"noCache"),n,"operator"===t.kind?{operator:t.name}:{})},Ue=(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 Te(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})},Ke=(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=ot(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]=_e(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]=_e(e,n,r,a))}void 0!==i&&e.scope.bindings.pop()}Ze(e,t),Ge(e,t)},Ge=(e,t)=>{if("buildString"!==t.name)return;const r=t.params.template;if("constant"!==r?.kind||"string"!=typeof r.value)return;const a=ve(r.value).filter(e=>"text"!==e.kind);if(0===a.length)return;const o=t.params.substitutions,s=(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(Qe(e,t,r,a,s),"absent"!==s.mode&&"object"!==s.mode)return;const i=[],l=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(l.has(t.body))continue;const a=Re(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,l.add(t.body),i.push({path:r.path,at:[t.body],node:a}))}0!==i.length&&(t.params.substitutions=He(e,t,o,i))},He=(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??we(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},Qe=(e,t,r,a,n)=>{const o=(a,n)=>Te(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}${Xe(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,Xe(r))}},Xe=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`},Ye=(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})},Ze=(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);Ye(e,a,"string"==typeof r.value?r.value:void 0,t.path)}catch{e.dynamic=!0}else e.dynamic=!0},_e=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=at(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=nt(e,t,a);if(null!==r)return r}return"value"===t.kind?Ee(e,t.value,t.path,a+1):et(e,t,a)},et=(e,t,r)=>{const{order:a,containerDepth:n}=tt(e,r),o=rt(e,t.elements,t.basePath,t.offset,n),s=t.elements.some(e=>void 0===e);return wt(e,t.elements,o,!0,s,void 0,t.basePath,a)},tt=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},rt=(e,t,r,a,n)=>t.map((t,o)=>({key:o,rawChild:void 0===t?null:t,node:Ee(e,void 0===t?null:t,we(r,a+o),n+1)})),at=(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}=tt(e,r),l=rt(e,a,n,o,i);if(l.every(e=>"constant"===e.node.kind)){const t=a.some(e=>void 0===e);return wt(e,a,l,!0,t,void 0,n,s)}return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:s}},nt=(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}=tt(e,r),{entries:i,vars:l,changed:c}=bt(e,a,t.path,s,o);if(i.every(e=>"constant"===e.node.kind))return wt(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},ot=(e,t,n,o,i)=>{const l=r=>{Te(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(Se.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},st=(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 Te(e,"error",s.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,we(a,n),o),Fe(t,a,o);const u=t[r],d=we(a,r);if(l){for(const r of["fallback","vars","noCache"])r in t&&Te(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,we(a,r),o);return pt(e,t,u,!0,a,o)}if(c)return mt(e,t,i,u,a,n,o);const f=Dr(e.registry,i),m=Je(e,f,a,o);for(const s in t){const i=t[s];s!==r&&"//"!==s&&void 0!==i&&We(e,m,s,i,a,n,o)}const h=[];return it(e,m,h,u,d,o),Ke(e,m,h,n,o),m},it=(e,t,r,a,o,s)=>{if(Array.isArray(a))ct(e,t,r,a,o,s);else if(!n(a)||m(a,e.recognizes))lt(e,t,r,a,o,s);else for(const n in a){const i=a[n];"//"!==n&&void 0!==i&&Ue(e,t,r,n,i,we(o,n),s)}},lt=(e,t,r,a,n,o)=>{const s=v(t.entry.definition);null!==s?r.push({name:s,kind:"value",value:a,path:n}):ut(e,t,n,o)},ct=(e,t,r,a,n,o)=>{const s=t.entry.definition,i=h(s,a.length);if(null===i)return void dt(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:we(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})},ut=(e,t,r,a)=>Te(e,"error",s.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),dt=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void ut(e,t,a,n);const i=o.length;Te(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})},pt=(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?Te(e,"error",s.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,we(n,r),o,{operator:"literal"}):Te(e,"warning",s.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,we(n,r),o));if(!a)return Te(e,"error",s.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Fe(t,n,o)}return Me(r,n,o)},ft=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return Te(e,"error",s.malformedNode,"the 'fragment' value must be a literal string",r,n),Fe(t,r,n);const i={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};ht(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?Te(e,"error",s.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,we(r,o),n):Be(e,i,l,r,n):i.vars=yt(e,l,r,a,n):i.fallback=Ee(e,l,we(r,"fallback"),a+1):vt(e,i,l,we(r,"parameters"),a,n))}return i},mt=(e,t,r,a,o,i,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};ht(e,c,i);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=Ee(e,n,we(o,"fallback"),i+1)),"noCache"===a&&Be(e,c,n,o,l),"vars"===a&&(c.vars=yt(e,n,o,i,l)))}return n(a)?vt(e,c,a,we(o,`$${r}`),i,l):Te(e,"error",s.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,we(o,`$${r}`),l),c},ht=(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 Te(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})},vt=(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=Ee(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]=Ee(e,n,we(o,t),i+1))}return void(t.parameters=a)}Te(e,"error",s.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},yt=(e,t,a,o,i)=>{const l=we(a,"vars");if(!n(t))return void Te(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=we(l,a),d=r(a);d.ok?c[a]=Ee(e,n,u,o+1):Te(e,"error",s.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,i)}return c},gt=(e,t,r,a,n)=>{const{entries:o,vars:s,changed:i}=bt(e,t,r,a,n);return wt(e,t,o,!1,i,s,r,n)},bt=(e,t,r,a,n)=>{let o,i=!1;const l=[];for(const c in t){const u=t[c];if("//"!==c)if("vars"!==c)if(void 0!==u){if(c.startsWith("$")){const t=f(c.slice(1),jt(e));Te(e,"warning",s.unrecognizedIdentifier,`'${c}' is not a registered operator or fragment and will pass through as data${t?` — did you mean '$${t}'?`:""}`,we(r,c),n,{suggestion:void 0===t?void 0:`$${t}`})}l.push({key:c,rawChild:u,node:Ee(e,u,we(r,c),a+1)})}else i=!0;else o=yt(e,u,r,a,n),i=!0;else i=!0}return{entries:l,vars:o,changed:i}},wt=(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}):(u[e]=a.skeleton,c.push(...a.holes.map(t=>({...t,at:[e,...t.at]}))))):(u[e]=a.value,a.value!==t&&(d=!0));if(0===c.length)return void 0!==o&&Object.keys(o).length>0&&Te(e,"warning",s.unreferencedVar,"this vars block declares names nothing in its scope references",we(i,"vars"),l),Me(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},kt=(e,t)=>"constant"===t.kind?[]:"skeleton"===t.kind?t.holes.map(t=>({node:t.node,...$t(e,t.node)})):[{node:t,...$t(e,t)}],$t=(e,t)=>{const r=xt(e,t);return void 0===r?{}:{timeoutFallback:r}},xt=(e,t)=>{if("operator"===t.kind||"fragmentCall"===t.kind){if(void 0!==t.fallback)return"constant"===t.fallback.kind?{value:t.fallback.value}:void 0;if("operator"===t.kind){const r=t.entry.instanceDefaults;return void 0!==r&&"fallback"in r&&ye(r.fallback,e.registry).constant?{value:r.fallback}:void 0}return t.entry?.timeoutFallback}},jt=e=>[...e.registry.operators.keys(),...e.registry.aliases.keys(),...e.registry.fragments.keys()],Ot=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 Pt(e.value);default:return"any"}},Pt=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"}},At=/*#__PURE__*/Object.freeze({parsePath:g,resolvePath:k,checkType:V,checkConstraints:J,describeType:q,renderText:ne,isTruthy:_}),Dt=(e,t={})=>{Ct({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),$e(e.issues),e.hasErrors=xe(e.issues)},St=(e,t,r,a,n,o,s={})=>{const i={severity:t,code:r,message:a,path:ke(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})},Ct=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Vt(e,t);case"skeleton":{const r=Ut(e,t.vars,t.path);for(const r of t.holes)Ct(e,r.node);return void Kt(e,r)}case"fragmentCall":return void It(e,t);case"elements":for(const r of t.nodes)Ct(e,r);return;case"entries":{const r=Ut(e,t.vars,t.path);for(const r in t.entries)Ct(e,t.entries[r]);return void Kt(e,r)}case"operator":return void zt(e,t)}return t},Nt=e=>"kind"in e&&"string"==typeof e.kind,zt=(e,t)=>{const r=Ut(e,t.vars,t.path);void 0!==t.fallback&&Ct(e,t.fallback);const a=t.entry.definition,n=Rt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?Et(e,n,r,o,a,Tt(t,r)):o.required&&St(e,"error",s.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}Lt(e,t);const o=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?o.push([r,n]):Ct(e,n)}if(o.length>0){const r={as:je(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)Ct(e,t);e.iteratorFrames.pop(),r.referenced||St(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})}Kt(e,r)},Tt=(e,t)=>{const{definition:r,instanceDefaults: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},Et=(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&&St(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 St(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=Mt(a,n,o);void 0!==l&&St(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&&qt(e,t,r,a,c,o));const l=Mt(a,n,o);void 0!==l&&St(e,"warning",s.fallbackMismatch,`this fallback can never satisfy ${i}: ${l.reason}`,n.path,n.order,{...t.extra,parameter:r}),c=n}},qt=(e,t,r,a,n,o)=>{const i=n.entry.instanceDefaults;if(void 0===i||!Object.hasOwn(i,"fallback"))return;const l=Ft(a,i.fallback,o);void 0!==l&&St(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})},Mt=(e,t,r)=>{switch(t.kind){case"constant":return Ft(e,t.value,r);case"operator":case"fragmentCall":{if("fragmentCall"===t.kind&&void 0===t.entry)return;const r=Ot(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=V(Array.isArray(t.skeleton)?[]:{},e.type);return r.ok?void 0:{code:s.typeCheck,reason:`expected ${r.expected}, received ${r.actual}`}}default:return}},Ft=(e,t,r)=>{if(null===t&&(r||!e.required&&!R(e.type)))return;const a=V(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}`}},Rt=e=>({label:e.name,extra:{operator:e.name}}),It=(e,t)=>{const r=Ut(e,t.vars,t.path);void 0!==t.fallback&&Ct(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||Nt(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?Et(e,r,o,i,l):i.required&&St(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));St(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(Nt(t.parameters))Ct(e,t.parameters);else for(const r in t.parameters)Ct(e,t.parameters[r]);Kt(e,r)},Lt=(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,At)}catch(r){return void St(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;St(e,r.severity,s.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Vt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Jt(e,t);case"params":return void Wt(e,t);case"element":case"index":return void Bt(e,t,t.namespace)}},Jt=(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}}St(e,"error",s.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},Wt=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void St(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)||St(e,"error",s.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Bt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Oe(n.as,r,t.binding))return void(n.referenced=!0)}St(e,"error",s.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Ut=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=we(r,"vars");for(const r in t){const o=t[r],i=we(n,r);for(const t of e.varsFrames)if(t.names.has(r)){St(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,Ct(e,r.node),a.currentVar=null;return a},Kt=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||St(e,"warning",s.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Gt(e,t)}},Gt=(e,t)=>{const r=new Set,a=new Set,n=new Set,o=e=>{if(a.has(e))return!1;if(r.has(e))return!0;r.add(e);for(const n of t.edges.get(e)??[])if(o(n))return r.delete(e),a.add(e),!0;return r.delete(e),a.add(e),!1};for(const r of t.names.keys())if(!a.has(r)&&!n.has(r)&&o(r)){const a=t.names.get(r);St(e,"error",s.varCycle,`'${r}' participates in a vars cycle — a var may not depend on itself`,a.declaredAt,a.order),n.add(r)}},Ht={capable:!1,effective:!1,disabled:[]},Qt={capable:!0,effective:!0,disabled:[]},Xt=e=>{const{effective:t}=Yt(e,e.root,!1);return $e(e.issues),t},Yt=(e,t,r)=>{switch(t.kind){case"constant":case"reference":return Ht;case"invalid":return Qt;case"skeleton":return rr(e,[...t.holes.map(e=>e.node),...ar(t.vars)],r);case"elements":return rr(e,t.nodes,r);case"entries":return rr(e,[...Object.values(t.entries),...ar(t.vars)],r);case"operator":return Zt(e,t,jr(t.entry),r);case"fragmentCall":return Zt(e,t,t.entry?.caches??!0,r)}return t},Zt=(e,t,r,a)=>{const n=!0===t.noCache,o=rr(e,tr(t),a||n),s=r||o.capable,i=_t(t),l=void 0===i?o.disabled:[i,...o.disabled];return n&&a?nr(e,t,"'noCache' is redundant — an enclosing node already sets it"):n&&!s&&nr(e,t,l.length>0?`'noCache' is redundant — caching is already disabled for ${er(l)}`:"'noCache' is dead — nothing beneath this node caches"),{capable:s,effective:!n&&(r||o.effective),disabled:l}},_t=e=>"operator"===e.kind&&e.entry.definition.cache&&!jr(e.entry)?e.entry.definition.name:void 0,er=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]}`},tr=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(...ar(e.vars)),t},rr=(e,t,r)=>{const a={capable:!1,effective:!1,disabled:[]};for(const n of t){const{capable:t,effective:o,disabled:s}=Yt(e,n,r);a.capable||=t,a.effective||=o,a.disabled.push(...s)}return a},ar=e=>void 0===e?[]:Object.values(e),nr=(e,t,r)=>{const a={severity:"warning",code:s.uselessModifier,message:r,path:ke(we(t.path,"noCache"))};"operator"===t.kind?a.operator=t.name:a.fragment=t.name,e.issues.push({issue:a,order:t.order})};class or{max;entries=new Map;constructor(e){this.max=e,sr(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(sr(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 sr=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},ir=Symbol("fig-tree:lazy-handle"),lr="~",cr=(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=cr(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=cr(e[r],t+1);if("json"!==a)return a}return"json"},ur=(e,t)=>dr(e,0,t)?t.join(""):void 0,dr=(e,t,r)=>{if(t>o)return!1;if(null===e)return fr(r,"n");if(void 0===e)return fr(r,"u");switch(typeof e){case"boolean":return fr(r,e?"t":"f");case"number":return pr(e,r);case"string":return fr(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!dr(a,t+1,r))return!1;return fr(r,"]")}if(!n(e)||ir in e)return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!dr(e[a],t+1,r))return!1;return fr(r,"}")},pr=(e,t)=>Number.isNaN(e)?fr(t,"N"):e===1/0?fr(t,"I"):e===-1/0?fr(t,"J"):Object.is(e,-0)?fr(t,"#-0"):fr(t,`#${String(e)}`),fr=(e,t)=>(e.push(t),!0);class mr{deps;identity=new WeakMap;content=new or(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=cr(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?ur(e,[lr]):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 hr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),vr=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),yr=(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))vr.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=gr(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},gr=(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))hr.has(e)||o(s.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...i,e]);const c=a.type??"any";if(!L(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=V(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=J(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},br=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=Ot(n),t.delete(e.name),r.add(e.name)};for(const t of e.fragments.values())a(t)},wr=(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},kr=(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=Ne(s.own,s.fragmentCalls,e.fragments);o.nodeCount=i.nodeCount,o.maxDepth=i.maxDepth,o.dependencies=i.dependencies,o.identityOnly=i.identityOnly,o.caches=Xt(s),o.timeoutFallback=$r(s,e.fragments)};for(const e of t.keys())a(e)},$r=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=xr(e,t);if(void 0===r)return;n.push(r.value)}return"skeleton"===r.kind?{value:Pe(r.skeleton,r.holes,n)}:{value:n[0]}},xr=(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},jr=e=>e.definition.cache&&!0!==e.instanceDefaults?.noCache,Or=["fallback","noCache"],Pr=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(!Y(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&&Ar(t.operatorDefaults,o,i,a),((t,r,a,n,o)=>{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=yr(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const i=new Map;for(const[e,a]of r.fragments){const n=t[e],o=Ce(n.expression,r,{basePath:["expression"]});a.body=o.root,i.set(e,o)}br(r);for(const[e,t]of r.fragments){const r=i.get(e);Dt(r,{fragmentParams:new Set(Object.keys(t.parameters))});for(const{issue:t}of r.issues){const r=t.path[t.path.length-1],a=t.code===s.unrecognizedIdentifier&&o?.has(r);("error"===t.severity||a)&&n(a?s.unknownFragment:t.code,a?`fragment '${e}' calls '${r.slice(1)}', which this update removes`:`fragment '${e}': ${t.message}`,["fragments",e,...t.path])}}wr(i,n)&&kr(r,i);for(const[e,t]of r.fragments)for(const{issue:r}of i.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,t.removedFragments),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},Ar=(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(Or.includes(e)){"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=V(r,i.type);if(u.ok){if(void 0!==i.constraints){const t=J(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.instanceDefaults=Object.freeze({...i}))}else n(s.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},Dr=(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},Sr="fig-tree:scope-settled",Cr="fig-tree:request-expired",Nr="fig-tree:evaluation-timeout";class zr{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?Sr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(Sr);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(Sr)))}}const Tr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:P}),Er=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(Sr)}})():(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(Sr)}}})(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()}}},qr=(e,t)=>Er(e,t,Cr),Mr=(e,t)=>(r,a)=>{const n=(o=[e.operator,e.fingerprint,r],ur(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)},Fr=/*#__PURE__*/Object.freeze({}),Rr=(e,t)=>!0!==t||!0===e.noCache?e:{...e,noCache:t};class Ir{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 Lr={memo:(e,t)=>t()},Vr={note:P},Jr=Symbol("fig-tree:internal-error"),Wr=e=>Zr(`[fig-tree internal] ${e}`,Jr),Br=e=>ea(e,Jr),Ur=Symbol("fig-tree:cancelled"),Kr=()=>Zr("[fig-tree] evaluation cancelled",Ur),Gr=e=>ea(e,Ur),Hr=(e,t,r)=>e.rootScope.aborted?Qr(e.rootScope.reason,t,r):e.abortScope.aborted?Kr():void 0,Qr=(e,t,r)=>e===Sr?Kr():Xr(e,ke(t),{operator:r}),Xr=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===Nr,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}:{}})},Yr=e=>A(e)&&(e.code===s.aborted||e.code===s.timeout),Zr=(e,t)=>{const r=new Error(e);return _r(r,t),r},_r=(e,t)=>{e[t]=!0},ea=(e,t)=>e instanceof Error&&!0===e[t],ta=()=>performance.now(),ra=e=>{const t=new Map,r=new WeakMap;let a;const n=(e,r,a)=>{const n=t.get(e);if(void 0===n)return;t.delete(e),"fallback"!==e.status&&(e.status=r),void 0!==a.error&&void 0===e.error&&(e.error=a.error),"failed"!==r&&"cancelled"!==r&&(e.value=a.value),void 0!==a.elapsed&&(e.elapsed=a.elapsed);const o=[...n.children,...aa(n)];o.length>0&&(e.children=o.sort((e,t)=>e.order-t.order||e.index-t.index).map(e=>e.entry))},o=(e,t)=>{(e.events??=[]).push(t)};return{enter:(e,n,o,s)=>{const i=ca(e),l=ua(e),c={path:ke(e.path),kind:la(e),status:"value",...void 0!==o?{source:{fragment:o.fragment}}:{},...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}),r.set(e,c),((e,r,n)=>{if(void 0===e)return void(a=r.entry);const o=t.get(e);void 0!==o&&(o.children.push(r),o.seen.add(n))})(n,{entry:c,order:e.order,index:s?.index??0},e),c},settle:n,markFallback:(e,t)=>{e.status="fallback",e.error=t},note:o,noteOn:(e,t)=>{const a=r.get(e);void 0!==a&&o(a,t)},finish:()=>{for(const e of[...t.keys()].reverse())n(e,"cancelled",{});return void 0!==a&&e.length>0&&(a.warnings=e),a}}},aa=e=>na(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:ke(e.path),kind:la(e),status:"skipped"},order:e.order,index:0})),na=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(oa),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...sa(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[]}},oa=e=>"elements"===e.kind||"entries"===e.kind?na(e):[e],sa=e=>void 0===e?[]:ia(e)?[e]:Object.values(e),ia=e=>"string"==typeof e.kind,la=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},ca=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,ua=e=>"reference"===e.kind?e.raw:void 0,da=(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(()=>Za(n,a,{var:e})));return a},pa=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await ma(e,t,a):fa(e,t,a),frame:n};delete o.scope,delete o.bindings;const s=await Za(t.body,o);return void 0===s?null:s},fa=(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 ha(e,o,s,r);let a;try{a=await Za(t,r)}catch(e){throw wa(e,r.frame)}return va(e,o,s,a,t.path,r)});n.set(o,()=>{const e=i();return e.catch(P),e})}return n},ma=async(t,r,a)=>{const n=t.parameters;let o;try{o=await Za(n,a)}catch(e){throw wa(e,a.frame)}if(!e(o))throw wa(ya(t,s.typeCheck,`'parameters' must evaluate to an object, received ${ga(o)}`,n.path),a.frame);const i=new Map;for(const[e,s]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?va(t,e,s,o[e],n.path,a):ha(t,e,s,a,n.path);i.set(e,()=>Promise.resolve(r))}return i},ha=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw wa(ya(e,s.missingRequired,`requires '${t}'`,n),a.frame)},va=(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=V(i,r.type);if(!l.ok)throw wa(ya(e,s.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=J(i,r.constraints);if(!a.ok)throw wa(ya(e,s.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return i},ya=(e,t,r,a)=>new O({code:t,message:`fragment '${e.name}' – ${r}`,path:ke(a)}),ga=e=>null===e?"null":Array.isArray(e)?"array":typeof e,ba=Symbol("fig-tree:anchored"),wa=(e,t)=>!A(e)||ea(e,ba)?e:(_r(e,ba),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=ke(t.callPath)),e);class ka 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 $a=e=>e instanceof ka,xa=(e,t,r)=>Oa(Array.from({length:e},(e,a)=>ja(a,()=>t(a),r)),e),ja=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},Oa=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[ir]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},Pa=e=>({[ir]:!0,evaluate:D(e)}),Aa=e=>({[ir]:!0,evaluate:()=>Promise.resolve(e)}),Da=(e,t,r,a,n)=>Pa(async()=>Sa(await Za(e,n),t,r,a)),Sa=(e,t,r,a)=>{const n=V(e,a.type);if(!n.ok)throw Ea(t,r,n);if(null!==e&&void 0!==a.constraints){const n=G(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw Ea(t,r,n)}return a.truthiness?Ra(e,a.type):e},Ca=(e,t,r,a,n,o)=>{const s=Array.isArray(t)?t:[],i=je(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>Sa(await Za(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{[ir]:!0,evaluate:c,settle:()=>xa(s.length,c,e=>e)}},Na=(e,t)=>t.truthiness?_(e):e,za=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>Pa(async()=>Na(await Za(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>xa(e.length,r=>Za(e[r],t,{index:r}),r))(e.nodes,r,e=>Na(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=da(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=Pa(async()=>Na(await Za(o,a),t));return n}},Ta=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>Aa(Na(e,t)));case"race":return((e,t)=>xa(e.length,t=>Promise.resolve(e[t]),t))(e,e=>Na(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=Aa(Na(n,t));return r}case"lazy":return Aa(e);default:return e}},Ea=(e,t,r)=>new O({code:s.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:ke(e.path),operator:e.name}),qa=(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=V(o,n.type);if(!s.ok)throw Ea(e,a.selector,s);const i=a.table.find(e=>e.value===o);if(void 0===i)throw Wr(`no null-policy row for ${e.name}.${a.selector}`);return i.policy},Ma=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},Fa=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),Ra=(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(_);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=_(a);return e}}return _(t)},Ia=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,instanceDefaults: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(Za(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(()=>Za(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]=Da(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=za(n,o,t);if(void 0!==e){d[r]=e;break}i.push(r),l.push(Za(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===Q?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 Ma(a,r,n));const o="eager"!==r.evaluation&&"structural"!==r.evaluation;if(null===a&&R(r.type)&&!o&&"propagate"===qa(e,r,c))return{params:d,propagate:!0};if("propagate"===r.elementNullPolicy&&Fa(a))return{params:d,propagate:!0};a=Sa(a,e,t,r),d[t]=Ta(a,r)}for(const[r,a]of s){if(void 0===a.over)throw Wr(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=Ca(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&&jr(e.entry),s=Va(n,r),i=void 0===s?void 0:qr(t.abortScope.signal,s),l=void 0===i?t:{...t,abortScope:Tr(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 Ir(e.abortScope,e.options,r?{memo:Mr({operator:t.name,fingerprint:t.fingerprint,note:a},e.cache)}:Lr,void 0===a?Vr:{note:a}))(l,n,o,c);try{return await La(e,t,r,u,i)}catch(r){throw Ja(r,e,t,i,s)}finally{i?.settle()}},La=async(e,t,r,a,n)=>{const o=Hr(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?Ba(await s,e):(s.catch(P),Ba(await Promise.race([s,n.expiry]),e))},Va=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},Ja=(e,t,r,a,n)=>{if(Br(e)||Gr(e))return e;const o=Hr(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===Cr?new ka(`request exceeded its ${String(n)}ms timeout`,{code:s.requestTimeout}):e},Wa=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>Za(r,t);const a=e.entry.instanceDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Ba=(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:ke(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[ir])throw new O({code:s.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:ke(t.path),operator:t.name});var r;return e},Ua=(e,t)=>{if(A(e))return e;if($a(e))return new O({code:e.code??s.operatorFailure,message:`${t.name} – ${e.message}`,path:ke(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:ke(t.path),operator:t.name})},Ka=(e,t)=>0===e.segments.length?t.data:Xa(t.data,e.segments,e,t,"is absent from the evaluation data"),Ga=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 Wr(`'${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?Ya(o):Xa(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Ha=async(e,t)=>{const r=t.params;if(void 0===r)throw Wr(`'${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]=Ya(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Wr(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const s=await o();return 0===n.length?Ya(s):Xa(s,n,e,t,`is absent from the value of '$params.${String(a)}'`)},Qa=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Oe(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Wr(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?Ya(a.element):Xa(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Xa=(e,t,r,a,n)=>{const o=k(e,t);if(o.found)return Ya(o.value);if(!a.strictDataPaths)return null;throw new O({code:s.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:ke(r.path)})},Ya=e=>void 0===e?null:e,Za=(e,t,r)=>void 0!==t.trace?_a(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(Hr(t,e.path)):en(e,t),_a=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=ta();try{if(t.abortScope.aborted)throw Hr(t,e.path);const a=await en(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:ta()-o}),a}catch(e){throw r.settle(n,Gr(e)?"cancelled":"failed",{...A(e)?{error:e}:{},elapsed:ta()-o}),e}},en=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Ka(e,t);case"vars":return Ga(e,t);case"params":return Ha(e,t);case"element":case"index":return Qa(e,t)}})(e,t);case"skeleton":return tn(e,t);case"operator":return(async(e,t)=>{const r=da(Rr(t,e.noCache),e.vars),a=e.entry.definition.deliversLazily?new zr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await Ia(e,n)}finally{a?.settle()}}catch(a){if(Br(a)||Gr(a)||Yr(a))throw a;const n=Ua(a,e),o=Wa(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(Br(t)||Gr(t)||Yr(t))throw t;const r=Ua(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 Wr(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=da(Rr(t,e.noCache),e.vars),n=new zr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},s={...a,abortScope:n};try{try{return await pa(e,r,s,a,o)}finally{n.settle()}}catch(r){if(Br(r)||Gr(r)||Yr(r))throw r;const n=wa(r,o),{fallback:s}=e;if(void 0===s)throw n;try{return await Za(s,a)}catch(e){if(Br(e)||Gr(e)||Yr(e))throw e;const r=wa(e,t.frame);throw A(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Wr(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Wr("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},tn=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=da(a,e.vars),o=e.holes.map(e=>void 0===r?Za(e.node,n):r(()=>Za(e.node,n),e.node)),s=o.some(S)?await Promise.all(o):o;return Pe(e.skeleton,e.holes,s)},rn=async(e,t,r)=>{const{timeout:a,signal:n}=t,o=e.holes.length>0,s=void 0!==a||void 0!==n?Er(n,a,Nr):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 zr(void 0),l=void 0!==s&&void 0!==a&&e.timeoutShielded&&o,c=!0===t.trace?ra(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,u=((e,t,r,a)=>({options:e,data:e.data??Fr,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,...void 0!==a?{trace:a}:{}}))(t,r,i,c),d=l?nn(e,s.expiry,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 Xr(i.reason,[]);const t=()=>p&&void 0!==d?d(()=>Za(e.root,f),e.root):Za(e.root,f),r=await(l||void 0===s?t():an(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()}},an=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Xr(e,[],{ms:r})})]),nn=(e,t,r)=>{const a=new Map(e.holes.map(e=>[e.node,e]));return(e,n)=>{const o=a.get(n);if(void 0===o)throw Wr(`the hole boundary was handed the node at ${JSON.stringify(ke(n.path))}, which is not one of the artifact's holes`);let s=!1;const i=Promise.resolve(e()).then(e=>(s=!0,e));return Promise.race([i,t.catch(e=>{if(e!==Nr)throw Xr(e,[]);if(!s)return r?.noteOn(o.node,{type:"shielded-fallback"}),on(o)})])}},on=e=>{if(void 0===e.timeoutFallback)throw Wr("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},sn={hit:!1},ln=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw un("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!cn(t))throw un("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw un("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw un("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},cn=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),un=e=>new O({code:s.invalidOptions,message:e,path:[]});class dn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new or(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 sn}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||pn(t)?(this.drop(e),sn):{hit:!0,value:t.value}:sn;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 pn=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),fn=e=>e===C?0:"number"==typeof e?1:2,mn=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=fn(r)-fn(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]}),hn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e)){const e={...n};void 0!==t&&Object.hasOwn(t,a)&&(e.instanceDefault=t[a]),r[a]=e}return r},vn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(yn(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},yn=(e,t)=>({severity:"error",code:s.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),gn=(e,t,r)=>{const a=[...vn(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...bn(e.dataReads,t.data)),a},bn=(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:ke(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},wn="...",kn=/*#__PURE__*/new Set(["propagate","value"]),$n=e=>e,xn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=jn(e.parameters,t,(t,r,a)=>{throw new O({code:t,message:r,path:a,operator:e.name})});return On(e,r)},jn=(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||!kn.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},On=(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:An(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=Dn(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(wn)?a.slice(3):null,o={[X]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:Sn(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?An(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),o.fingerprint=Pn(o),Cn(o)},Pn=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)),An=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],Dn=t=>{if(Array.isArray(t))return t.map(Dn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=Dn(a);return e}return t},Sn=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)}},Cn=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&&Nn(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)},Nn=t=>{Array.isArray(t)?(t.forEach(Nn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(Nn),Object.freeze(t))},zn=e=>{if(Array.isArray(e))return e;try{return g(e)}catch(e){throw new ka(e.message)}},Tn=(e,t)=>{if("string"!=typeof e)return[];try{return g(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},En=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"}]:[],qn=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`}]:[]},Mn=/*#__PURE__*/qn("values"),Fn=/*#__PURE__*/qn("input"),Rn=/*#__PURE__*/qn("entries"),In=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"}]:[],Ln=(e,t)=>new ka(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:s.emptyAggregate}),Vn=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),Jn(r);return!t},Jn=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},Wn=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)},Bn=(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=>me(r(e),a))},Un={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)"}},Kn={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:Un,positionalParams:["...values"],returns:"boolean",validate:In,evaluate:({values:e,caseInsensitive:t})=>Bn(e,t)},Gn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:Un,positionalParams:["...values"],returns:"boolean",validate:In,evaluate:({values:e,caseInsensitive:t})=>!Bn(e,t)},Hn=(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(ee(t,r))}}),Qn=/*#__PURE__*/Hn("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),Xn=/*#__PURE__*/Hn("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),Yn=/*#__PURE__*/Hn("lessThan","<","Is the first value strictly less than the second?",e=>e<0),Zn=/*#__PURE__*/Hn("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),_n={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},eo=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,to={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?Mn({values:e}):En({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw Ln("the sum","pin the mode with 'expect' to get its identity");return _n[t]()}const r=t??eo(e[0]),a=e.find(e=>eo(e)!==r);if(void 0!==a)throw n=`all operands must be ${r}s — received ${q(a)}`,new ka(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)}}},ro={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},ao={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},no={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},oo={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:Mn,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},so={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},io={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(de(Math.abs(e),t));return r*de(a,-t)})(e,t)},lo=(e,t,r,a)=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"],description:r}},positionalParams:["value"],returns:"number",evaluate:({value:e})=>a(e)}),co=/*#__PURE__*/lo("floor","Round down toward negative infinity","The number to round down",Math.floor),uo=/*#__PURE__*/lo("ceil","Round up toward positive infinity","The number to round up",Math.ceil),po=/*#__PURE__*/lo("abs","The absolute value","The number",Math.abs),fo=(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:En,evaluate:({values:e})=>{const r=e;if(0===r.length)throw Ln(t);return r.reduce((e,t)=>a(ee(t,e))?t:e)}}),mo=(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)}),ho={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?ue(e):e.split(t);return r?a.map(oe):a}},vo=e=>null!==e&&"object"==typeof e,yo=e=>Array.isArray(e.values)&&e.values.some(vo)?[{severity:"error",parameter:"values",message:"a composite element renders as a placeholder, never as text — drill in, or join it explicitly"}]:[],go={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=>[...Mn(e),...yo(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"}):vo(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),ne(e)}).join(t)},bo=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}`},wo={type:"array",description:"The collection iterated over; a null input is a type error"},ko={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},$o={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},xo={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},jo={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:Q,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})=>Tn(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=k(t,zn(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 ka(`'${Oo(e)}' is missing (strictDataPaths)`,{code:s.missingDataPath});return null}},Oo=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),Po={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=>[...Rn(e),...Ao(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=ne(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},Ao=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=ne(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},Do=(e,t)=>new ka(`cannot convert ${q(e)} to ${t}`),So=/*#__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:Mn,evaluate:({values:e})=>Vn(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:Mn,evaluate:({values:e})=>Vn(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:ne(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new ka(`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:Mn,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Kn,Gn,Qn,Xn,Yn,Zn,to,ro,oo,ao,no,so,io,co,uo,po,/*#__PURE__*/fo("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/fo("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 ve(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=ne(e);vo(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?oe(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=le(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=ce(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("")}},ho,go,/*#__PURE__*/mo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/mo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/mo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",oe),{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:"any",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?bo(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=bo(r);if(void 0!==o)throw new ka(o);const s=e=>{try{return new RegExp(t,r+e)}catch(e){throw new ka(`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?ue(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:wo,as:ko,nullInputDefault:$o,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Fn,evaluate:({each:e})=>Wn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:wo,as:ko,nullInputDefault:$o,each:xo},positionalParams:["input","each"],returns:"array",validate:Fn,evaluate:async({input:e,each:t})=>{const r=await Wn(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:wo,as:ko,nullInputDefault:$o,each:xo,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:Fn,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:wo,as:ko,nullInputDefault:$o,each:xo},positionalParams:["input","each"],returns:"boolean",validate:Fn,evaluate:({each:e})=>Vn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:wo,as:ko,nullInputDefault:$o,each:xo},positionalParams:["input","each"],returns:"boolean",validate:Fn,evaluate:({each:e})=>Vn(e.settle(),!1)},jo,Po,{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 ka(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw Do(t,"number");case"string":if(Array.isArray(t)||e(t))throw new ka(`cannot convert ${q(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw Do(t,"string");return ne(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return _(t);case"array":return Array.isArray(t)?t:[t]}}}].map(xn),Co="3.0.0-preview.6",No=(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);Wo(r);const a=zo(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=Pr({operators:r.operators??[So],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{},removedFragments:new Set(Object.entries(t.fragments??{}).flatMap(([t,r])=>null===r&&e?.registry.fragments.has(t)?[`$${t}`]:[]))});return{options:r,evaluation:a,registry:o,compileCache:new mr({compile:e=>To(e,o),probe:e=>ye(e,o)})}},zo=e=>{const t={...e};return delete t.operators,delete t.fragments,t},To=(e,t)=>{const r=Ce(e,t);return Dt(r),r.hasNoCache&&Xt(r),r};class Eo{state;results;version=Co;constructor(e={}){this.state=No(null,e),this.results=new dn(ln(this.state.options.cache))}updateOptions(e={}){const t=No(this.state,e),r=ln(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,instanceDefaults:r}=e,a={name:t.name,category:t.category,description:t.description,parameters:hn(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.instanceNoCache=!0),Object.hasOwn(r,"fallback")&&(a.instanceFallback=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:mn(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:Vo(this.state.evaluation,t),a=To(e,this.state.registry),n=gn(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n}}getDependencies(e){return mn(Ce(e,this.state.registry).dependencies)}isEvaluable(e){const t=Ce(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return qo(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>To(e,r.registry))}compile(e){const{state:t}=this;return Io(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const qo=async(e,t,r,a,n,o)=>{const s=void 0===a?e:Vo(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=yn(l.depth,s.maxDepth);throw Uo(e,[e])}return r}const{artifact:c}=l;if(c.hasErrors||void 0!==s.maxDepth||void 0!==s.maxNodes){const e=[...vn(c,s),...c.issues.map(e=>e.issue)],t=e.find(e=>"error"===e.severity);if(void 0!==t)throw Uo(t,e)}const u=await rn(c,s,t);return!0===s.trace?u:u.result};let Mo;const Fo=(e,t)=>Mo?.(e,t);class Ro{#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,Mo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Vo(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 qo(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return mn(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#s??=To(this.#t,this.#n)}}const Io=(e,t,r,a,n)=>new Ro(e,t,r,a,n),Lo=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,trace:0})),Vo=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Lo.has(a))throw Jo(a);r??={...e},r[a]=n}}return void 0===r?e:(Wo(t),r)},Jo=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:[]}),Wo=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&&!Bo(r))throw new O({code:s.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},Bo=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Uo=(e,t)=>new O({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},issues:t});export{re as A,Q as E,Eo as F,kn as N,H as O,wn as R,L as a,U as b,V as c,J as d,R as e,jn as f,On as g,ka as h,Y as i,zn as j,q as k,xn as l,$n as m,Co as n,gn as o,Tn as p,ae as q,ne as r,Pe as s,ke as t,ee as u,Fo as v,So as w,me as x,$a as y,_ as z};
|
|
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};
|